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
          });
          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) {
      let obj = {};
      let breakOff = false;
      this.data.list.filter(v => {
        if (breakOff) return;
        if (v.type == '自定义') {
          if (!v.value) v.value = 0;
          if (v.value < v.min) v.value = v.min;
        }
        obj[v.key] = v.value || '';
        if (isSubmit && !obj[v.key]) {
          wx.showToast({
            title: `请完成定制"${v.label}"选项`,
            icon: "none"
          })
          breakOff = true;
        }
      })
      this.triggerEvent("onChange", breakOff ? false : obj)
      return breakOff ? false : obj
    },
    /* 定制步进器 */
    changeStepper(e) {
      const {
        index,
        item
      } = e.currentTarget.dataset;
      if (!item.value) item.value = 0;
      if (e.type == 'plus') {
        item.value += 1
      } else if (e.type == 'minus') {
        item.value -= 1
      } else {
        item.value = (e.detail.value - 0).toFixed(item.decimalplaces);
      }
      item.value = item.value - 0;
      if (item.value > item.max) item.value = item.max;
      if (item.value < item.min) item.value = item.min;
      this.setData({
        [`list[${index}]`]: item
      })
      this.getResult();
    },
  }
})