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.getCalendarInfo()
        }
      }
    },
    military: { //是否为军事营 1-是 0-否
      type: Number,
      value: 0,
      observer: function (newVal) {
        this.setData({ military: newVal });
      },
    },
    ageLimit: { //活动年龄限制
      type: String,
      value: '',
      observer: function (newVal) {
        this.setData({ ageLimit: newVal });
      },
    },
    s1: {
      type: Number,
      observer: function (newVal) {
        this.data.initialSku.s1 = (newVal == '' || newVal == 'undefined') ? -1 : newVal;
        this.setData({ initialSku: this.data.initialSku });
      },
    },
    s2: {
      type: String,
      observer: function (newVal) {
        this.data.initialSku.s2 = (newVal == '' || newVal == 'undefined') ? -1 : newVal;
        this.setData({ initialSku: this.data.initialSku });
      },
    },
    shareInfo: {
      type: Object,
      observer: function (newVal) {
        this.setData({ shareInfo: newVal });
      },
    },
    aid: {
      type: String,
      observer: function (val) {
        this.setData({ aid: val });
      }
    },
    atype: {
      type: Number,
      observer: function (newVal) {
        this.setData({ atype: newVal });
      }
    },
    changeSku: { //是否为换场次
      type: Boolean,
      observer: function (newVal) {
        this.setData({ changeSku: newVal });
      }
    },
    recommender: {
      type: String,
      observer: function (newVal) {
        this.setData({ recommender: newVal });
      }
    },
    street: {
      type: String,
      observer: function (newVal) {
        this.setData({ street: newVal });
      }
    },
    familyCommittee: {  //0-不需要 1-需要&必填 2-需要&非必填 ,
      type: Number,
      observer: function (newVal) {
        this.setData({ familyCommittee: 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 });
      }
    },
    orderInfo: {
      type: Object,
      observer: function (newVal) {
        this.setData({ orderInfo: 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: {
    checkeduseCoin: false,
    maxUserCoin: 0,//最大可使用宝贝币数
    saleType: false,  //是否为候补
    show: false,
    height: '85%',
    FixHeight: '85%',
    presellOpen: 0,
    aid: '',
    atype: 0,
    changeSku: false,
    orderInfo: null,
    qptype: 0,
    recommender: '',
    street: '',
    familyCommittee: 0,
    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
    },
    military: 0,
    ageLimit: '',
    //日历信息
    calendarInfo: [],
    sessionInfo: [],
    mealsInfo: [],
    // 日历场次选中项
    checkDate: {},
    checkSession: -1,
    checkMeals: -1,
    // 分享者信息
    shareInfo: {}
  },
  methods: {
    showFund() {
      this.triggerEvent("showFund")
    },
    checkboxChange(e) {
      let initialSku = {
        s1: -1,
        s2: -1,
        selectedNum: 1
      }
      this.setData({ checkeduseCoin: !this.data.checkeduseCoin, initialSku })
      this.getCalendarInfo()
    },
    // 获取日历信息
    getCalendarInfo() {
      let that = this;
      let data = {
        aid: that.data.aid,
        sid: that.data.initialSku.s1 != -1 ? that.data.initialSku.s1 : '',
      }
      if (this.data.checkeduseCoin) {
        data.useUserCoin = 1
      }
      util.ajax({
        func: 'v2/article/date/list',
        data,
        load: false
      }, function (res) {
        if (res.code == 0) {
          that.setData({ calendarInfo: res.data || [] })
        } else {
          util.showTips(data.reason);
        }
      })
    },
    // 获取场次列表
    getSessionInfo(e, type) {
      let that = this;
      let data = {
        aid: that.data.aid,
        date: e.dateString,
      }
      if (this.data.checkeduseCoin) {
        data.useUserCoin = 1
      }
      util.ajax({
        func: 'v2/article/session/list',
        data,
        load: false
      }, function (res) {
        if (res.code == 0) {
          if (res.data && res.data.length > 0) {
            that.setData({
              sessionInfo: res.data,
              checkSession: that.getDefaultOption(res.data, 0, type == 'click' ? -1 : that.data.initialSku.s1, 1, 'sid') != -1 ? that.getDefaultOption(res.data, 0, type == 'click' ? -1 : that.data.initialSku.s1, 1, 'sid') : that.getDefaultOption(res.data, 0, type == 'click' ? -1 : that.data.initialSku.s1, 2, 'sid')
            })
            if (that.data.checkSession != -1) {
              if (that.data.mealsInfo.length > 0) {
                that.setData({ mealsInfo: [] })
              }
              that.getMealsInfo(type)
            }
          }
        } else {
          util.showTips(data.reason);
        }
      })
    },
    // 获取套餐/排列表
    getMealsInfo(type) {
      let that = this;
      if (that.data.mealsInfo.length > 0) {
        that.setData({ mealsInfo: [] })
      }
      let sid = that.data.sessionInfo[that.data.checkSession].sid;
      let data = { sid: sid, }
      if (this.data.checkeduseCoin) {
        data.useUserCoin = 1
      }
      util.ajax({
        func: 'v2/article/meal/list',
        data,
        load: false
      }, function (res) {
        if (res.code == 0) {
          if (res.data && res.data.length > 0) {
            that.setData({
              mealsInfo: res.data,
              checkMeals: that.getDefaultOption(res.data, 0, type == 'click' ? -1 : that.data.initialSku.s2, 1, 'pid') != -1 ? that.getDefaultOption(res.data, 0, type == 'click' ? -1 : that.data.initialSku.s2, 1, 'pid') : that.getDefaultOption(res.data, 0, type == 'click' ? -1 : that.data.initialSku.s2, 2, 'pid')
            })

            if (that.data.checkMeals != -1) {
              let num = 0;
              if (that.data.presellOpen == 0) {
                num = that.data.mealsInfo[that.data.checkMeals].actnum > 0 ? that.data.mealsInfo[that.data.checkMeals].actnum : (that.data.mealsInfo[that.data.checkMeals].actnum <= 0 && that.data.mealsInfo[that.data.checkMeals].waitActNum > 0 ? that.data.mealsInfo[that.data.checkMeals].waitActNum : 0)
                that.data.saleType = (that.data.mealsInfo[that.data.checkMeals].actnum <= 0 && that.data.mealsInfo[that.data.checkMeals].waitActNum > 0) ? true : false;
                that.setData({ saleType: that.data.saleType })
              } else {
                num = that.data.mealsInfo[that.data.checkMeals].actnum
              }
              that.setData({
                'initialSku.selectedNum': that.data.mealsInfo[that.data.checkMeals].minT,
                'sku.stock_num': num,
                'sku.maxT': that.data.mealsInfo[that.data.checkMeals].maxT,
                'sku.minT': that.data.mealsInfo[that.data.checkMeals].minT,
              })
            }
          }
        } else {
          util.showTips(data.reason);
        }
      })
    },
    // 递归判断场次默认项
    getDefaultOption(arr, index, id, opt, type) {
      if (arr.length > 0 && index < arr.length) {
        if (id != -1) {
          if (arr[index][type] == id && (
            (arr[index].status == 0 && arr[index].actnum > 0) ||
            (arr[index].status == 1 && arr[index].actnum <= 0 && arr[index].waitActNum > 0 && this.data.presellOpen == 0)
          )) {
            return index;
          } else {
            return this.getDefaultOption(arr, index + 1, id, opt, type);
          }
        } else {
          if (opt == 1) {
            let obj = arr[index];
            if (obj.actnum > 0 && obj.status == 0) {
              return index;
            } else {
              return this.getDefaultOption(arr, index + 1, id, opt, type);
            }
          } else if (opt == 2) {
            let obj = arr[index];
            if (obj.actnum <= 0 && obj.waitActNum > 0 && obj.status == 1 && this.data.presellOpen == 0) {
              return index;
            } else {
              return this.getDefaultOption(arr, index + 1, id, opt, type);
            }
          }
        }
      }
      return -1;
    },
    close(e) {
      this.triggerEvent("close", e.detail);
    },
    // 选择日历
    changeDate(e) {
      let obj = e.detail, type = '';
      if (obj.bol) {
        this.setData({ 'initialSku.s1': -1 })
        type = 'click';
      }
      this.setData({ checkDate: obj });
      if (this.data.sessionInfo.length > 0) {
        this.setData({ sessionInfo: [] })
      }
      if (!util.isEmpty(obj) && obj.day != 0) {
        this.getSessionInfo(obj, type);
      }
    },
    // 选择场次
    selectSession(e) {
      let val = e.currentTarget.dataset.item, i = e.currentTarget.dataset.i;
      if (val.status == 2 || (val.status == 1 && this.data.presellOpen == 1) || (val.actnum <= 0 && val.waitActNum <= 0 && this.data.presellOpen == 0) || this.data.checkSession == i) { return false; }
      this.setData({ checkSession: i });
      this.getMealsInfo('click');
    },
    // 选择套餐
    selectMeals(e) {
      let val = e.currentTarget.dataset.item, i = e.currentTarget.dataset.i, num = 0, that = this;
      if (this.data.military == 1 && (val.status == 2 || (val.status == 1 && this.data.presellOpen == 1) || (val.actnum <= 0 && val.waitActNum <= 0 && this.data.presellOpen == 0) || this.data.checkMeals == i)) { return false; }
      this.setData({ checkMeals: i })
      if (that.data.presellOpen == 0) {
        num = that.data.mealsInfo[that.data.checkMeals].actnum > 0 ? that.data.mealsInfo[that.data.checkMeals].actnum : (that.data.mealsInfo[that.data.checkMeals].actnum <= 0 && that.data.mealsInfo[that.data.checkMeals].waitActNum > 0 ? that.data.mealsInfo[that.data.checkMeals].waitActNum : 0)
        that.data.saleType = (that.data.mealsInfo[that.data.checkMeals].actnum <= 0 && that.data.mealsInfo[that.data.checkMeals].waitActNum > 0) ? true : false;
        that.setData({ saleType: that.data.saleType })
      } else {
        num = that.data.mealsInfo[that.data.checkMeals].actnum
      }
      this.setData({
        'initialSku.selectedNum': val.minT,
        'sku.stock_num': num,
        'sku.maxT': that.data.mealsInfo[that.data.checkMeals].maxT,
        'sku.minT': that.data.mealsInfo[that.data.checkMeals].minT
      })
    },
    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 (this.data.checkSession == -1) {
        util.showTips('请选择场次');
        return false;
      }
      if (this.data.checkMeals == -1) {
        util.showTips('请选择' + this.data.military == 1 ? "排" : "套餐");
        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('&')
        })
      }
    },
    // 关注服务号
    confirm() {
      this.triggerEvent("showCode")
    },
    // 确认换场次
    confirmChange() {
      // console.log(this.data.orderInfo);
      let dateTimeNow = new Date().getTime(), that = this;
      if (this.data.sessionInfo[this.data.checkSession].stopBuy < dateTimeNow) {
        util.showTips('所选择的场次已经截止报名，请选择其他场次~');
        return false;
      }
      if (this.data.military != 1 && this.data.initialSku.s1 == this.data.sessionInfo[this.data.checkSession].sid) {
        util.showTips('本活动为非军事营活动，不可更换同场次下的套餐！');
        return false;
      }
      if (this.data.military != 1 && this.data.sessionInfo[this.data.checkSession].actnum <= 0 && this.data.sessionInfo[this.data.checkSession].waitActNum > 0) {
        util.showTips('不可更换为候补状态的场次！');
        return false;
      }
      if (this.data.military == 1 && that.data.mealsInfo[that.data.checkMeals].actnum <= 0 && that.data.mealsInfo[that.data.checkMeals].waitActNum > 0) {
        util.showTips('不可更换为候补状态的排！');
        return false;
      }
      util.requestMsg(['NWR1qEbBHgY6y1zin4uveLZlVBhkqBtob8V5J2ydkoM', '9N_BQYOCniXrjVJ52O9AvbNHs2T078uIcR1iAJI7ql0'], true).then(e => {
        let zid = that.data.mealsInfo[that.data.checkMeals].zid;
        that.triggerEvent('confirmChange', zid)
      })
    }
  }
})
