const _Http = getApp().globalData.http,
  currency = require("../../utils/currency"),
  CNY = sum => currency(sum, {
    symbol: "￥",
    precision: 2
  }).format();
let downCount = {};
import {
  getCustomText
} from "../../utils/customItemType";
Page({
  data: {
    list: [],
    results: [], //选中结果
    classList: [], //生成订单时所选
    sum: 0, //价格合
    hidePrice: wx.getStorageSync('hidePrice')
  },
  onLoad() {
    this.getList()
  },
  /* 打开设置定制项 */
  customization(e) {
    const {
      item
    } = e.target.dataset;
    if (item) this.selectComponent("#Custom").onClick(item)
  },
  onShow() {
    //修改定制项产品
    getApp().globalData.customizedProduct = (item, custom) => {
      let obj = {
        "width": 0,
        "length": 0,
      }
      for (const key in custom) {
        let name = key.replace("favorites", '')
        obj[name] = custom[key]
      }
      return new Promise((resolve) => {
        _Http.basic({
          "id": 20231121143403,
          "content": {
            "itemid": item.itemid,
            "sa_favoritesid": item.sa_favoritesid,
            "favoritesqty": item.favoritesqty,
            "qty": item.favoritesqty,
            ...obj,
            ...custom,
            "iscollection": true
          },
        }).then(res => {
          console.log("修改定制", res)
          wx.showToast({
            title: res.msg != '成功' ? res.msg : '修改成功',
            icon: "none"
          });
          this.getList()
          resolve(true)
        })
      })
    }
  },
  /* 获取列表 */
  getList() {
    _Http.basic({
      "id": 20231121145103,
      "content": {
        nocache: true,
        istool: 0,
        "pageNumber": 1,
        "pageSize": getApp().globalData.favoriteCount + 5,
        "where": {
          "condition": ""
        }
      }
    }).then(res => {
      console.log('收藏夹列表', res)
      this.selectComponent('#ListBox').RefreshToComplete();
      this.selectComponent("#ListBox").setHeight(".head", this);
      if (res.msg != '成功') return wx.showToast({
        title: res.msg,
        icon: "none"
      })
      this.setData({
        list: res.data.map(v => {
          v.showPrice = CNY(v.gradeprice)
          if (v.iscustomsize) v.customText = getCustomText(v, 'favorites');
          return v
        })
      });
      if (wx.getStorageSync('favorites')) {
        this.setData({
          ...wx.getStorageSync('favorites')
        });
        this.computeSum();
      }
    })
  },
  /* 选中单品 */
  clickBut(e) {
    this.data.classList.length >= 2 ? wx.showToast({
      title: '请选择订单领域(订单只允许同领域的商品)',
      icon: "none",
      duration: 3000
    }) : this[e.target.id](0);
  },
  /* 是否选择全部 */
  setIsAll() {
    let isAll = this.data.isAll;
    this.setData({
      results: isAll ? [] : this.data.list.map(v => v.sa_favoritesid),
      isAll: !isAll
    })
    this.computeSum();
  },
  /* 计算总价/产品领域分类 */
  computeSum() {
    let results = this.data.results,
      sum = 0,
      classList = [];
    if (results.length) results = results.filter(v => {
      let item = this.data.list.find(va => va.sa_favoritesid == v);
      if (item) {
        sum = currency(sum).add(currency(item.favoritesqty).multiply(item.gradeprice)).value;
        /* 领域分类 */
        let index = classList.findIndex(value => value.type == item.tradefield[0].tradefield);
        if (index == -1) {
          classList.push({
            type: item.tradefield[0].tradefield,
            list: [item],
            name: item.tradefield[0].tradefield + "(1件商品)"
          })
        } else {
          classList[index].list.push(item)
          classList[index].name = classList[index].type + `(${classList[index].list.length}件商品)`
        }
      };
      return item
    });
    wx.setStorageSync('shopping', {
      results
    })
    console.log("计算价格results", results)
    this.setData({
      sum: CNY(sum),
      isAll: results.length == this.data.list.length,
      results,
      classList
    });
  },
  /* 提交 */
  submit(e) {
    this[e.target.id](e.detail.value)
  },
  /* 处理生成订单 */
  handleSubmit(index) {
    let data = this.data.classList[index];
    wx.showLoading({
      title: '生成中...',
    })
    _Http.basic({
      "id": 20221128183202,
      "content": {
        istool: 0,
        type: "标准订单",
        "tradefield": data.type, //必选
        sa_brandid: this.data.sa_brandid,
        "items": data.list.map(v => {
          return {
            "sa_orderitemsid": 0,
            "itemid": v.itemid,
            "qty": v.favoritesqty,
            "sa_brandid": v.brand.length ? v.brand[0].sa_brandid : this.data.sa_brandid || 0,
            width: v.favoriteswidth || 0,
            length: v.favoriteslength || 0,
          }
        })
      }
    }).then(res => {
      wx.hideLoading()
      console.log("转化订单", res)
      if (res.msg != '成功') return wx.showToast({
        title: res.msg,
        icon: "none"
      });
      this.setData({
        results: [],
        isAll: false
      })
      wx.showModal({
        title: '提示',
        content: '生成成功!是否立即前往',
        complete: (s) => {
          if (s.confirm) wx.navigateTo({
            url: '/packageA/orderForm/detail?id=' + res.data.sa_orderid,
          })
        }
      });
    })
  },
  addToShoppingCart(index) {
    let data = this.data.classList[index];
    wx.showLoading({
      title: '处理中...',
    })
    _Http.basic({
      "id": 20231024110003,
      "content": {
        "items": data.list.map(v => {
          return {
            "sa_brandid": v.brand.length ? v.brand[0].sa_brandid : 0,
            "itemid": v.itemid,
            "qty": v.favoritesqty,
            "itemno": v.itemno,
            "tradefield": data.type,
            "length": v.favoriteslength || 0,
            "width": v.favoriteswidth || 0
          }
        })
      }
    }).then(res => {
      wx.hideLoading()
      console.log("加入购物车", res)
      wx.showToast({
        title: res.msg != '成功' ? res.msg : "加入成功",
        icon: "none"
      });
      if (res.msg != '成功') return;
      this.setData({
        results: [],
        isAll: false
      })
    })
  },
  /* 切换选中项 */
  changeResults(e, my = false) {
    const {
      item
    } = my ? e : e.currentTarget.dataset;
    let results = this.data.results,
      sa_brandid = this.data.sa_brandid;
    console.log(item)
    if (sa_brandid && sa_brandid != item.sa_brandid) return;
    if (results.length == 0) {
      results.push(item.sa_favoritesid);
      sa_brandid = item.sa_brandid;
    } else {
      let index = results.findIndex(v => v == item.sa_favoritesid)
      if (index == -1) {
        results.push(item.sa_favoritesid);
      } else {
        results.splice(index, 1);
        if (results.length == 0) sa_brandid = null;
      }
    };
    this.setData({
      results,
      sa_brandid
    })
    this.computeSum();
  },
  /* 删除产品 */
  deteleItem(e) {
    const {
      item
    } = e.currentTarget.dataset;
    wx.showModal({
      title: '提示',
      content: `是否确认删除${item.itemname}?`,
      complete: ({
        confirm
      }) => {
        e.detail.instance.close();
        if (confirm) _Http.basic({
          "id": 20231121143403,
          "content": {
            "itemid": item.itemid,
            "iscollection": false
          }
        }).then(res => {
          wx.showToast({
            title: res.msg != '成功' ? res.msg : "删除成功",
            icon: "none"
          });
          if (res.msg != '成功') return;
          this.getList(true)
          getApp().globalData.getFavoriteCount()
        })
      }
    })
  },
  /* 输入框失去焦点调整数量 */
  inputBlur(e) {
    const {
      index
    } = e.currentTarget.dataset;
    let item = this.data.list[index];
    let favoritesqty = 0;
    if (item.orderminqty > e.detail.value) {
      wx.showToast({
        title: '输入数量低于最低起订量！',
        icon: "none"
      })
      favoritesqty = item.orderminqty;
    } else if (item.orderminqty < e.detail.value) {
      var currencyRounding = value => currency(value, {
        increment: item.orderaddqty
      });
      favoritesqty = currency(currencyRounding(currency(e.detail.value).subtract(item.orderminqty)).format()).add(item.orderminqty).value;

    } else {
      favoritesqty = e.detail.value;
    }
    this.setData({
      [`list[${index}].favoritesqty`]: 0
    });
    this.setData({
      [`list[${index}].favoritesqty`]: favoritesqty
    });
    this.handleChangeQty(item, index)
  },
  /* 步进器调整数量 */
  stepperChange(e) {
    const {
      index
    } = e.currentTarget.dataset;
    let item = this.data.list[index];
    if (e.type == 'plus') {
      item.favoritesqty += item.orderaddqty
    } else {
      item.favoritesqty -= item.orderaddqty
    }
    this.setData({
      [`list[${index}]`]: item
    })
    this.handleChangeQty(item, index)
  },
  handleChangeQty(item, index) {
    this.computeSum();
    clearTimeout(downCount['count' + index])
    downCount['count' + index] = setTimeout(() => {
      _Http.basic({
        "id": 20231121143403,
        "content": {
          "sa_favoritesid": item.sa_favoritesid,
          "itemid": item.itemid,
          "favoritesqty": item.favoritesqty,
          "qty": item.favoritesqty,
          "width": item.width || 0,
          "length": item.length || 0,
          "iscollection": true
        },
      }, false).then(res => {
        console.log("修改数量", res)
      })
    }, 1000)
  }
})