coupon-select.js 1.94 KB
Component({
  properties: {
    show: {
      type: Boolean,
      value: false,
      observer: '_show'
    },
    coupons: {
      type: Array,
      value: []
    },
    selectedCode: {
      type: String,
      value: ''
    }
  },
  data: {
    chosenIdx: ''
  },
  methods: {
    confirm: function () {
      let item = this.data.coupons[this.data.chosenIdx];
      let code = item && item.coupon_code || '';
      let amount = item && item.coupon_value_str || '';

      this.triggerEvent('confirmselect', {code, amount})
    },
    cancel: function () {
      this.triggerEvent('cancel')
    },
    check: function (e) {
      let idx = e.currentTarget.dataset.idx;

      this.data.coupons.forEach((item, index) => {
        if (index !== idx && item.isChosen) {
          this.setData({
            [`coupons[${index}].isChosen`]: false
          });
        }
        if (index === idx) {
          this.setData({
            [`coupons[${idx}].isChosen`]: true
          });
        }
      });
      this.data.chosenIdx = idx;
    },
    uncheck: function (e) {
      let idx = e.currentTarget.dataset.idx;

      this.setData({
        [`coupons[${idx}].isChosen`]: false
      });
      this.data.chosenIdx = '';
    },
    _show: function (show) {
      if (show) {
        if (this.data.selectedCode) {
          this.data.coupons.forEach((item, index) => {
            if (item.coupon_code === this.data.selectedCode) {
              this.setData({
                [`coupons[${index}].isChosen`]: true
              });
              this.data.chosenIdx = index;
            } else {
              this.setData({
                [`coupons[${index}].isChosen`]: false
              });
            }
          });
        } else {
          this.data.coupons.forEach((item, index) => {
              this.setData({
                [`coupons[${index}].isChosen`]: false
              });
          });
          this.data.chosenIdx = '';
        }
      }
    }
  }
});