// pages/GroupTour/FillOrder/FillOrder.js
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    payInfo: {},
    data: {
      teamType:0,
    },
    contact: {
      ContactMobile: "",
      ContactName: "",
    },
    code: '',  //输入的 兑换码
    userInfo: {},
    RedEnvelopeMoneyALL: 0, //获取的 存折金额
    RedMoney: '', //输入的 红包金额
    teamType: '',// 0 跟团游  1自由行  2当地游
    cpList: [], // 优惠券数据
    cpBoxShow: false,
    SettlementPrice: 0,
    CouponLength: '',
    GoodsView: false
  },
  // 关闭或打开 价格详情
  CloseGoodsView: function (){
    this.setData({
      GoodsView: !this.data.GoodsView,
    })
  },
  // 关闭打开优惠券选择box
  closeBox: function(){
    this.setData({
      cpBoxShow: !this.data.cpBoxShow
    })
  },
  // 选择优惠券 一些逻辑
  clickCP: function (e) {
    let index = e.currentTarget.dataset.index 
    let list = this.data.cpList;
    if (list[index].dis) {  // 禁用了的点击直接爬开
      return
    }
    let jishu = 0;
    list[index].checkd = !list[index].checkd;
    // 先判断是否叠加
    if (list[index].overlapUse == 1) { // 可叠加
      for (let i = 0; i < list.length; i++) {
        if (list[index].id !== list[i].id && list[i].overlapUse !== 1) { // 排除自己  禁用不可叠加
          list[i].dis = true
        }
      }
    } else {  // 不可叠加
      for (let i = 0; i < list.length; i++) {
        if (list[index].id !== list[i].id) { // 排除自己  全部禁用
          list[i].dis = true
        }
      }
    }
    for (let i = 0; i < list.length; i++) { // 获取选中的个数 
      if (list[i].checkd) {  
        jishu = jishu + 1
      }
    }
    if (jishu == 0){  // 莫得选中的解除全部禁用
      list.map(i=>{
        i.dis = false
      })
    }
    this.setData({
      cpList: list
    })
    // 计算金额
    this.getCpPrice()
    //有点麻烦 先凑合用
  },
  // 获取优惠券优惠金额
  getCpPrice: function(){
    let price = this.data.payInfo.PreferPrice,
      yPrice = 0, cpList = this.data.cpList, type = 0, CouponMoney = 0, CouponSale = 1, CouponIds = '', CouponLength = 0, SettlementPrice = 0;
    cpList.map(item => {
      if (item.checkd) {
        
        type = item.couponsType
        CouponLength = CouponLength + 1
        CouponIds = CouponIds + item.id + ','
        if (item.couponsType === 1) {
          CouponMoney = CouponMoney + item.denomination
        } else {
          CouponSale = CouponSale * (item.denomination / 10)
        }
      }
      if (type === 1) {
        SettlementPrice = price - (price - CouponMoney)
      } else if (type === 2) {
        SettlementPrice = price - (price * CouponSale)
      } else if (type === 0) {
        SettlementPrice = 0
      }
    })
    this.setData({
      CouponLength: CouponLength,
      CouponIds: CouponIds,
      SettlementPrice: SettlementPrice,
    })
  },
  // 获取优惠券
  getCpList: function (){
    let msg = {
      lineId: this.data.payInfo.lineId,
      lineteamId: this.data.payInfo.lineteamId,
      CouponsUseScope: 2,
    }
    app.$apiJavaData("api/b2b/user/getUserCanUseCouponList", { ActivateCode: this.data.code }).then(res => {
      let data = res.data
      let list = [];
      for(let i = 0; i < data.length; i++) {
        data[i].effectDate = data[i].effectDate.split(' ')[0].replace(/-/g,'.')
        data[i].expirationDate = data[i].expirationDate.split(' ')[0].replace(/-/g, '.')
        data[i].dis = false
        data[i].ckeckd = false
        if (this.data.payInfo.PreferPrice > data[i].useCondition){
          list.push(data[i])
        }
      }
      this.setData({
        cpList: list
      })
    }).catch(err => { })
  },
  //输入使用存折金额
  changeRedMoney: function (e){
    let money = 0;
    if (/^(\d?)+(\.\d{0,2})?$/.test(e.detail.value)) {
      money = e.detail.value;
    } else {
      money = e.detail.value.substring(0, e.detail.value.length - 1);
    }
    console.log(money)
    if (money !== ""  && parseFloat(money) > this.data.RedEnvelopeMoneyALL) {
      money = this.data.RedEnvelopeMoneyALL
      wx.showToast({
        title: '最大金额不能超过余额',
        icon: 'none',
        duration: 2000
      })
    }
    this.setData({
      RedMoney: parseFloat(money)
    })
  },
  // 获取幸福存折余额
  getHappyMoney: function (){
    app.$api('customer_post_GetCustomerBigRedEnvelopeBalance', { CustomerId: this.data.userInfo.id}).then(res => {
      this.setData({
        RedEnvelopeMoneyALL: res
      })
    }).catch(err => {

    })
  }, 
  //兑换码兑换
  subCode: function () {
    if (this.data.code == "") {
      wx.showToast({
        title: '请输入兑换码',
        icon: 'none',
        duration: 2000
      })
      return
    }
    app.$apiJavaData("api/b2b/user/updateUseCouponBycode", { ActivateCode: this.data.code}).then(res => {
      wx.showToast({
        title: '兑换成功，请到优惠券列表查看',
        icon: 'none',
        duration: 2000
      })
      this.getCpList()
    }).catch(err => { })
  },
  // 写入兑换码
  setCode: function (e) {
    this.setData({
      code: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    let payInfo = wx.getStorageSync('payInfo');
    this.setData({
      payInfo: payInfo,
      userInfo: wx.getStorageSync('admin'),
      teamType: options.teamType
    })
    let that = this;
    let msg = {};
    if (options) {
      // console.log("options", options)
      msg.configId = decodeURIComponent(options.idDes);
      msg.tcid = options.tcid;
      if (options.teamType) {
        msg.teamType = options.teamType;
        that.data.teamType = options.teamType;
      }
      that.data.teamType = options.teamType;
      cityId: that.data.cityId,
        that.setData({
          msg: msg,
        teamType: that.data.teamType
        })
      this.getData(msg);
    }
    this.getHappyMoney()
    this.getCpList()
  },
  getData(msg) {
    let that = this;
    app.$api('b2b_get_GetB2BTravelInfoV1', msg).then(res => {
      let data = res;
      that.setData({
        data: res,
      })
    }).catch(err => {

    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },
  Name(e) {
    this.data.payInfo.ContactName = e.detail.value;
    this.setData({
      payInfo: this.data.payInfo
    })
  },
  Mobile(e) {
    let that = this;
    let phoneNumber = e.detail.value;
    that.data.payInfo.ContactMobile = e.detail.value;
    if (phoneNumber.length==11){
      let checkedNum = that.checkPhoneNum(phoneNumber);
    }
    that.data.payInfo.ContactMobile = phoneNumber;
    that.setData({
      payInfo: that.data.payInfo
    })
  },

  checkPhoneNum(phoneNumber) {
    let str = /^1\d{10}$/;
    if (str.test(phoneNumber)) {
      return true
    } else {
      wx.showToast({
        title: '手机号不正确',
        duration: 500,
        icon: 'none',
      })
      return false
    }
  },

  StartYd() {
    let that = this;
    if (that.data.payInfo.ContactMobile == "" || !that.data.payInfo.ContactMobile || that.data.payInfo.ContactMobile.length<11) {
      wx.showToast({
        title: "请输入正确的手机号",
        icon: 'none',
        duration: 1000
      })
      return;
    }
    if (that.data.payInfo.ContactName == "" || !that.data.payInfo.ContactName) {
      wx.showToast({
        title: "请输入联系人姓名",
        icon: 'none',
        duration: 1000
      })
      return;
    }
    this.data.payInfo.CouponAllotIds = this.data.CouponIds ? this.data.CouponIds.slice(0, this.data.CouponIds.length - 1) : ''
    this.data.payInfo.DiscountMoney = this.data.SettlementPrice
    this.data.payInfo.RedEnvelopeMoney = this.data.RedMoney
    app.$api('sellorder_post_SetOrderInfoForB2B', that.data.payInfo).then(res => {
      let index = this.data.teamType == "0" ? 1 : this.data.teamType == "1" ? 2 : 3
      wx.reLaunch({
        url: '/pages/member/orderCenter/orderCenter?index=' + index,
      })
    }).catch(err => {

    })

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})