import {
  getCustomItems
} from "../../../../../utils/customItemType";

Component({
  properties: {
    topHei: {
      type: String,
      value: "20rpx"
    },
    onChange: {
      type: Function
    }
  },
  options: {
    multipleSlots: true
  },
  externalClasses: ["external-custom-box", "external-custom-label", "external-custom-stepper-box", "external-explain", "external-active", "external-custom-option"],
  data: {
    list: []
  },
  methods: {
    init(data, prefix = '') {
      return new Promise((resolve) => {
        getCustomItems(data, prefix).then(list => {
          this.setData({
            list: list.map(v => {
              if (v.type == '可选' && v.rowsdetail.length == 1) {
                v.value = v.rowsdetail[0].num
              }
              return v
            })
          });
          this.getResult();
          resolve(list.length);
        });
      });
    },
    onOption(e) {
      const {
        index,
        value
      } = e.currentTarget.dataset;
      if (this.data.list[index].value == value) return;
      this.setData({
        [`list[${index}].value`]: value
      });
      this.getResult();
    },
    getResult(isSubmit = false) {
      let obj = {};
      let breakOff = false;
      this.data.list.filter(v => {
        if (breakOff) return;
        if (v.type == '自定义') {
          if (!v.value) v.value = 0;
        }
        obj[v.key] = v.value || '';
        if (isSubmit && !obj[v.key]) {
          wx.showToast({
            title: `请完成定制"${v.label}"选项`,
            icon: "none"
          })
          breakOff = true;
        } else if (v.tips) {
          wx.showToast({
            title: v.tips,
            icon: "none"
          })
          breakOff = true;
        }
      })
      this.triggerEvent("onChange", breakOff ? false : obj)
      return breakOff ? false : obj
    },
    valueChange(e) {
      const {
        index,
        item
      } = e.currentTarget.dataset;
      wx.hideToast()
      item.tips = '';
      item.value = e.detail.value;
      if (item.decimalplaces && item.value.includes(".") && item.value.split(".")[1].length > item.decimalplaces) item.tips = `自定义${item.label}仅允许${item.decimalplaces}位小数！`
      if (item.value > item.max) {
        item.tips = `自定义${item.label}超出可选范围！`
        wx.showToast({
          title: item.tips,
          icon: "none"
        })
      }
      if (item.value < item.min) item.tips = `自定义${item.label}少于可选范围！`;
      this.setData({
        [`list[${index}]`]: item
      })
    },
    valueBlur(e) {
      const {
        index,
        item
      } = e.currentTarget.dataset;
      if (item.tips) wx.showToast({
        title: item.tips,
        icon: "none"
      })
    }
  }
})