import currency from "../../../utils/currency";
const _Http = getApp().globalData.http,
  file = require("../../../utils/FormatTheAttachment"),
  {
    getItem
  } = require("../selectProduct/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,
    privacyFieldC: [],
    packageList: [],
    condition: "",
    searchList: [],
    dialogShow: false,
    submitQty: 1,
    packagetypemxrows: [],
    modification: false, //是否为修改套餐数量
  },
  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;
      }
      console.log(params)
      _Http.basic({
        id: 2024080614131103,
        content: {
          sa_promotionid: params.content.sa_promotionid,
          packagetype: params.content.packagetype
        }
      }).then(res => {
        console.log('套餐分类', res)
        if (res.msg != '成功') return wx.showToast({
          title: res.msg,
          icon: "none"
        })
        let packageList = []
        try {
          let packagetypemxrows = [];
          if (options.packagetypemxrows) {
            this.data.packagetypemxrows = JSON.parse(options.packagetypemxrows);
            packagetypemxrows = this.data.packagetypemxrows.map(v => v.packagetypemx);
          }
          packageList = res.data.find(v => v.value == params.content.packagetype).subvalues;
          if (packagetypemxrows.length != 0) {
            if (options.butText == '调整套数') {
              packageList = packagetypemxrows
              this.setData({
                "submitQty": this.data.packagetypemxrows[0].packagetypeqty
              })
            } else {
              packageList = packageList.filter(v => !packagetypemxrows.includes(v))
            }
          }
        } catch (error) {
          console.error("error", error)
        }
        let getListPa = "";
        if (options.getListPa) {
          getListPa = JSON.parse(options.getListPa);
          getListPa.content.pageNumber = 1;
          getListPa.content.pageSize = 9999;
          getListPa.content.onlyquery = 1;
          getListPa.content.where = {
            packagetypemx: ''
          }
          delete getListPa.content.pageTotal;
        }
        if (packageList.length) params.content.where.packagetypemx = packageList[0]
        this.setData({
          params,
          getListPa,
          butText: options.butText || '生成订单',
          packageList
        });
        this.getList()
        this.selectComponent("#ListBox").setHeight(".search", this);
      })
      this.setData({
        params,
        butText: options.butText || '生成订单'
      });
    };
    try {
      let privacyFieldC = wx.getStorageSync('auth').wdiscounts.forms.wdiscounts.formcols.map(v => v.title);
      this.setData({
        privacyFieldC
      })
    } catch (error) {
      console.error(error)
    }
    this.setData({
      idname: options.idname || this.data.idname
    });
  },
  customization(e) {
    let {
      item
    } = e.target.dataset;
    this.bindChangeFun();
    if (item) this.selectComponent("#Custom").onClick(item)
  },
  bindChangeFun() {
    getApp().globalData.customizedProduct = function (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.itemid == item.itemid),
          i = this.data.searchList.findIndex(v => v.itemid == item.itemid);
        item.CompleteCustomization = true;
        if (index != -1) this.setData({
          [`list[${index}]`]: item
        })
        if (i != -1) this.setData({
          [`searchList[${i}]`]: item,
        })
        resolve(true)
      })
    }.bind(this)
  },
  async getList(init = false) {
    //init 用于初始化分页
    if (init.detail != undefined) init = init.detail;
    let params = this.data.params;
    if (init) params.content.pageNumber = 1
    params.content.pageSize = 9999;
    if (params.content.pageNumber > params.content.pageTotal) return;
    let res = {},
      CompleteCustomization = false,
      modification = false;
    if (params.content.where.packagetypemx == '') return this.setData({
      loading: false
    })
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    if (this.data.getListPa) {
      this.data.getListPa.content.where.packagetypemx = params.content.where.packagetypemx;
      res = await _Http.basic(this.data.getListPa);
      CompleteCustomization = true;
      modification = true;
      if (!res.data.length) {
        res = await _Http.basic(params);
        CompleteCustomization = false;
        modification = false;
      }
    } else {
      res = await _Http.basic(params);
    }
    wx.hideLoading()
    console.log("选择产品列表", res)
    this.selectComponent('#ListBox').RefreshToComplete();
    this.selectComponent("#ListBox").setHeight(".search", this);
    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.CompleteCustomization = CompleteCustomization;
      }
      return value;
    })
    this.setData({
      'params.content.pageNumber': res.pageNumber + 1,
      'params.content.pageTotal': res.pageTotal,
      'params.content.total': res.total,
      modification,
      list: res.pageNumber == 1 ? res.data : this.data.list.concat(res.data),
      loading: false
    })
    this.handleSearch()
  },
  tabsChange(e) {
    this.setData({
      "params.content.where.packagetypemx": e.detail.name
    })
    try {
      this.setData({
        "submitQty": this.data.packagetypemxrows.find(v => v.packagetypemx == e.detail.name).packagetypeqty || 1
      })
    } catch (error) {

    }
    this.getList(true)
  },
  changeQtySte({
    detail
  }) {
    if (detail == '-' || detail <= 0) detail = 1;
    this.setData({
      submitQty: detail
    })
  },
  /* 提交 */
  submit() {
    const customsize = this.data.list.find(v => (v.iscustomsize && !v.CompleteCustomization));
    let that = this;
    if (customsize) {
      return wx.showModal({
        title: '提示',
        content: `请先完成"${customsize.itemname}"产品的定制化信息`,
        // confirmText: "查看产品",
        showCancel: false,
        complete: ({
          confirm
        }) => {
          if (confirm) {
            /* that.setData({
              condition: customsize.itemname
            })
            that.handleSearch() */
          }
        }
      })
    }

    /* if (this.data.modification) {
      wx.showModal({
        title: '提示',
        content: '您已添加过此套餐，是否需要重新调整套数？',
        confirmText: '是',
        cancelText: "否",
        complete: ({
          confirm
        }) => {
          if (confirm) handle()
        }
      })
    } else {
      handle()
    } */
    handle()

    function handle() {
      that.setData({
        dialogShow: true
      })
      that.selectComponent("#Dialog").data.beforeClose = (action) => new Promise((resolve) => {
        if (action == 'cancel') {
          resolve()
          that.setData({
            dialogShow: false
          })
          return;
        }
        getApp().globalData.handleSelect && getApp().globalData.handleSelect({
          list: that.data.list.map(v => {
            v.qty = v.qty * that.data.submitQty;
            return v
          })
        }).then(res => {
          resolve()
          that.setData({
            dialogShow: false
          })
        })
      });
    }

  },
  /* 预览图片 */
  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
  }) {
    this.data.condition = detail;
    this.handleSearch()
  },
  /* 取消搜索 */
  onClear() {
    this.data.condition = '';
    this.handleSearch()
  },
  handleSearch() {
    let searchList = this.data.list;
    if (this.data.condition.length) searchList = searchList.filter(v => {
      return ['itemname', 'itemno', 'standards', 'model', 'spec'].some(s => {
        try {
          return v[s].includes(this.data.condition)
        } catch (error) {
          return false
        }
      })
    })
    this.setData({
      searchList
    })
  },
  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;
  }
})