const util = require("../../../utils/util.js");
const app = getApp();
Component({
  options:{addGlobalClass: true},
  properties: {
    show: {
      type: Boolean,
      observer: function (newVal) {
        this.setData({ show: newVal,checkeduseCoin:false });
        if (this.data.show) this.getInfo();
      }
    },
    s1: {
      type: Number,
      observer: function (newVal) {
        this.data.initialSku.s1 = newVal;
        this.setData({ initialSku: this.data.initialSku });
      },
    },
    aid: {
      type: String,
      observer: function (val) {
        this.setData({ aid: val });
      }
    },
    atype: {
      type: Number,
      observer: function (newVal) {
        this.setData({ atype: newVal });
      }
    },
    recommender: {
      type: String,
      observer: function (newVal) {
        this.setData({ recommender: newVal });
      }
    },
    street: {
      type: String,
      observer: function (newVal) {
        this.setData({ street: newVal });
      }
    },
    qptype: {
      type: Number,
      observer: function (newVal) {
        this.setData({ qptype: newVal });
      }
    },
    createGroup: {
      type: Number,
      observer: function (newVal) {
        this.setData({ createGroup: newVal });
      }
    },
    groupid: {
      type: String,
      observer: function (newVal) {
        this.setData({ groupid: newVal });
      }
    },
    setMeals: {
      type: Object,
      observer: function (newVal) {
        this.data.sku.tree[0].k = newVal[0] || '选择场次';
        this.data.sku.tree[1].k = newVal[1] || '选择套餐';
        this.setData({ sku: this.data.sku });
      }
    },
    presellOpen: {
      type: Number,
      observer: function (newVal) {
        this.setData({ presellOpen: newVal });
      }
    },
    maxUserCoin: {
      type: Number,
      observer: function (newVal) {
        this.setData({ maxUserCoin: newVal });
      }
    },
  },
  data: {
    maxUserCoin:0,
    saleType:false,
    show: false,
    height:'',
    presellOpen:0,
    aid: '',
    atype: 0,
    qptype: 0,
    recommender:'',
    street:'',
    createGroup: 0,
    groupid: '',
    info: {},
    sku: {
      tree: [
        {
          k: '选择场次', // skuKeyName：规格类目名称
          v: []
        },
        {
          k: '选择套餐', // skuKeyName：规格类目名称
          v: []
        }
      ],
      price: '0.00', // 默认价格（单位元）
      stock_num: 0, // 商品总库存
      quota: 10,//限购，超过99为不限制购买
      minT: 1,
      maxT: 1,
      presellPrice:0.00,
    },
    initialSku: {
      s1: -1,
      s2: -1,
      selectedNum: 1,
      userCoin:0
    },
    checkeduseCoin:false
  },
  methods: {
    initialiSku(){
      let sku={
        tree: [{k: '选择场次',v: []},{k: '选择套餐',v: []}],
        price: '0.00', 
        stock_num: 0, 
        quota: 10,
        minT: 1,
        maxT: 1,
        presellPrice:0.00,
      };
      this.setData({sku})
    },
    checkboxChange(e){
      this.initialiSku()
      this.setData({checkeduseCoin:!this.data.checkeduseCoin})
      this.getInfo()
    },
    close(e) {
      this.triggerEvent("close", e.detail);
    },
    getInfo() {
      let that = this, initialSku = this.data.initialSku, s1Status = true, s2Status = true, s3Status = true;
      let params ={ 
        aid: that.data.aid,
      }
      if (this.data.checkeduseCoin) {
        params.useUserCoin=1
      }
      util.ajax({ 
        func: 'v2/article/payinfo', 
        data: params,
        load:false
      }, function (res) {
        if (res.code == 0) {
          let data = res.data.sessions;
          if (data && data.length > 0) {
            data.forEach((item, index) => {
              that.data.sku.tree[0].v[index] = { name: item.name, actnum: item.actnum, status: item.status,waitActNum:item.waitActNum};
              if (((item.actnum > 0 && item.status == 0) || (item.actnum <= 0 && item.waitActNum > 0 && item.status == 1 && that.presellOpen==0)) && s1Status) {
                that.data.initialSku.s1 = that.data.initialSku.s1 != -1 ? that.data.initialSku.s1 : index;
              }
              if (item.meals.length > 0 && ((item.actnum > 0 && item.status == 0) || (item.actnum <= 0 && item.waitActNum > 0 && item.status == 1)) && s1Status && index == that.data.initialSku.s1) {
                item.meals.forEach((it, i) => {
                  item.meals[i].name = it.policyName;
                  it.waitActNum = item.waitActNum;
                  // it.status = item.status;
                  that.data.sku.stock_num =(item.actnum <= 0 && item.waitActNum > 0 && item.status == 1)?it.waitActNum:it.actnum;
                  if ((it.actnum > 0 || (it.actnum <= 0 && it.waitActNum > 0)) && s2Status) {
                    that.data.initialSku.s2 = i;
                    that.data.initialSku.selectedNum = it.minT;
                    that.data.initialSku.userCoin = it.userCoin;
                    that.data.sku.price = it.price;
                    that.data.sku.presellPrice = it.presellPrice;
                    that.data.sku.minT = it.minT;
                    that.data.sku.maxT = it.maxT;
                    s2Status = false;
                  }
                });
                that.data.sku.tree[1].v = item.meals;
                s1Status = false;
              } else if (item.status != 0 && s2Status && s3Status) {
                item.meals.forEach((it, i) => {
                  it.waitActNum = item.waitActNum;
                  it.status = item.status;
                  item.meals[i].name = it.policyName;
                  item.meals[i].actnum = 0;
                });
                that.data.sku.tree[1].v = item.meals;
                that.data.sku.stock_num = item.meals[0].actnum;
                that.data.sku.price = item.meals[0].price;
                that.data.sku.presellPrice = item.meals[0].presellPrice;
                that.data.sku.minT = item.meals[0].minT;
                that.data.sku.maxT = item.meals[0].maxT;
                that.data.initialSku.selectedNum = item.meals[0].minT;
                s3Status = false;
              }
            });
            if (that.data.initialSku.s1 !=-1) {
              that.data.saleType=(data[that.data.initialSku.s1].actnum<=0 && data[that.data.initialSku.s1].waitActNum>0)?true:false;
            }
          }else{
            this.initialiSku()
          }
          res.data.sessions = data;
          that.setData({ info: res.data, sku: that.data.sku, initialSku: that.data.initialSku,saleType:that.data.saleType})
        } else {
          util.showTips(data.reason);
        }
      })
    },
    checkChange(e) {
      let data = e.currentTarget.dataset, that = this, s2Status = true;
      if (data.disabled) return false;
      if (data.index == 0) {
        this.data.initialSku.s1 = data.i;
        this.data.sku.tree[1].v = [];
        this.data.saleType=(this.data.info.sessions[this.data.initialSku.s1].actnum<=0 && this.data.info.sessions[this.data.initialSku.s1].waitActNum>0)?true:false;
        this.setData({saleType:this.data.saleType})
        this.data.info.sessions[this.data.initialSku.s1].meals.forEach((item, idx) => {
          item.name = item.policyName;
          if ((item.actnum > 0 || (item.actnum <= 0 && this.data.info.sessions[this.data.initialSku.s1].waitActNum > 0))  && s2Status) {
            console.log(item)
            that.data.initialSku.s2 = idx;
            that.data.initialSku.userCoin = item.userCoin;
            that.data.sku.stock_num = item.actnum>0?item.actnum:this.data.info.sessions[this.data.initialSku.s1].waitActNum;
            that.data.sku.price = item.price;
            that.data.sku.presellPrice = item.presellPrice;
            that.data.sku.minT = item.minT;
            that.data.sku.maxT = item.maxT;
            s2Status = false;
          }
          this.data.sku.tree[1].v[idx] = item;
        });
      } else {
        this.data.initialSku.s2 = data.i;
        this.data.sku.price = this.data.sku.tree[1].v[data.i].price;
        this.data.sku.presellPrice = this.data.sku.tree[1].v[data.i].presellPrice;
        this.data.sku.stock_num = this.data.info.sessions[this.data.initialSku.s1].actnum>0?this.data.info.sessions[this.data.initialSku.s1].actnum:this.data.info.sessions[this.data.initialSku.s1].waitActNum;
        this.data.sku.minT = this.data.sku.tree[1].v[data.i].minT;
        this.data.sku.maxT = this.data.sku.tree[1].v[data.i].maxT;
        this.data.initialSku.userCoin = this.data.sku.tree[1].v[data.i].userCoin;
      }
      this.data.initialSku.selectedNum = this.data.sku.minT;
      this.setData({ initialSku: this.data.initialSku, sku: this.data.sku });
    },
    quantity(e) {
      let type = e.currentTarget.dataset.type, val = e.detail.value;
      switch (type) {
        case 'minus':
          this.data.initialSku.selectedNum--;
          break;
        case 'plus':
          this.data.initialSku.selectedNum++;
          break;
        case 'modfiy':
          this.data.initialSku.selectedNum = val;
          break;
      }
      if (parseInt(this.data.initialSku.selectedNum) > this.data.sku.stock_num) {
        util.showTips("库存不足");
        this.data.initialSku.selectedNum = this.data.sku.stock_num;
      }
      if ((type == 'minus' || type == 'modfiy') && (parseInt(this.data.initialSku.selectedNum) < this.data.sku.minT || util.isEmpty(this.data.initialSku.selectedNum))) {
        util.showTips("至少选择" + this.data.sku.minT + "件");
        this.data.initialSku.selectedNum = this.data.sku.minT;
      }
      if ((type == 'plus' || type == 'modfiy') && (parseInt(this.data.initialSku.selectedNum) > this.data.sku.maxT)) {
        util.showTips("最大只能购买" + this.data.sku.maxT + "件");
        this.data.initialSku.selectedNum = this.data.sku.maxT;
      }
      this.setData({ initialSku: this.data.initialSku });
    },
    sumbit(e) {
      let type=e.currentTarget.dataset.type,initialSku = this.data.initialSku;
      if (initialSku.s1 == -1) {
        util.showTips('请' + this.data.sku.tree[0].k);
        return false;
      }
      if (initialSku.s2 == -1) {
        util.showTips('请' + this.data.sku.tree[1].k);
        return false;
      }
      wx.reportAnalytics('active_enroll', {
        aid: this.data.aid,
        title: this.data.title,
      });
      if (util.isObjEmpty(app.globalData.userInfo)) {
        let that = this
        // 静默登录
        util.silentLogin().then(res => {
          that.toBuy(type)
        })
        return false;
      }
      this.toBuy(type)
    },
    toBuy(type) {
      let initialSku = this.data.initialSku
      if (type) {
        let data = {};
        data.aid = this.data.aid;
        data.atype = this.data.atype;
        // data.createGroup=this.data.createGroup;
        // data.groupid=this.data.groupid;
        data.createGroup = 0;
        data.groupid = '';
        data.qptype = this.data.qptype;
        data.sessionsIndex = this.data.sessionInfo[this.data.checkSession].sid;
        data.mealsIndex = this.data.mealsInfo[this.data.checkMeals].pid;
        data.quantity = initialSku.selectedNum;
        data.recommender = this.data.recommender;
        data.military = this.data.military ? 1 : 0,
          data.street = this.data.street;
        data.familyCommittee = this.data.familyCommittee;
        let age = this.data.mealsInfo[this.data.checkMeals].minAge + '-' + this.data.mealsInfo[this.data.checkMeals].maxAge;
        data.ageLimit = this.data.military == 1 ? age : this.data.ageLimit;
        data.presellOpen = this.data.presellOpen;
        data.btype = (this.data.presellOpen == 0 && this.data.mealsInfo[this.data.checkMeals].actnum <= 0 && this.data.mealsInfo[this.data.checkMeals].waitActNum > 0) ? 3 : -1;
        this.triggerEvent('alternateEmit', data)
      } else {
        let data = [];
        data.push('aid=' + this.data.aid)
        data.push('atype=' + this.data.atype)
        data.push('createGroup=' + this.data.createGroup)
        data.push('qptype=' + this.data.qptype)
        data.push('groupid=' + this.data.groupid)
        data.push('sessionsIndex=' + this.data.sessionInfo[this.data.checkSession].sid)
        data.push('mealsIndex=' + this.data.mealsInfo[this.data.checkMeals].pid)
        data.push('military=' + (this.data.military ? 1 : 0))
        data.push('quantity=' + initialSku.selectedNum)
        let age = this.data.mealsInfo[this.data.checkMeals].minAge + '-' + this.data.mealsInfo[this.data.checkMeals].maxAge;
        data.push('ageLimit=' + (this.data.military == 1 ? age : this.data.ageLimit))
        data.push('recommender=' + this.data.recommender)
        data.push('street=' + this.data.street)
        data.push('familyCommittee=' + this.data.familyCommittee)
        data.push('presellOpen=' + this.data.presellOpen)
        data.push('btype=' + ((this.data.presellOpen == 0 && this.data.mealsInfo[this.data.checkMeals].actNum <= 0 && this.data.mealsInfo[this.data.checkMeals].waitActNum > 0) ? 3 : -1))
        wx.navigateTo({
          url: '/pages/product/buy/index?' + data.join('&')
        })
      }
    },
  }
})
