import currency from "../../../utils/currency";
const _Http = getApp().globalData.http,
  file = require("../../../utils/FormatTheAttachment"),
  {
    getItem
  } = require("./calculatePrice");
import {
  getCustomText
} from "../../../utils/customItemType";

Page({
  data: {
    loading: true,
    params: {}, //请求体
    result: [], //返回结果
    idname: "itemid", //idkey
    showName: "itemname",
    newPrice: "price",
    oldPrice: "oldprice",
    resultList: [],
    sa_brandid: null,
  },
  onLoad(options) {
    if (options.params) {
      let params = JSON.parse(options.params);
      if (!params.content.pageNumber || !params.content.pageTotal) {
        params.content.pageNumber = 1;
        params.content.pageTotal = 1;
      }
      this.setData({
        params,
        butText: options.butText || '生成订单'
      });
    };
    this.setData({
      idname: options.idname || this.data.idname
    });
    this.getList()
    getApp().globalData.customizedProduct = (item, custom) => {
      item = getItem(getItem(Object.assign(item, custom)), 'newOldPrice', 'oldprice');
      item.customText = getCustomText(item);

      return new Promise((resolve) => {
        let index = this.data.list.findIndex(v => v[this.data.idname] == item[this.data.idname]),
          resultList = this.data.resultList,
          result = this.data.result;
        if (index != -1) this.data.list[index] = item;
        let i = resultList.findIndex(v => v[this.data.idname] == item[this.data.idname]);
        if (item.pitchOn) {
          if (i == -1) {
            resultList.push(item);
            result.push(item[this.data.idname])
          } else {
            resultList[i] = item;
          }
        } else {
          resultList[i] = item;
        }
        this.setData({
          list: this.data.list,
          result,
          resultList
        })
        resolve(true)
      })
    }
  },
  onShow() {
    this.getCollectCount()
  },
  getCollectCount() {
    return _Http.basic({
      "id": 20220927093202,
      "content": {
        sa_promotionid: this.data.params.content.sa_promotionid
      }
    }).then(res => {
      console.log("促销购物车数量", res.data)
      this.selectComponent("#Footer").setData({
        badge: res.data.num || 0
      })
    });
  },
  updateCart({
    detail
  }) {
    if (detail == "toindex") {
      wx.navigateTo({
        url: `/packageA/activity/selectProduct/cart/index?data=${
          JSON.stringify({
            "sa_brandid": this.data.params.content.sa_brandid,
            "sa_promotionid": this.data.params.content.sa_promotionid,
          })
        }`,
      })
    } else if (detail == "submit") {
      this.submit()
    } else {
      _Http.basic({
        "id": 20231024110003,
        "content": {
          sa_promotionid: this.data.params.content.sa_promotionid,
          items: this.data.resultList.map(v => {
            return {
              "sa_brandid": this.data.params.content.sa_brandid,
              "sa_promotionid": this.data.params.content.sa_promotionid,
              "itemid": v.itemid,
              "qty": v.qty,
              "itemno": v.itemno,
              "tradefield": v.tradefield.map(s => s.tradefield).join(","),
              sa_promotion_itemsid: v.sa_promotion_itemsid,
              "width": v.width || 0,
              "length": v.length || 0,
            }
          })
        },
      }).then(res => {
        console.log("批量添加购物车", res)
        wx.showToast({
          title: res.msg == '成功' ? '添加成功' : res.msg,
          icon: "none"
        })
        if (res.msg == '成功') {
          this.setData({
            result: [],
            resultList: [],
          })
          this.getCollectCount();
        }
      })
    }
  },
  customization(e) {
    let {
      item
    } = e.target.dataset;
    item.pitchOn = false;
    if (item) this.selectComponent("#Custom").onClick(item)
  },
  getList(init = false) {
    //init 用于初始化分页
    if (init.detail != undefined) init = init.detail;
    let params = this.data.params;
    if (init) params.content.pageNumber = 1
    if (params.content.pageNumber > params.content.pageTotal) return;
    _Http.basic(params).then(res => {
      console.log("选择产品列表", res)
      this.selectComponent('#ListBox').RefreshToComplete();
      if (res.msg != '成功') return wx.showToast({
        title: res.msg,
        icon: "none"
      })
      const CNY = num => currency(num, {
        symbol: "￥",
        precision: 2
      }).format();
      let newPrice = this.data.newPrice,
        oldPrice = this.data.oldPrice;
      res.data = res.data.map(value => {
        if (value.attinfos.length != 0) {
          value.attinfos = file.fileList(value.attinfos)
          let image = value.attinfos.find(v => v.fileType == "image");
          if (image) {
            try {
              value.cover = image.subfiles.find(v => v.type == "thumbnail").url;
            } catch (error) {
              value.cover = image.url;
            }
          }
        }
        if (value.islimit == 0) value.groupqty = 0;
        if (newPrice) value.newPrice = CNY(value[newPrice] || 0);
        if (oldPrice) value.oldPrice = CNY(value[oldPrice] || 0);
        //value.orderminqty = value.packageqty || value.orderminqty; 起订量优先取包装数量
        if (!value.saledqty) value.saledqty = 0;
        value.maxQty = value.groupqty == 0 ? "" : value.groupqty - value.saledqty; //有限购 设置最高可订购数量
        value.qty = value.orderminqty;

        if (value.iscustomsize) {
          value.customText = getCustomText(value);
          value.pitchOn = false;
        }

        return value;
      })
      this.setData({
        'params.content.pageNumber': res.pageNumber + 1,
        'params.content.pageTotal': res.pageTotal,
        'params.content.total': res.total,
        list: res.pageNumber == 1 ? res.data : this.data.list.concat(res.data),
        loading: false
      })
    })
  },
  /* 选中 */
  changeResult(e) {
    let {
      id,
      item
    } = e.currentTarget.dataset, result = this.data.result, resultList = this.data.resultList;
    if (this.data.radio) {
      result = [id];
      resultList = [item]
    } else {
      let isAdd = result.some(v => v == id);
      if (!isAdd) {
        if (item.iscustomsize == 1) {
          if ((item.widthschemeid && !item.width) || (item.lengthschemeid && !item.length)) {
            item.pitchOn = true;
            if (item) this.selectComponent("#Custom").onClick(item)
          } else {
            result.push(id)
            resultList.push(item)
          }
        } else {
          result.push(id)
          resultList.push(item)
        }
      } else {
        result = result.filter(v => v != id)
        resultList = resultList.filter(v => v[this.data.idname] != id)
      }
    }
    this.setData({
      result,
      resultList
    });
  },
  /* 提交 */
  submit() {
    let result = this.data.result,
      resultList = this.data.resultList,
      obj = {
        result,
        list: resultList,
        value: [result.map(v => {
          let data = this.data.list.find(value => value[this.data.idname] == v);
          return data ? data[this.data.showName] : ""
        }), result]
      }
    getApp().globalData.handleSelect && getApp().globalData.handleSelect(obj)
  },
  /* 预览图片 */
  viewImage(e) {
    const {
      file
    } = e.currentTarget.dataset;
    if (file.length) wx.previewMedia({
      sources: file.filter(value => ['image', 'vadio'].includes(value.fileType)).map(v => {
        return {
          url: v.url,
          type: v.fileType
        }
      }),
      current: 0,
      showmenu: true
    })
  },
  /* 开始搜索 */
  startSearch({
    detail
  }) {
    let condition = this.data.content ? this.data.content.where.condition : this.data.params.content.where.condition;
    if (detail == condition) return;
    this.setData({
      'content.where.condition': detail,
      'params.content.where.condition': detail
    });
    this.getList(true);
  },
  /* 取消搜索 */
  onClear() {
    this.setData({
      'content.where.condition': "",
      'params.content.where.condition': ""
    });
    this.getList(true);
  },
  onReady() {
    this.selectComponent("#ListBox").setHeight(".search", this);
  },
  /* 步进器输入框失去焦点 */
  inputBlur(e) {
    const {
      index
    } = e.currentTarget.dataset;
    let item = this.data.list[index];
    let qty = 0;
    if (item.orderminqty > e.detail.value) {
      wx.showToast({
        title: '输入数量低于最低起订量！',
        icon: "none"
      })
      qty = item.orderminqty;
    } else if (item.orderminqty < e.detail.value) {
      var currencyRounding = value => currency(value, {
        increment: item.orderaddqty
      });
      qty = currency(currencyRounding(currency(e.detail.value).subtract(item.orderminqty)).format()).add(item.orderminqty).value;

    } else {
      qty = e.detail.value;
    }
    this.setData({
      [`list[${index}].qty`]: 0
    });
    this.setData({
      [`list[${index}].qty`]: qty
    });
    let i = this.data.resultList.findIndex(v => v.itemid == item.itemid);
    if (i !== -1) this.data.resultList[i].qty = qty;
  },
  stepperChange(e) {
    const {
      index
    } = e.currentTarget.dataset;
    let item = this.data.list[index];
    if (e.type == 'plus') {
      item.qty += (item.orderaddqty) - 0
    } else {
      item.qty -= item.orderaddqty
    }
    this.setData({
      [`list[${index}]`]: item
    })
    let i = this.data.resultList.findIndex(v => v.itemid == item.itemid);
    if (i !== -1) this.data.resultList[i] = item;
  },
  onUnload() {
    //回收数据
    getApp().globalData.handleSelect = null;
  }
})