// packageH/flightInformation/flightInformation.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    columns: [],
    pickerValue: [0, 0, 0],
    imgheights: 0,
    nowDate: Date.parse(new Date()),
    // 二期
    form: {
      destination: '',
      terminus: '',
      flight: '',
      isDateName: ''
    },
    calendarShow: false,
    selectShow: false,
    minDate: new Date(2010, 0, 1).getTime(),
    maxDate: new Date(2010, 0, 31).getTime(),
    morePage:1,
    page:1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      minDate: new Date(this.fun_date(1)).getTime()
    });
  },
  goDetail(){
    wx.navigateTo({
      url: '/packageH/flightInformation/flightInformationDetailList/flightInformationDetailList',
    });
  },
  inpDes(e) {
    this.setData({
      ['form.destination']: e.detail,
    });
  },
  inpTerm(e) {
    this.setData({
      ['form.terminus']: e.detail
    });
  },
  inpFlight(e) {
    this.setData({
      ['form.flight']: e.detail
    });
  },
  calendarTap() {
    this.setData({
      calendarShow: true
    });
  },
  onClose() {
    this.setData({
      calendarShow: false
    });
  },
  popClose(e) {
    this.setData({
      show: false
    });
  },
  popShow() {
    this.setData({
      show: true
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getData();
  },
  imageLoad(e) {
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      ratio = imgwidth / imgheight;
    var viewHeight = 750 / ratio;
    this.setData({
      imgheights: this.data.imgheights > viewHeight ? this.data.imgheights : viewHeight
    });
  },
  linkUrl(e) {
    console.log(e);
    let img = e.currentTarget.dataset.img;
    try {
      wx.navigateTo({
        url: img,
      });
    } catch (error) {
      wx.redirectTo({
        url: img,
      });
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

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

  },

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

  },

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

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

  },
  dfsave(e) {
    let arr = e.detail;
    let json = {
      start_id: this.data.start_id,
      destination_id: this.data.destination_id,
      flight_id: this.data.flight_id,
      form_id: this.data.goodDYDormID,
      form_data: JSON.stringify(arr),
      form_data_id: this.data.form_data_id ? this.data.form_data_id : "",
      flight_time: this.data.flight_time
    };
    let that = this;
    console.log(json);
    let urlStr = app.getNetAddresss('plugin.flight-collect.frontend.index.save-diy-form-data');
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            title: '提交成功',
            icon: 'none',
            duration: 1000
          });
          that.setData({
            start_id:'',
            destination_id:'',
            flight_id:'',
            flight_time:'',
            form:{
              destination: '',
              terminus: '',
              flight: '',
              isDateName: ''
            }
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1000
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },
  gofunarr() {
    if(app._isTextEmpty(this.data.start_id)){
      wx.showToast({
        title: '请填写出发地',
        duration:1000,
        icon:'none'
      });
      return;
    }
    if(app._isTextEmpty(this.data.destination_id)){
      wx.showToast({
        title: '请填写目的地',
        duration:1000,
        icon:'none'
      });
      return;
    }
    if(app._isTextEmpty(this.data.flight_id)){
      wx.showToast({
        title: '请填写航班',
        duration:1000,
        icon:'none'
      });
      return;
    }
    if(app._isTextEmpty(this.data.flight_time)){
      wx.showToast({
        title: '请填写飞行计划日期',
        duration:1000,
        icon:'none'
      });
      return;
    }

    let that = this;
    if (this.data.info.is_submit) {
      // 指定时间限制
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let start_Min = Date.parse(`${year}/${month}/${day} ${that.data.startTime}:00`);
      let end_Min = Date.parse(`${year}/${month}/${day} ${that.data.endTime}:00`);
      if (that.data.nowDate >= start_Min && that.data.nowDate <= end_Min) {
        that.setData({
          ['info.is_submit']: 1
        });
        let child = this.selectComponent('.dsfrom');
        child.submit();
      } else {
        that.setData({
          ['info.is_submit']: 0
        });
        return;
      }
    }

  },
  getData() {
    let that = this;
    let urlStr = app.getNetAddresss('plugin.flight-collect.frontend.index');
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          let _tips = res.data.information.replace(/<img/g, '<img style="width:100%"');
          res.data.form_data.status = 0;
          that.setData({
            columns: res.data.flight,
            information: _tips,
            info: res.data,
            goodDYDormID: res.data.diyform,
            dfData: res.data.form_data,
            startTime: res.data.hours_start,
            endTime: res.data.hours_end,
          });
          if (res.data.is_submit) {
            // 指定时间限制
            let date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            console.log(year, month, day);
            let start_Min = Date.parse(`${year}/${month}/${day} ${res.data.hours_start}:00`);
            let end_Min = Date.parse(`${year}/${month}/${day} ${res.data.hours_end}:00`);
            if (that.data.nowDate >= start_Min && that.data.nowDate <= end_Min) {
              that.setData({
                ['info.is_submit']: 1
              });
            } else {
              that.setData({
                ['info.is_submit']: 0
              });
            }
            if (res.data.flight_time) {
              let fun = that.fun_date(Number(res.data.flight_time));
              console.log(fun);
              let timeset = new Date(fun).getTime();
              console.log(timeset);
              that.setData({
                maxDate: timeset
              });
            }
          }

          if (res.data.form_data) {
            // 已填回显处理
            if (res.data.form_data.form_data_id) {
              // 编辑提交的id
              that.setData({
                form_data_id: res.data.form_data.form_data_id,
              });
            }

          }
        } else {
          console.log(res.msg);
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },
  bindChange(e) {
    this.setData({
      pickerValue: e.detail.value
    });
  },
  search(e) {
    console.log(e);
    let key = e.currentTarget.dataset.key;
    if (key == 'des') {
      this.setData({
        noKey: 'des',
        selectShow: true,
        moreList: []
      });
      let e = {
        detail: this.data.form.destination
      };
      this.searchGinfo(e);
    }
    if (key == 'ter') {
      // this.searchGinfo(this.data.form.destination,key);
      this.setData({
        noKey: 'ter',
        selectShow: true,
        moreList: []
      });
      let e = {
        detail: this.data.form.terminus
      };
      this.searchGinfo(e);
    }
    if (key == 'fli') {
      this.setData({
        noKey: 'fli',
        moreList: [],
        selectShow: true,
      });
      let e = {
        detail: this.data.form.flight
      };
      this.searchFlight(e);
    }
  },
  tapSelect(e) {
    console.log(e);
    let item = e.currentTarget.dataset.item;
    console.log(this.data.noKey);
    if (this.data.noKey == 'des') {
      this.setData({
        start_id: item.id,
        ['form.destination']: item.flight_city_name
      });
      console.log(item, this.data.start_id);
    } else if (this.data.noKey == 'ter') {
      this.setData({
        destination_id: item.id,
        ['form.terminus']: item.flight_city_name
      });
      console.log(item, this.data.start_id);
    } else if (this.data.noKey == 'fli') {
      // this.flight_id = item.id;
      // this.form.flight = item.flight_number;
      this.setData({
        flight_id: item.id,
        ['form.flight']: item.flight_number
      });
    }
    this.setData({
      selectShow: false
    });
  },
  // 搜索航班
  searchFlight(info,key) {
    let that = this;
    wx.showLoading({
      title: '加载中',
    });
    let urlStr = app.getNetAddresss('plugin.flight-collect.frontend.index.get-flight-number');
    app._getNetWork({
      url: urlStr,
      data: {
        keyword: info.detail
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          if(key == 'more'){
            this.setData({
              moreList: that.data.moreList.concat(res.data.data),
            });
          }else{
            this.setData({
              moreList: res.data.data,
            });
          }
          
          wx.hideLoading({
            success: (res) => {},
          });
        } else {
          wx.hideLoading({
            success: (res) => {},
          });
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1000
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },
  selectShowClose() {
    this.setData({
      selectShow: false
    });
  },
  tapMore(){
    let key = this.data.noKey;
    this.setData({
      page : this.data.page + 1
    });
    if(key == 'fli'){
      let e = {
        detail: this.data.form.flight
      };
      this.searchFlight(e,'more');
    }else{
      let e = {
        detail: this.data.form.terminus
      };
      this.searchGinfo(e,'more');
    }
  },
  // 搜索城市
  searchGinfo(info,key) {
    // this.noKey = key;
    console.log(info);
    if(key != 'more'){
      this.setData({
        page:1
      });
    }
    let that = this;
    let urlStr = app.getNetAddresss('plugin.flight-collect.frontend.index.get-city');
    app._getNetWork({
      url: urlStr,
      data: {
        keyword: info.detail,
        page:this.data.page
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          if(key == 'more'){
            this.setData({
              moreList: that.data.moreList.concat(res.data.data),
              morePage:res.data.last_page
            });
          }else{
            this.setData({
              moreList: res.data.data,
              morePage:res.data.last_page
            });
          }
          
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1000
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },
  onConfirm(e) {
    // console.log(e)
    let date = e.detail;
    this.calendarShow = false;
    let timestr = (this.formartDateTime(this.formatDate(date)) / 1000);
    this.setData({
      calendarShow: false,
      ['form.isDateName']: this.formatDate(date),
      flight_time: timestr
    });
  },
  formatDate(date) {
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  },
  formartDateTime(dateStr) {
    dateStr = dateStr.replace(/-/g, '/');
    dateStr = dateStr + " 00:00:00";
    var timestamp = new Date(dateStr).getTime();
    return timestamp;
  },
  // onConfirm(e) {
  //   let pickerValue = this.data.pickerValue;
  //   this.setData({
  //     columnsShow: false,
  //     start_id: this.data.columns[pickerValue[0]].start_id,
  //     destination_id: this.data.columns[pickerValue[0]].children[pickerValue[1]].destination_id,
  //     flight_id: this.data.columns[pickerValue[0]].children[pickerValue[1]].children[pickerValue[2]].flight_id,
  //     start_name: this.data.columns[pickerValue[0]].text,
  //     destination_name: this.data.columns[pickerValue[0]].children[pickerValue[1]].text,
  //     flight_name: this.data.columns[pickerValue[0]].children[pickerValue[1]].children[pickerValue[2]].text
  //   });
  //   console.log(this.data);
  // },
  tapShow() {
    this.setData({
      columnsShow: true
    });
  },
  tapCanle() {
    this.setData({
      columnsShow: false
    });
  },
  fun_date(num) {
    var date1 = new Date();
    //今天时间
    var time1 = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate();
    console.log(time1);
    var date2 = new Date(date1);
    date2.setDate(date1.getDate() + num);
    //num是正数表示之后的时间，num负数表示之前的时间，0表示今天
    var time2 = Number(date2.getFullYear()) + "/" + Number(date2.getMonth() + 1) + "/" + Number(date2.getDate());
    return time2;
  },
});