var app = getApp();

Component({
  properties: {
    couponRefresh: {
      type: Boolean,
      value: false,
      observer: function (t) {
        if(t) this.getCoupon();
      }
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    quan: []
  },

  attached() {
    // this.getCoupon();
  },

  /**
   * 组件的方法列表
   */
  methods: {
    getCoupon: function(){
      let that = this;
      let token = wx.getStorageSync('token');
      app.util.request({
        url: 'entry/wxapp/index',
        data: { controller: 'goods.get_seller_quan', token },
        dataType: 'json',
        success: function (res) {
          let list = res.data.quan_list;
          let hasCoupon = false;
          if (Object.prototype.toString.call(list) == '[object Object]' && Object.keys(list).length>0) hasCoupon = true;
          if (Object.prototype.toString.call(list) == '[object Array]' && list.length > 0) hasCoupon = true;
          that.setData({
            quan: res.data.quan_list || [],
            hasCoupon
          })
        }
      });
    },
    receiveCoupon: function (event) {
      let quan_id = event.currentTarget.dataset.quan_id;
      var token = wx.getStorageSync('token');
      var quan_list = this.data.quan;
      var that = this;

      app.util.request({
        url: 'entry/wxapp/index',
        data: { controller: 'goods.getQuan', token, quan_id },
        dataType: 'json',
        success: function (msg) {
          //1 被抢光了 2 已领过  3  领取成功
          if (msg.data.code == 1) {
            wx.showToast({
              title: '被抢光了',
              icon: 'none'
            })
          } else if (msg.data.code == 2) {
            wx.showToast({
              title: '已领取',
              icon: 'none'
            })
            var new_quan = [];
            for (var i in quan_list) {
              if (quan_list[i].id == quan_id) quan_list[i].is_get = 1;
              new_quan.push(quan_list[i]);
            }
            that.setData({ quan: new_quan })
          }
          else if (msg.data.code == 3) {
            var new_quan = [];
            for (var i in quan_list) {
              if (quan_list[i].id == quan_id) quan_list[i].is_get = 1;
              new_quan.push(quan_list[i]);
            }
            that.setData({ quan: new_quan })
            wx.showToast({
              title: '领取成功',
            })
          }
          else if (msg.data.code == 4) {
            // 未登录
          }
        }
      })
    }
  }
})
