// pages/GroupTour/ChDateNum/ChDateNum.js
let app = getApp();
var util = require('../../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentDay: util.YYMMDD(new Date()),
    priceData: [],
    numer: 1,
    GoodsView: false,
    msg: {},
    priceList: [],
    monthList: [],
    activeTab: 0,
    isLogin: app.isLogin,
    selectIndex: -1,
    FlightList: [],
    cityId: app.state.site.cityId,
    teamType: 0,
    trip: {},
    customer: {},

    chosenObj: {
      startDate: '',
      crCount: 0,
      etCount: 0,
      yeCount: 0,
      lrCount: 0,
      etbzcCount: 0,
      etzc: 0,
      df: 0,
      dcf: 0,
      srf: 0,
      isUnico: false,
      unicoDep: {
        city: null,
        date: null,
        price: 0,
        isSup: -2
      },
      unicoArr: {
        city: null,
        date: null,
        price: 0,
        isSup: -2
      },
      remark: ''
    },
    isLogin: app.isLogin,
    price: 0,
    zaoniao: 0,
    sumSeat: 0,
    totalPersion: 0,
    adultPrice: 0,
    childrenPrice: 0,
    babyPrice: 0,
    zf: 0,//杂费
    zcf: 0,
    bzcf: 0,
    qzPrice: 0,
    backVisaPrice: 0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let msg = {};
    if (options) {
      msg.configId = decodeURIComponent(options.idDes);
      msg.tcid = options.tcid;
      // msg.configId = options.idDes = decodeURIComponent("5aEwngdTBnM%3D%0A");
      // msg.tcid = options.tcid = "3458";
      if (options.teamType) {
        msg.teamType = options.teamType;
        that.data.teamType = options.teamType;
      }

      cityId: that.data.cityId,
        that.setData({
          msg: msg,
          teamType: that.data.teamType
        })
      this.getData(that.data.msg);
      
    }

  },
  StartYd() {
    let that = this;
    let trip = that.data.trip;
    let chosenObj = that.data.chosenObj;
    if (chosenObj.startDate == "") {
      wx.showToast({
        title: "请先选择团期",
        icon: 'none',
        duration: 1000
      })
      return;
    }
    if (chosenObj.crCount + chosenObj.etzc < 1) {
      wx.showToast({
        title: "至少选择一人",
        icon: 'none',
        duration: 1000
      })
      return;
    }

    let youhuiMoney = 0
    trip.lineTeamDiscountList.forEach(x => {
      if (x.startNum <= sumSeat && sumSeat <= x.endNum) {
        youhuiMoney = x.discountAmount
        return false
      }
    })
    let fcnt = 0;
    let sumFang = chosenObj.crCount + chosenObj.etzc + chosenObj.lrCount
    sumFang = sumFang - chosenObj.df - (chosenObj.dcf * 2) - (chosenObj.srf * 3)
    if (sumFang > 0) {
      fcnt = parseFloat(sumFang) / 2.0 + chosenObj.dcf + chosenObj.df + chosenObj.srf
    }
    fcnt += chosenObj.dcf + chosenObj.df + chosenObj.srf
    let msg = {
      OrderId: 0,
      TCID: trip.currentPriceInfo.tcid,
      GroupType: 1,
      CustomerId: that.data.customer.customerId,
      CustomerType: that.data.customer.gradeLevel,
      DepartureCityId: trip.startCityId,
      Unit_Price: trip.currentPriceInfo.b2BMemberPrice,
      TC_Price: trip.currentPriceInfo.b2BMemberPrice,
      startDate: chosenObj.startDate,
      ManNum: chosenObj.crCount,
      ChirdNum: chosenObj.etzc + chosenObj.etbzcCount,
      ChirdNeedBedNum: chosenObj.etzc,
      BabyNum: chosenObj.yeCount,
      PreferPrice: that.data.price,
      YSeatNum: chosenObj.crCount + chosenObj.etzc + chosenObj.etbzcCount,
      ESeatNum: 0,
      FSeatNum: 0,
      Commission: ((parseFloat(youhuiMoney) / 2.0) + (parseFloat(that.data.price) * 0.01)).toFixed(2),
      ClientSource: 2,
      BrandId: 0,
      TradeWay: 0,
      PlatformOrder: '',
      GuestNum: that.data.totalPersion,
      IsChildrenTour: trip.currentPriceInfo.isSupportChildren,
      IsBirdDiscount: that.data.zaoniao > 0 ? 1 : 2,
      PredictRoomNum: fcnt,
      BigRoomNum: chosenObj.dcf,
      TripleRoomNum: chosenObj.srf,
      TradeDate: util.YYMMDD(new Date()),
      CostType: 0,
      MinOrderPrice: 0,
      Remarks: chosenObj.remark,
      VisaNum: chosenObj.crCount + chosenObj.etzc + chosenObj.etbzcCount + chosenObj.yeCount,
      SafeNum: chosenObj.crCount + chosenObj.etzc + chosenObj.etbzcCount + chosenObj.yeCount,
      AirticketNum: 0,
      ReturnArriveCityId: chosenObj.unicoArr.city && chosenObj.unicoArr.city.length > 0 ? chosenObj.unicoArr.city[chosenObj.unicoArr.city.length - 1] : trip.returnArriveCityId,
      IsReturnIntermodal: (chosenObj.unicoArr.city && chosenObj.unicoArr.city.length > 0 && chosenObj.unicoArr.date) ? 1 : 2,
      GoCityTime: chosenObj.unicoDep.city && chosenObj.unicoDep.city.length > 0 && chosenObj.unicoDep.date ? chosenObj.unicoDep.date : '',
      BackCityTime: chosenObj.unicoArr.city && chosenObj.unicoArr.city.length > 0 && chosenObj.unicoArr.date ? chosenObj.unicoArr.date : '',
      ScenicRefundArr: [],
      CommissionSharePeople: 0,
      CommissionShareMoney: 0,
      OrderSource: 2,
      IsIntermodal: 2,
      IsReturnIntermodal: 2,
      OldPeopleNum: 0,
      SingleRoomNum: 0,
      lineId: that.data.trip.lineId,
      lineteamId: that.data.trip.lineteamId,
    };
    wx.setStorageSync('payInfo', msg)
    wx.navigateTo({
      url: '/pages/GroupTour/FillOrder/FillOrder?idDes=' + encodeURIComponent(that.data.msg.configId) + "&tcid=" + that.data.msg.tcid + "&teamType=" + that.data.msg.teamType,
    })
  },
  //计算价格
  // 婴儿
  yEsubevent(e) {
    let val = e.detail.val;
    this.data.chosenObj.yeCount = val;
    this.setData({
      chosenObj: this.data.chosenObj
    })
    this.calcMoney();
  },
  yEaddCount(e) {
    let val = e.detail.val;
    this.data.chosenObj.yeCount = val;
    this.setData({
      chosenObj: this.data.chosenObj
    })
    this.calcMoney();
  },
  // 儿童不占位
  etbZsubevent(e) {
    let val = e.detail.val;
    this.data.chosenObj.etbzcCount = val;
    this.setData({
      chosenObj: this.data.chosenObj
    })
    this.calcMoney();
  },
  etbZaddCount(e) {
    let val = e.detail.val;
    this.data.chosenObj.etbzcCount = val;
    this.setData({
      chosenObj: this.data.chosenObj
    })
    this.calcMoney();
  },
  // 儿童占位
  etZsubevent(e) {
    let val = e.detail.val;
    this.data.chosenObj.etzc = val;
    this.setData({
      chosenObj: this.data.chosenObj
    })
    this.calcMoney();
  },
  etZaddCount(e) {
    let val = e.detail.val;
    this.data.chosenObj.etzc = val;
    this.setData({
      chosenObj: this.data.chosenObj
    })
    this.calcMoney();
  },
  cRaddCount(e) {

    let val = e.detail.val;
    this.data.chosenObj.crCount = val;
    this.setData({
      chosenObj: this.data.chosenObj
    })
    this.calcMoney();
  },
  cRsubevent(e) {
    let val = e.detail.val;
    this.data.chosenObj.crCount = val;
    this.setData({
      chosenObj: this.data.chosenObj
    })
    this.calcMoney();
  },
  calcMoney() {
    let that = this;
    let chosenObj = that.data.chosenObj;
    let currentPriceInfo = that.data.trip.currentPriceInfo;
    let adultCount = chosenObj.crCount; //成人数量
    let childrenPlaceholderCount = chosenObj.etzc; //儿童占床
    let childrenNotPlaceholderCount = chosenObj.etbzcCount; //儿童不占床
    let babyCount = chosenObj.yeCount; //婴儿

    let childrenCount = childrenNotPlaceholderCount + childrenPlaceholderCount;

    let totalPersion = adultCount + babyCount + childrenCount;

    let znyh = parseFloat(currentPriceInfo.discountPrice); // 早鸟优惠
    let isBrid = currentPriceInfo.isBirdDiscount == 2 ? false : true; // 是否符合早鸟优惠

    let chidrenFjf = parseFloat(currentPriceInfo.babyChargePrice); // 儿童附加费


    let adultPrice = currentPriceInfo.b2BPrice - (isBrid == true ? znyh : 0);//成人价格
    let childrenPrice = currentPriceInfo.b2BPrice + chidrenFjf - (isBrid == true ? znyh : 0);//儿童价格

    let babyPrice = parseFloat(currentPriceInfo.babyPrice);//婴儿价格

    let zf = parseFloat(currentPriceInfo.otherPrice); // 杂费
    let zcf = (currentPriceInfo.childNeedPrice != null ? parseFloat(currentPriceInfo.childNeedPrice) : 0); // 儿童占床费
    let bzcf = (currentPriceInfo.childNoNeedPrice != null ? -(parseFloat(currentPriceInfo.childNoNeedPrice)) : 0); // 儿童不占床费

    let qzPrice = currentPriceInfo.visaPrice; // 签证费用

    let backVisaPrice = currentPriceInfo.backVisaPrice != null ? currentPriceInfo.backVisaPrice : 0; // 退签费用

    let qzCount = adultCount + childrenCount + babyCount; // 签证数量

    let totalPrice = adultPrice * adultCount + childrenCount * childrenPrice + babyCount * babyPrice + zf * (totalPersion - babyCount) + childrenPlaceholderCount * zcf + (childrenCount - childrenPlaceholderCount) * bzcf + (totalPersion - babyCount) * qzPrice - backVisaPrice * (totalPersion - qzCount);
    this.setData({
      price: totalPrice,
      totalPersion: totalPersion,
      chosenObj: chosenObj,
      adultPrice: adultPrice,
      childrenPrice: childrenPrice,
      babyPrice: babyPrice,
      zf: zf,//杂费
      zcf: zcf,
      bzcf: bzcf,
      qzPrice: qzPrice,
      backVisaPrice: backVisaPrice,

    })
  },

  getB2BSellByCustomerId() {
    app.$api('b2b_get_GetCustomerSummary', {}).then(res => {
      this.setData({
        customer: res,
      })

    }).catch(err => {

    })

  },
  CloseGoodsView(e) {
    if (e.target.dataset.target == "self") {
      this.setData({
        GoodsView: false,

      })
    }
  },
  OpenGoodsView() {
    this.setData({
      GoodsView: true,

    })
  },
  childrenEvent(e) {
    let that = this;
    let val = e.detail;
    let msg = {
      configId: val.configId,
      cityId: that.data.cityId,
      tcid: val.tcid,
      teamType: that.data.teamType,
    };
    that.data.chosenObj.startDate = val.ymd;
    that.setData({
      selectIndex: val.selectIndex,
      chosenObj: that.data.chosenObj
    })
    this.getData(msg);
  },
  selectMonth(e) {

    let item = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    this.setData({
      activeTab: index,
      currentDay: item.date + '-01',
      priceData: item.datalist
    })
    this.CreatCalendar();


  },

  getData(msg) {

    let that = this;
    app.$api('b2b_get_GetB2BTravelInfoV1', msg).then(res => {
      that.getB2BSellByCustomerId();
      let data = res;
      that.setData({
        trip: data,
        priceList: data.priceList,
        FlightList: data.currentPriceInfo && data.currentPriceInfo.priceFlight ? data.currentPriceInfo.priceFlight : '',
      })

      this.getDateArr(that.data.priceList);
    }).catch(err => {

      this.CreatCalendar();

    })
  },

  getDateArr(arr) {
    let that = this;

    var new_arr = {};
    for (var i = 0, len = arr.length; i < len; i++) {
      var Month_index = arr[i].startDate.lastIndexOf('-');
      var startDate = arr[i].startDate.substr(0, Month_index);
      if (!new_arr[startDate]) {
        new_arr[startDate] = [];
        new_arr[startDate].push(arr[i])
      } else {
        new_arr[startDate].push(arr[i])
      }

    }

    let dataList = [];
    for (let key in new_arr) {
      let obj = {
        date: '',
        datalist: [],
      };
      obj.date = key;
      obj.datalist = new_arr[key];
      dataList.push(obj);
    }
    console.log(dataList)

    if (dataList.length > 0) {
      this.setData({
        currentDay: dataList[0].date + '-01',
        priceData: dataList[0].datalist
      })
    }
    this.setData({
      monthList: dataList
    })

    this.CreatCalendar();


  },

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

  },

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

  },
  CreatCalendar() {
    this.calendar = this.selectComponent('#calendar');
    this.calendar.getYearMonthDay();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

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

  },

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

  },

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

  },

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

  }
})