const util = require('../../../utils/util.js');
const app = getApp();
Page({
  data: {
    num: 0, //套餐数量
    agreement: false, //同意合同
    pay: true, //同意微信支付
    qptype: 0,
    btype: -1, //上页面传入的活动类型    0（默认）-普通购买 1-预付 2-付尾款 3-候补购买
    recommender: '', //推荐人
    recommenderStatus: '',
    street: '', //街道社区
    streetStatus: '',
    atype: 0, //0活动1电商
    recommenderShow: false,
    recommenderShowText: '',
    datas: {}, //payinfo数据
    imgPath: util.config.imgPath,
    userInfo: app.globalData.userInfo,
    formData: {
      aid: '',
      sid: '',
      vid: '',
      cid: '',
      useCoin: 0,
      useBalance: 0,
      useUserCoin: 1,
      meals: ''
    },
    total: {
      coin: '0.00', //钱包
      coupons: '0.00', //现金券
      ldiscount: '0.00', //早鸟优惠价格
      mdiscount: '0.00', //会员折扣价
      price: '0.00', //总价
      sumBalance: '0.00', //账户余额
      ableBalance: '0.00', //账户余额可用
    },
    idcards: {},
    textarea: '', //备注
    phoneNum: '', //手机号码
    mailAddress: '', //邮寄地址
    shipAddress: '', //收货地址
    email: '', //邮箱
    familyCommittee: '',
    travelDates: '', //出行日期
    groupid: '', //拼团号
    shareId: '', //分享id
    paying: false, //支付中
    percent: 0,
    alone: 0, //0单独报名,1拼团
    initialSku: {},
    havePerson: false,
    sku: {
      quantity: 0, //购买数量
      sessions: {},
      meals: {},
      quota: 999, //限购
    },
    show: {
      address: false,
      vouche: false,
      integral: false
    },
    voucheConfig: {},
    maskShow: false,
    presellOpen: 0,
    military: 0,
    ageLimit: ''
  },
  onLoad(options) {
    console.log(options)
    wx.removeStorageSync('idcards');
    this.data.formData.aid = options.aid;
    this.setData({
      formData: this.data.formData,
      qptype: options.qptype || '',
      btype: options.btype,
      groupid: (!util.isEmpty(options.groupid) && options.groupid != 'null' && options.groupid != 'undefined') ? options.groupid : '',
      recommenderStatus: options.recommender,
      streetStatus: options.street,
      alone: options.createGroup != undefined ? options.createGroup : 0,
      initialSku: {
        sessionsIndex: parseInt(options.sessionsIndex),
        mealsIndex: parseInt(options.mealsIndex),
        quantity: parseInt(options.quantity)
      },
      atype: parseInt(options.atype),
      presellOpen: options.presellOpen,
      military: options.military,
      ageLimit: options.ageLimit
    });
    this.payinfo();
    if (util.isObjEmpty(options.recommender) || options.recommender == '0') {
      this.setData({
        recommenderShow: false
      })
    } else if (options.recommender == '1') {
      this.setData({
        recommenderShow: true,
        recommenderShowText: '请填写推荐人，没有填无'
      })
    } else if (options.recommender == '2') {
      this.setData({
        recommenderShow: true,
        recommenderShowText: '非必填，若有请填写'
      })
    }
  },
  onShow() {
    let idcards = wx.getStorageSync('idcards');
    this.data.formData.cid = !util.isObjEmpty(idcards) ? idcards.ids.join(",") : '';
    this.setData({
      idcards,
      formData: this.data.formData
    });
    this.setData({
      userInfo: app.globalData.userInfo
    });
    if (!util.isObjEmpty(this.data.sku.meals)) this.safe();
  },
  onUnload() {
    wx.removeStorageSync('idcards');
  },
  // 判断是否含有出行人信息
  getIdcardinfoList() {
    var self = this;
    util.ajax({
      func: "user/idcardinfo_list",
      data: {
        type: this.data.ctype == 0 ? 0 : -1
      },
      load: false
    }, function (res) {
      if (res.code == 0) {
        self.setData({
          havePerson: res.data.length > 0 ? true : false
        })
      } else {
        util.showTips(res.reason)
      }
    })
  },
  payinfo() {
    let that = this,
      userInfo = app.globalData.userInfo;
    util.ajax({
      func: "article/payinfo",
      data: {
        "aid": that.data.formData.aid,
        "qptype": that.data.qptype ? that.data.qptype : 0,
        'sid': that.data.initialSku.sessionsIndex  // 参数新增sid返回数据场次只有一条
      }
    }, function (res) {
      if (res.code == 0) {
        // res.data.remark = res.data.remark || (that.data.atype==0? "请填写家长特别叮嘱，若无则填写无。":res.data.sremark == 'yes'? '给卖家留言，非必填':'');
        // if (that.data.presellOpen ==1) {
        //   that.data.total.price = util.toMoney(res.data.presellPrice, ',');
        // }
        that.setData({
          datas: res.data,
          userInfo,
          total: that.data.total,
          formData: that.data.formData,
          phoneNum: res.data.buyInfo.contactPhone || '',
          textarea: res.data.orderRemark || '',
          mailAddress: res.data.buyInfo.mailAddress || '',
          email: res.data.needEmail != 'no' ? res.data.buyInfo.email : '',
          street: res.data.buyInfo.street || ''
        });
        wx.reportAnalytics('enter_enlist', {
          aid: that.data.formData.aid,
          title: res.data.title
        });
        that.getSku();
        that.safe();
        that.getIdcardinfoList()
        that.shipInfo();
      } else if (res.code == 3003) {
        wx.showModal({
          title: '提示',
          content: res.reason,
          showCancel: false,
          success: function (data) {
            if (data.confirm) {
              wx.navigateBack();
            }
          }
        })
      } else {
        util.showTips(res.reason);
      }
    })
  },
  getSku() { //sku
    let sku = this.data.sku,
      info = this.data.datas,
      initialSku = this.data.initialSku;
    sku.sessions = this.getSkuInfo(info.sessions, 0, 'sid', this.data.initialSku.sessionsIndex);
    this.data.formData.sid = sku.sessions.sid;
    sku.meals = this.getSkuInfo(sku.sessions.alipays, 0, 'pid', this.data.initialSku.mealsIndex);
    sku.meals.originalPrice = util.toMoney(sku.meals.originalPrice)
    sku.meals.price = this.data.presellOpen == 0 ? util.toMoney(sku.meals.price) : util.toMoney(this.data.datas.presellPrice)
    sku.quantity = initialSku.quantity;
    sku.quota = this.data.btype == -1 ? (parseInt(sku.meals.actNum) < sku.meals.maxT ? parseInt(sku.meals.actNum) : sku.meals.maxT) : (parseInt(sku.meals.waitActNum) < sku.meals.maxT ? parseInt(sku.meals.waitActNum) : sku.meals.maxT);
    this.setData({
      sku,
      formData: this.data.formData
    })
  },
  // 循环获取场次信息
  getSkuInfo(arr, i, type, id) {
    if (arr.length > 0 && i < arr.length) {
      if (arr[i][type] == id) {
        return arr[i];
      } else {
        return this.getSkuInfo(arr, i + 1, type, id)
      }
    }
  },
  numAdd() {
    let sku = this.data.sku;
    if (sku.quantity >= sku.quota) {
      util.showTips("库存不足");
    } else {
      sku.quantity = parseInt(sku.quantity) + 1;
      this.setData({
        sku
      });
      this.removeIdcards();
      this.safe();
    }
  },
  numReduce() {
    let sku = this.data.sku;
    if (sku.quantity <= 1) {
      util.showTips("至少选择1件");
    } else {
      sku.quantity = parseInt(sku.quantity) - 1;
      this.setData({
        sku
      });
      this.removeIdcards();
      this.safe();
    }
  },
  numChange(e) {
    let sku = this.data.sku;
    if (parseInt(e.detail.value) > sku.quota) {
      util.showTips("库存不足");
      sku.quantity = sku.quota;
    } else if (parseInt(e.detail.value) <= 0 || util.isEmpty(e.detail.value)) {
      util.showTips("至少选择1件");
      sku.quantitym = 1;
    } else {
      sku.quantity = e.detail.value;
    }
    this.setData({
      sku
    });
    this.removeIdcards();
    this.safe();
  },
  removeIdcards() {
    wx.removeStorageSync('idcards');
    this.setData({
      idcards: []
    })
  },
  openQuestion() {
    this.setData({
      maskShow: true
    })
  },
  maskClose() {
    this.setData({
      maskShow: false
    })
  },
  agree() {
    this.setData({
      agreement: !this.data.agreement
    })
  },
  choosePay() {
    this.setData({
      pay: !this.data.pay
    })
  },
  // 选择出行人
  chooseCard() {
    var quantity = this.data.sku.quantity;
    if (quantity > 0) {
      wx.navigateTo({
        url: '/pages/account/cards/index?quantity=' + quantity + '&mage=' + this.data.datas.mage + '&lage=' + this.data.datas.lage + '&sparent=' + this.data.datas.sparent + '&adultMinAge=' + this.data.datas.adultMinAge + '&adultMaxAge=' + this.data.datas.adultMaxAge + '&needClothesSize=' + this.data.datas.clothesSize + '&needShoeSize=' + this.data.datas.shoeSize + '&ageLimit=' + this.data.ageLimit + '&campSex=' + this.data.sku.meals.campSex + '&military=' + this.data.military + '&sid=' + this.data.sku.sessions.sid
      })
    } else {
      util.showTips('请选择场次或者套餐数量');
    }
  },
  // 查看数组是否有重复元素
  hasDuplicate(arr) {
    if (arr && arr.length > 0) {
      return new Set(arr).size !== arr.length;
    } else {
      return false
    }
  },
  safe() {
    let that = this;
    that.data.formData.meals = that.data.sku.meals.pid + '|' + that.data.sku.quantity;
    that.data.formData.btype = this.data.btype != -1 ? this.data.btype : (this.data.presellOpen != 0 ? 1 : 0);
    util.ajax({
      func: "voucher/pay_mvoucher", //会员折扣，现金券，钱包
      data: that.data.formData,
      load: false
    }, function (res) {
      if (res.code == 0 && res.data != "") {
        let data = res.data;
        that.data.total.coin = util.toMoney(data.coin, ',');
        that.data.total.coupons = util.toMoney(data.price, ',');
        that.data.total.ldiscount = util.toMoney(data.ldiscount, ',');
        that.data.total.mdiscount = util.toMoney(data.mdiscount, ',');
        // if (this.data.presellOpen !=1) {
        that.data.total.price = util.toMoney(data.totalFee, ',');
        // }
        that.data.total.sumBalance = util.toMoney(data.sumBalance, ',');
        that.data.total.sumBalanceNum = data.sumBalance;
        that.data.total.sumUserCoin = data.sumUserCoin || 0;
        that.data.total.userCoin = data.userCoin || 0;
        // accountBalance  账户余额是否可用，0 不可  1 可
        // commissionWallet  佣金钱包是否可用  同上
        that.data.total.accountBalance = data.accountBalance;
        that.data.total.commissionWallet = data.commissionWallet;

        that.data.total.ableBalance = util.toMoney(data.ableBalance, ',');
        that.data.formData.vid = data.id || '';
        that.setData({
          total: that.data.total,
          formData: that.data.formData
        });
      } else {
        // that.clearSafe();
      }
    })
  },
  getPackId() {
    return (this.data.sku.meals.pid || '') + '|' + this.data.sku.quantity;
  },
  goCoupon() {
    var packIds = this.getPackId();
    if (this.data.datas.needIdcard != 'no' && util.isObjEmpty(this.data.idcards)) {
      util.showTips('请先选择购买儿童的身份信息。');
      return false;
    }
    this.data.show = {
      address: false,
      vouche: true,
      integral: false
    };
    let voucheConfig = {
      packIds: packIds,
      aid: this.data.formData.aid,
      sid: this.data.formData.sid,
      vid: this.data.formData.vid,
      cid: this.data.formData.cid
    }
    this.setData({
      voucheConfig,
      show: this.data.show
    })
  },
  goPay() {
    var packIds = this.getPackId(),
      phoneNum = this.data.phoneNum,
      idcards = this.data.idcards,
      num = this.data.sku.quantity,
      datas = this.data.datas,
      userInfo = app.globalData.userInfo,
      email = this.data.email;
    if (util.isObjEmpty(this.data.sku.meals)) {
      util.showTips('请先选择场次套餐，再付款。');
      return false;
    }
    if (datas.needIdcard != 'no' && this.data.atype == 0) {
      if (idcards.ids) {
        if (idcards.ids.length == 0) {
          util.showTips('请先选择出行人的身份信息。');
          return false;
        } else if (idcards.ids.length != num) {
          util.showTips('请设置' + num + '人的身份信息。');
          return false;
        }
      } else {
        util.showTips('请先选择出行人的身份信息。');
        return false;
      }
    }
    if (datas.sphone == 'yes' && util.isPhone(phoneNum)) {
      util.showTips('请填写正确的用户联系手机号码。');
      return false;
    }
    if (datas.smailAddress == 'yes' && !this.data.mailAddress) {
      util.showTips(this.data.atype == 1 ? '请填写收货地址。' : '请填写邮寄信息。');
      return false;
    }
    // var myreg = /^([a-zA-Z0-9]+[_|\_|\.|-]+)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.|-]+)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/gi;
    if (datas.needEmail && datas.needEmail == 'yes' && !email) {
      util.showTips('请填写电子邮箱。');
      return false;
    }
    // if (datas.needEmail == 'yes' && !myreg.test(email)) {
    //   util.showTips('请正确填写电子邮箱。');
    //   return false;
    // }

    if (datas.familyCommittee == '1' && this.data.familyCommittee == '' && this.data.atype == 0) {
      util.showTips('请填写是否为家委会');
      return false;
    }
    if (this.data.streetStatus == '1' && this.data.street == '') {
      util.showTips('请填写街道社区，没有填无');
      return false;
    }
    if (this.data.recommenderStatus == '1' && this.data.recommender == '') {
      util.showTips('请填写推荐人，没有填无');
      return false;
    }
    if (this.data.recommenderStatus == '1' && this.data.recommender.length > 10) {
      util.showTips('请正确填写推荐人');
      return false;
    }
    if (datas.travelDates == 'yes' && !this.data.travelDates && this.data.atype == 0) {
      util.showTips('请选择出行日期。');
      return false;
    }
    if (this.data.atype == 0 && datas.sremark == 'yes' && this.data.textarea == '') {
      util.showTips('请填写家长叮嘱等备注信息。');
      return false;
    }
    if (datas.agreement && !this.data.agreement && this.data.atype == 0 && this.data.presellOpen == 0) {
      util.showTips('请认真阅读相关协议条款，并认可同意。');
      return false;
    }
    if (!this.data.paying) {
      // this.setData({ paying: true });
      this.WeChatPay();
    }
    console.log(this.data.formData);
  },
  WeChatPay() {
    // this.setData({
    //   paying: true
    // });
    var data = {},
      getPackId = this.getPackId(),
      userInfo = app.globalData.userInfo,
      that = this,
      sku = this.data.sku;
    console.log(sku)
    data['meals'] = getPackId; //支付套餐字符串 如：pid|num,pid|num
    data['aid'] = this.data.formData.aid; //活动唯一标识
    data['sid'] = this.data.formData.sid; //场次id
    data['orderTitle'] = this.data.datas.title; //商品名
    data['phone'] = userInfo.phoneNum; //用户联系电话
    data['vid'] = this.data.formData.vid == -1 ? "" : this.data.formData.vid; //现金券id
    data['idcards'] = this.data.idcards.ids != undefined ? this.data.idcards.ids.join(",") : ""; //身份证信息 ,字符串多个","隔开 如： id1,id2 remark
    data['remark'] = this.data.textarea; //备注
    data['contactPhone'] = this.data.phoneNum; //联系手机号
    data['recommender'] = this.data.recommender; //推荐人
    data['street'] = this.data.street; //街道社区
    data['familyCommittee'] = this.data.familyCommittee; //街道社区
    data['travelDates'] = this.data.travelDates; //出行日期
    data['mailAddress'] = this.data.mailAddress; //邮寄地址
    data['openid'] = userInfo.socialUid; //微信用户的openid
    data['email'] = this.data.email || ''; //邮件地址
    data['wallet'] = this.data.formData.useCoin;
    data['useBalance'] = this.data.formData.useBalance;
    data.useUserCoin = this.data.formData.useUserCoin;
    if (!util.isEmpty(this.data.groupid) && this.data.groupid != 'null' && this.data.groupid != 'undefined') {
      data['groupid'] = this.data.groupid; //拼团号
    }
    data['shareId'] = this.data.shareId; //分享id
    data['product'] = 0; //产品： 0(默认)-活动  1-年卡
    data.createGroup = this.data.alone;
    data.btype = this.data.btype != -1 ? this.data.btype : (this.data.presellOpen != 0 ? 1 : 0); //this.data.presellOpen ==1 ?1 : (this.data.presellOpen ==0 && sku.meals.actNum<=0 && sku.meals.waitActNum>0 ?3:0);
    data.orderid = '';
    let str = data.idcards
    console.log(str);
    let idCards = str.split(',');
    console.log(idCards, 'idCards');
    let obj = {}
    //是否重复 false不重复
    if (this.hasDuplicate(idCards)) {
      obj.isRepeat = true
    } else {
      obj.isRepeat = false
    }
    console.log(obj.isRepeat);
    if (this.data.atype != 1) {
      if (obj.isRepeat) {
        util.showTips('你选择的儿童中存在相同信息,请核对后重新选择')
      } else {
        util.WXPay(data, this.data.formData.aid, this.data.datas.title, that.data.alone, this.data.presellOpen).then(function (data) {
          that.setData({
            paying: false
          });
          wx.navigateTo({
            url: '/pages/order/success/index?orderid=' + data.orderid + '&alone=' + that.data.alone + '&presellOpen=' + that.data.presellOpen + '&btype=' + data.btype + '&tradeChannelWeixin=' + data.tradeChannelWeixin
          });
        }, function (res) {
          that.setData({
            paying: false
          });
          util.showTips(res.reason)
        });
        wx.reportAnalytics('gopay', {
          aid: that.data.aid,
          title: that.data.datas.title,
        });
      }
    } else {
      util.WXPay(data, this.data.formData.aid, this.data.datas.title, that.data.alone, this.data.presellOpen).then(function (data) {
        that.setData({
          paying: false
        });
        wx.navigateTo({
          url: '/pages/order/success/index?orderid=' + data.orderid + '&alone=' + that.data.alone + '&presellOpen=' + that.data.presellOpen + '&btype=' + data.btype + '&tradeChannelWeixin=' + data.tradeChannelWeixin
        });
      }, function (res) {
        that.setData({
          paying: false
        });
        util.showTips(res.reason)
      });
      wx.reportAnalytics('gopay', {
        aid: that.data.aid,
        title: that.data.datas.title,
      });
    }
  },
  coinChange(e) {
    this.data.formData.useUserCoin = Number(e.detail.value);
    this.setData({
      formData: this.data.formData
    });
    this.safe();
  },
  switchChange(e) {
    this.data.formData.useCoin = Number(e.detail.value);
    this.setData({
      formData: this.data.formData
    });
    this.safe();
  },
  balanceChange(e) {
    this.data.formData.useBalance = Number(e.detail.value);
    this.setData({
      formData: this.data.formData
    });
    this.safe();
  },
  textarea(e) {
    this.setData({
      textarea: e.detail.value
    });
  },
  phoneNum(e) {
    this.setData({
      phoneNum: e.detail.value
    });
  },
  chooseAddress() {
    this.data.show = {
      address: true,
      vouche: false,
      integral: false
    };
    this.setData({
      show: this.data.show
    });
  },
  submitAddress(e) {
    let data = e.detail;
    data.address = data.address.replace(/\s+/g, ' ')
    this.setData({
      mailAddress: data.name + ' ' + data.mobile + ' ' + data.provincial + ' ' + data.address
    });
    this.shipInfo();
  },
  shipInfo() {
    if (this.data.mailAddress) {
      let address = this.data.mailAddress.split(' ');
      let addressInfo = address[2].split('/');
      let shipAddress = {
        userName: address[0],
        telNumber: address[1],
        provinceName: addressInfo[0],
        cityName: addressInfo[1],
        countyName: addressInfo[2],
        detailInfo: address[3],
      }
      this.setData({
        shipAddress
      });
    }
  },
  changeVouche(e) {
    this.data.formData.vid = e.detail;
    this.setData({
      formData: this.data.formData
    });
    this.safe();
  },
  // 推荐人
  recommender(e) {
    this.setData({
      recommender: util.trim(e.detail.value)
    });
  },
  // 街道社区
  streetInput(e) {
    this.setData({
      street: util.trim(e.detail.value)
    });
  },
  // 邮箱
  email(e) {
    this.setData({
      email: util.spaceTrim(e.detail.value)
    });
    let userInfo = app.globalData.userInfo;
    userInfo.email = util.spaceTrim(e.detail.value);
    wx.setStorageSync('WXuserInfo', userInfo);
  },
  // 家委会
  familyCommittee(e) {
    this.setData({
      familyCommittee: util.trim(e.detail.value)
    });
  },
  bindDateChange(e) {
    this.setData({
      travelDates: e.detail.value
    });
  },
  openDoc() {
    let datas = this.data.datas,
      url = '',
      that = this;
    switch (datas.agreement) {
      case 'default': //境内旅游合同
        url = util.config.imgUrl + '/doc/jingneihetong.pdf'
        break;
      case 'foreign': //境外旅游合同
        url = util.config.imgUrl + '/doc/jingwaihetong.pdf'
        break;
      case 'within': //沐童境内旅游合同
        url = util.config.imgUrl + '/doc/jingneimutong.pdf'
        break;
      case 'leave': //沐童境外旅游合同
        url = util.config.imgUrl + '/doc/jingwaimutong.pdf'
        break;
      case 'pay': //知识付费协议
        url = util.config.imgUrl + '/doc/knowledge.pdf'
        break;
      case 'bicycleDomestic': //沐童境内旅游合同（含骑行）
        url = util.config.imgUrl + '/doc/bicycleDomestic.pdf'
        break;
      case 'bicycleAbroad': //沐童出境旅游合同（含骑行）
        url = util.config.imgUrl + '/doc/bicycleAbroad.pdf'
        break;

      case 'within1': //境内旅游合同（沐童旅行社单日版）
        url = util.config.imgUrl + '/doc/singleDayContract.pdf'
        break;
      case 'within1_bicycle': //境内旅游合同（沐童旅行社单日骑行版）
        url = util.config.imgUrl + '/doc/singleDayBicycle.pdf'
        break;
      case 'within3': //境内旅游合同（沐童旅行社多日版）
        url = util.config.imgUrl + '/doc/manyDayContract.pdf'
        break;
      case 'within3_bicycle': //境内旅游合同（沐童旅行社多日骑行版)
        url = util.config.imgUrl + '/doc/manyDayBicycle.pdf'
        break;
    }
    const downloadTask = wx.downloadFile({
      url: url,
      success: function (res) {
        wx.openDocument({
          filePath: res.tempFilePath,
          fileType: "pdf",
        })
      }
    })
    downloadTask.onProgressUpdate((res) => {
      that.setData({
        percent: res.progress
      })
    });
  },
  integral() {
    if (this.data.datas.needIdcard != 'no' && util.isObjEmpty(this.data.idcards)) {
      util.showTips('请先选择购买儿童的身份信息。');
      return false;
    }
    this.data.show = {
      address: false,
      vouche: false,
      integral: true
    };
    this.setData({
      show: this.data.show,
      integralConfig: {
        idcards: this.data.idcards,
        sid: this.data.formData.sid,
        aid: this.data.formData.aid
      }
    });
  },
  close(e) {
    this.data.show[e.currentTarget.dataset.name] = false;
    this.setData({
      show: this.data.show
    })
  },
  onShareAppMessage() {
    return {
      title: '分享自@宝贝走天下微信小程序',
      path: '/pages/home/index'
    }
  }
})