// pages/product/productOrder/productOrder.js
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isMember: 0,
    configId: '0',
    calendarNum: -1,
    calendar: [],
    priceList: [],
    monthList: [],
    monthKey: 0,
    unitPrice: '',
    tcid: 0,
    people: {
      ManNum: 0,
      ChirdNeedBedNum: 0,
      ChirdNoNeedBedNum: 0,
      BabyNum: 0,
      OldPeopleNum: 0
    },
    Remarks: '',
    formInfo: {
      startCityId: 0,
      returnArriveCityId: 0,
      lineTeamDiscountList: []
    }
  },

  /**
   * 生成日历
   */
  createCalendar: function (date) {
    var date = new Date(date);
    //当前是哪一年
    var year = date.getFullYear();
    //当前是哪个月，注意这里的月是从0开始计数的
    var month = date.getMonth();

    //当前月的第一天的日期
    var firstDay = new Date(year, month, 1);
    //第一天是星期几
    var weekday = firstDay.getDay();

    //求当前月一共有多少天
    var days = new Date(year, month + 1, 0).getDate();

    var res = [];
    //输出第一天之前的空格
    for (var i = 1; i < weekday; i++) {
      res.push({
        day: '',
        date: '',
        hasType: 0,
        b2BMemberPrice: 0,
        b2BPrice: 0
      });
    }

    for (var j = 1; j <= days; j++) {
      let hasType = 0
      let b2BMemberPrice = 0
      let b2BPrice = 0
      let tcid = 0
      let priceList = []
      for (let k = 0; k < this.data.priceList.length; k++) {
        let newDate = new Date(this.data.priceList[k].startDate)
        if (newDate.getMonth() === month && newDate.getDate() === j) {
          hasType = 1
          b2BMemberPrice = this.data.priceList[k].b2BMemberPrice
          b2BPrice = this.data.priceList[k].b2BPrice
          tcid = this.data.priceList[k].tcid
          priceList = this.data.priceList[k]
        }
      }
      res.push({
        day: j,
        date: year+'-'+(month + 1)+'-'+j,
        hasType: hasType,
        b2BMemberPrice: b2BMemberPrice,
        b2BPrice: b2BPrice,
        tcid: tcid,
        priceList: priceList
      })
    }
    this.setData({
      calendar: res,
      calendarNum: -1,
      unitPrice: '',
      tcid: 0
    })
  },

  /**
   * 获取详情
   */
  getDetail: function (configId) {
    app.$api('b2b_get_GetB2BTravelInfoNoDes', {
      configId: configId
    }).then(res => {
      let priceList = res.priceList
      let monthNumList = []
      let monthList = []
      for (let i = 0; i < priceList.length; i++) {
        let date = priceList[i].startDate.split('-')[0] + '-' + priceList[i].startDate.split('-')[1]
        if (monthNumList.indexOf(date) === -1) {
          monthNumList.push(date)
          monthList.push({
            date: date,
            month: date.split('-')[1],
            b2BMemberPrice: priceList[i].b2BMemberPrice,
            b2BPrice: priceList[i].b2BPrice
          })
        } else {
          let index = monthNumList.indexOf(date)
          if (priceList[i].b2BMemberPrice < monthList[index].b2BMemberPrice) {
            monthList[index].b2BMemberPrice = priceList[i].b2BMemberPrice
          }
          if (priceList[i].b2BPrice < monthList[index].b2BPrice) {
            monthList[index].b2BPrice = priceList[i].b2BPrice
          }
        }
      }
      this.setData({
        priceList: priceList,
        monthList: monthList,
        'formInfo.startCityId': res.startCityId,
        'formInfo.returnArriveCityId': res.returnArriveCityId,
        'formInfo.lineTeamDiscountList': res.lineTeamDiscountList
      })
      if (monthList.length !== 0) {
        this.createCalendar(monthList[0].date)
      } else {
        let nowDate = new Date()
        let date = nowDate.getFullYear() + '-' + (nowDate.getMonth() + 1)
        this.createCalendar(date)
      }
    })
  },

  /**
   * 月份选择按钮
   */
  monthOn: function (e) {
    this.createCalendar(e.currentTarget.dataset.date)
  },

  /**
   * 日期选择按钮
   */
  dayOn: function (e) {
    if (e.currentTarget.dataset.hastype === 1) {
      let price = ''
      let tcid = 0
      if (this.data.isMember === 1) {
        price = this.data.calendar[e.currentTarget.dataset.index].b2BMemberPrice
      } else {
        price = this.data.calendar[e.currentTarget.dataset.index].b2BPrice
      }
      tcid = this.data.calendar[e.currentTarget.dataset.index].tcid
      this.setData({
        calendarNum: e.currentTarget.dataset.index,
        unitPrice: price,
        tcid: tcid
      })
    }
  },

  /**
   * 输入框
   */
  bindKeyInput: function (e) {
    let name = e.currentTarget.dataset.name
    let text = 'people.' + name
    this.setData({
      [text]: e.detail.value*1
    })
  },

  /**
   * 输入框2
   */
  bindKeyInput2: function (e) {
    let name = e.currentTarget.dataset.name
    this.setData({
      [name]: e.detail.value
    })
  },

  /**
   * 人数减
   */
  numLeft: function (e) {
    let name = e.currentTarget.dataset.name
    let num = this.data.people[name]
    let text = 'people.' + name
    if (num*1!==0) {
      this.setData({
        [text]: num*1-1
      })
    }
  },
  /**
   * 人数加
   */
  numRight: function (e) {
    let name = e.currentTarget.dataset.name
    let num = this.data.people[name]
    let text = 'people.' + name
    this.setData({
      [text]: num * 1 + 1
    })
  },

  priceCale: function () {
    let zaoniao = 0
    let priceList = this.data.calendar[this.data.calendarNum].priceList
    let money = this.data.unitPrice * this.data.people.ManNum

    money += this.data.unitPrice * (this.data.people.ChirdNeedBedNum * 1 + this.data.people.ChirdNoNeedBedNum * 1)
    money += priceList.babyChargePrice * (this.data.people.ChirdNeedBedNum * 1 + this.data.people.ChirdNoNeedBedNum * 1)
    money += priceList.childNeedPrice * this.data.people.ChirdNeedBedNum
    
    money -= priceList.childNoNeedPrice * this.data.people.ChirdNeedBedNum
    money += this.data.unitPrice * this.data.people.OldPeopleNum
    money += priceList.oldManChargePrice * this.data.people.OldPeopleNum
    money += priceList.babyPrice * this.data.people.BabyNum

    let sumCount = this.data.people.ManNum + (this.data.people.ChirdNeedBedNum * 1 + this.data.people.ChirdNoNeedBedNum * 1) + this.data.people.OldPeopleNum
    money += priceList.visaPrice * sumCount
    money += priceList.otherPrice * sumCount

    if (priceList.discountPric && priceList.discountPric > 0) {
      zaoniao = priceList.discountPrice * sumCount
    }
    money -= zaoniao
    return {
      money: money,
      zaoniao: zaoniao
    }
  },

  /**
   * 下单
   */
  submit: function () {
    if (this.data.unitPrice === '') {
      wx.showToast({
        title: '请选择团期',
        icon: 'none',
        duration: 1000
      })
      return
    }
    let peopleNum = this.data.people.ManNum*1 + this.data.people.ChirdNeedBedNum*1 + this.data.people.ChirdNoNeedBedNum*1 + this.data.people.BabyNum*1 + this.data.people.OldPeopleNum*1
    if (peopleNum === 0) {
      wx.showToast({
        title: '请选择人数',
        icon: 'none',
        duration: 1000
      })
      return
    }
    
    let sumSeat = this.data.people.ManNum * 1 + this.data.people.ChirdNeedBedNum * 1 + this.data.people.ChirdNoNeedBedNum * 1 + this.data.people.OldPeopleNum * 1
    let youhuiMoney = 0
    this.data.formInfo.lineTeamDiscountList.forEach(x => {
      if (x.startNum <= sumSeat && sumSeat <= x.endNum) {
        youhuiMoney = x.discountAmount
        return false
      }
    })
    let priceList = this.data.calendar[this.data.calendarNum].priceList
    let price = this.priceCale()
    
    let nowDate = new Date()
    console.log(app.state.admin)
    let msg = {
      OrderId: 0,
      TCID: this.data.tcid,
      CustomerType: this.data.isMember,
      GroupType: 1,
      ContactName: app.state.admin.name,
      ContactMobile: app.state.admin.photo,
      CustomerId: app.state.admin.id,
      DepartureCityId: this.data.formInfo.startCityId,
      IsIntermodal: 2,
      Unit_Price: this.data.unitPrice,
      TC_Price: this.data.unitPrice,
      ManNum: this.data.people.ManNum,
      ChirdNum: this.data.people.ChirdNeedBedNum * 1 + this.data.people.ChirdNoNeedBedNum * 1,
      ChirdNeedBedNum: this.data.people.ChirdNeedBedNum,
      BabyNum: this.data.people.BabyNum,
      OldPeopleNum: this.data.people.OldPeopleNum,
      SingleRoomNum: 0,
      PreferPrice: price.money,
      YSeatNum: sumSeat,
      ESeatNum: 0,
      FSeatNum: 0,
      Commission: ((parseFloat(youhuiMoney) / 2.0) + (parseFloat(price.money) * 0.01)).toFixed(2),
      ClientSource: 2,
      BrandId: 0,
      TradeWay: 0,
      PlatformOrder: '',
      GuestNum: sumSeat,
      IsChildrenTour: priceList.isSupportChildren,
      IsBirdDiscount: price.zaoniao > 0 ? 1 : 2,
      PredictRoomNum: sumSeat/2,
      BigRoomNum: 0,
      TripleRoomNum: 0,
      TradeDate: nowDate.getFullYear + '-' + (nowDate.getMonth + 1) + '-' + nowDate.getDate,
      CostType: 0,
      MinOrderPrice: 0,
      Remarks: this.data.Remarks,
      VisaNum: sumSeat,
      SafeNum: sumSeat,
      AirticketNum: 0,
      ReturnArriveCityId: this.data.formInfo.returnArriveCityId,
      IsReturnIntermodal: 2,
      GoCityTime: '',
      BackCityTime: '',
      ScenicRefundArr: [],
      CommissionSharePeople: 0,
      CommissionShareMoney: 0,
      OrderSource: 2
    }
    app.$api('sellorder_post_SetOrderInfoForB2B', msg).then( res => {
      wx.showToast({
        title: '预定成功',
        icon: 'none',
        duration: 1000
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        })
      }, 1000)
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      isMember: app.state.admin.isMember,
      configId: options.configId
    })
    this.getDetail(options.configId)
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})