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

  /**
   * 页面的初始数据
   */
  data: {
    isLogin: app.isLogin,
    screenList:[
      {
        name: '航空公司',
        id: 1,
      },
      {
        name: '舱位',
        id: 2,
      }
    ],
    cangweiList: [
      { title: "头等舱", id: 1 },
      { title: "商务舱", id: 2 },
      { title: "经济舱", id: 3 }
    ],
    msg: {
      pageIndex: 1,
      pageSize: 10,
      id: 0,
      qFlightDateStart: util.YYMMDD(new Date()),
      qFlightDateEnd: "",
      flight_number: "",
      airLineID: 0,
      ticketType: 2,
      lineId: 0,
      isPayOrder: 0,
      departure_city: 0,
      departure_cityname: "",
      arrival_city: 0,
      arrival_cityname: "",
      freightSpace: 0,
      airTicketScatterNum: 0,
      flithtMonthDate: new Date().Format("yyyy-MM"), 
      timeSort: 0,
      priceSort: 0, 
    },
    airlineList: [],
    bottomActive: 1,
    screenBoxShow: false,
    screenID: 1,
    getMonthMsg:{
      id: 0,
      flithtMonthDate: '',
      flight_number: '',
      airLineID: 0,
      ticketType: 2,
      lineId: 0,
      isPayOrder: 0,
      freightSpace: 0,
      airTicketScatterNum: 0,
      qFlightDateStart: "",
      departure_city: 0,
      departure_cityname: "",
      arrival_city: 0,
      arrival_cityname: "",
    },
    MinPriceList: [],
    MinPriceListActive: -1,
    qitianhou: "",
    monthList: [],
    classArray: [],
    calendarTit: "",
    MonthDate: new Date().Format("yyyy-MM"),
    MonthDate2: new Date().Format("MM"),
    leftpx: -1,
    dateBoxShow: true,
    AirticketList: [],
    pageIndex: 1,
    totalPage: 1,
    detailShow: false,
    detailMsg: {},
  },
  // 航班详情弹窗
  closeDetail: function (e) {
    let index = e.currentTarget.dataset.index;
    let msg = index >= 0 ? this.data.AirticketList[index] : ""
    console.log(msg)
    this.setData({
      detailShow: !this.data.detailShow,
      detailMsg: msg
    })
  },
  // 加载更多
  scrollGetMore: function () {
    this.setData({
      'msg.pageIndex': this.data.pageIndex + 1,
    })
    this.getList(1)
  },
  // 获取机票列表
  getList: function (type) {
    if (this.data.pageIndex >= this.data.totalPage && type) {
      return
    }
    app.$apiJavaData("api/dmc/airticket/getB2BAirticketList", this.data.msg).then(res => {
      let arr = this.data.AirticketList;
      let arr2 = res.data.pageData;
      if (type) {
        for (let i = 0; i < arr2.length; i++){
          arr.push(arr2[i])
        }
      } else {
        arr = arr2
      }
      this.setData({
        AirticketList: arr,
        totalPage: res.data.pageCount ? res.data.pageCount : 1,
        pageIndex: res.data.pageIndex ? res.data.pageIndex : 1,
      })
    }).catch(err => { })
  },
  //切换月份
  changeMonth: function (e) {
    let t = e.currentTarget.dataset.type;
    let newDate = this.data.classArray[0][0].dateStr; 
    let preMonth = this.data.MinPriceList[0].timeStr;
    if (t == 'a') {   
      if (this.data.MonthDate2 == new Date().Format("MM")) {
        wx.showToast({
          title: '不能再往前了',
          icon: 'none',
          duration: 2000
        })
        return
      }else{
        preMonth = util.getPreMonth(newDate)
        preMonth = new Date(preMonth).Format("yyyy-MM")
      }
    } else if (t == 'b'){
      preMonth = util.getNextMonth(newDate)
      preMonth = new Date(preMonth).Format("yyyy-MM")
    } 
    this.setData({
      MonthDate2: new Date(preMonth).Format("MM"),
      "msg.flithtMonthDate": preMonth,
      'getMonthMsg.flithtMonthDate': preMonth + "-01",
      'getMonthMsg.qFlightDateStart': preMonth + "-01" + " 00:00:00",
      "msg.qFlightDateStart": preMonth + "-01" + " 00:00:00",
      totalPage: 0,
      pageIndex: 0,
      'msg.pageIndex': 0
    })
    this.getMinPrice()
    this.getForMonthMinPrice()
  },
  //打开日历
  openDate: function () {
    this.setData({
      dateBoxShow: !this.data.dateBoxShow
    })
  },
  // 点击上面一坨日历
  changeMinPrice: function (e) {
    let index = Number(e.currentTarget.dataset.index)
    if (this.data.MinPriceList[index].price !== '0.00' && this.data.MinPriceList[index].timeStr > this.data.qitianhou){
      this.setData({
        MinPriceListActive: index,
        "msg.qFlightDateStart": this.data.MinPriceList[index].timeStr,
        "MonthDate2": new Date(this.data.MinPriceList[index].timeStr).Format("MM"),
        "msg.flithtMonthDate": new Date(this.data.MinPriceList[index].timeStr).Format("yyyy-MM"),
        "msg.qFlightDateStart": this.data.MinPriceList[index].timeStr,
        totalPage: 0,
        pageIndex: 0,
        'msg.pageIndex': 0
      })
      this.getList()
    } else { 
      if (this.data.MinPriceList[index].timeStr < this.data.qitianhou){
        wx.showToast({
          title: '只能购买7天以后的机票',
          icon: 'none',
          duration: 2000
        })
      }
    } 
  },
  //舱位筛选
  changeCangwei: function (e) {
    let id = Number(e.currentTarget.dataset.id)
    this.setData({
      'msg.freightSpace': id
    })
  },
  // 筛选项切换
  changeScreenList: function (e) {
    let id = Number(e.currentTarget.dataset.id)
    this.setData({
      screenID: id
    })
  },
  // 航空公司筛选
  changeAirline: function (e) {
    let id = Number(e.currentTarget.dataset.id)
    this.setData({
      'msg.airLineID': id
    })
  },
  // 关闭筛选框
  closeScreenBox: function (){
    this.setData({
      screenBoxShow: false
    })
  },
  // 航空公司下拉框
  initAirlines: function () {
    app.$api('airline_get_GetB2BAirLineList', {}).then(res => {
      this.setData({
        airlineList: res
      })
    }).catch(err => { }); 
  },
  //底部按钮监听
  cahngeBtnActive: function (e) {
    let index = e.currentTarget.dataset.index;
    console.log(index == 3)
    let priceSort = index == 2 ? 1 : 0
    let timeSort = index == 3 ? 1 : 0
    this.setData({
      bottomActive: Number(index),
      'msg.timeSort': timeSort,
      'msg.priceSort': priceSort
    })
    if (index == 4) {
      this.setData({
        screenBoxShow: true
      })
    } else {
      this.getList()
    }
  },
  //获取月日历
  getForMonthMinPrice: function () {
    app.$apiJavaData("api/dmc/airticket/getB2BAirticketForMonthMinPrice", this.data.msg).then(res => { 
      this.creatCalendar(res.data)
    }).catch(err => { })
  },
  // 获取上面一坨日历
  getMinPrice: function (date) {
    app.$apiJavaData("api/dmc/airticket/getB2BAirticketForMinPrice", this.data.getMonthMsg).then(res => {
      this.setData({
        MinPriceList: res.data
      })
      //日历联动
      if (date) {
        for (let i = 0; i < res.data.length; i++) {
          if (date == res.data[i].timeStr){
            this.setData({
              leftpx: i,
              MinPriceListActive: i
            })
          }
        }
      }
    }).catch(err => { })
  },
  creatCalendar(list) { 
    // 创建日历
    let dateList = [];
    if (list && list.length > 0) {
      list.forEach((x, index) => {
        // if(parseFloat(999) > 0){
        let msg = {
          dateStr: x.timeStr,
          cDate: x.timeStr.replace("-", "年").replace("-", "月"),
          price: x.price,
          b2BMemberPrice: x.price,
          b2BPrice: x.price,
          b2CMemberPrice: x.price,
          id: index,
          dateStrS: x.timeStr.substring(0, x.timeStr.length - 3)
        };
        dateList.push(msg);
        // }
      });
    }
    let monthArray = [];
    for (var i in dateList) {
      var data = dateList[i];
      var dateDict = {
        mounth: data.dateStr.substring(0, data.dateStr.length - 3)
      };
      monthArray.push(dateDict);
    }
    //数组去重,获取有几个月
    var hash = {};
    monthArray = monthArray.reduce(function (item, next) {
      hash[next.mounth] ? "" : (hash[next.mounth] = true && item.push(next));
      return item;
    }, []);
    //数据分组
    let classArray = [];
    for (var j in monthArray) {
      var newArray = new Array();
      for (var i in dateList) {
        var data = dateList[i];
        if (
          data.dateStr.substring(0, data.dateStr.length - 3) ==
          monthArray[j].mounth
        ) {
          newArray.push(data);
        }
      }
      classArray.push(newArray);
    }
    this.data.classArray = classArray;
    var hash = {};
    dateList = dateList.reduce(function (item, next) {
      hash[next.dateStrS]
        ? ""
        : (hash[next.dateStrS] = true && item.push(next));
      return item;
    }, []);
    this.setData({
      calendarTit: dateList,
      classArray: classArray
    })
    this.calendarCreatCalendar()
  },
  calendarCreatCalendar() { 
    this.calendar = this.selectComponent('#calendar');
    this.calendar.getYearMonthDay(this.data.classArray);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let tit = "机票列表"
    if (options.sName && options.eName){
      tit = options.sName + '——' + options.eName
    }
    wx.setNavigationBarTitle({
      title: tit
    })
    this.setData({
      'getMonthMsg.flithtMonthDate': new Date().Format("yyyy-MM-dd"),
      'getMonthMsg.qFlightDateStart': new Date().Format("yyyy-MM-dd")+ " 00:00:00",
      "msg.qFlightDateStart": util.AddDays(new Date().Format("yyyy-MM-dd"), 6),
      qitianhou: util.AddDays(new Date().Format("yyyy-MM-dd"), 6),
      // "getMonthMsg.departure_city": options.sId,
      // "getMonthMsg.departure_cityname": options.sName,
      // "getMonthMsg.arrival_city": options.eId,
      // "getMonthMsg.ticketType": options.type,
      // "msg.ticketType": options.type,
    })
    this.getMinPrice()
    this.getForMonthMinPrice()
    this.getList()
  },
  childrenEvent: function (i) {
    console.log(i)
    this.data.getMonthMsg.flithtMonthDate = i.detail.date_str
    this.data.getMonthMsg.qFlightDateStart = i.detail.date_str + " 00:00:00"
    this.getMinPrice(i.detail.date_str)
    this.openDate()
    this.setData({
      "msg.qFlightDateStart": i.detail.date_str
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.initAirlines()
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})