// component/datepick/datepick.js
var Moment = require("moment.js");
var DATE_LIST = [];
var DATE_YEAR = new Date().getFullYear();
var DATE_MONTH = new Date().getMonth() + 1;
var DATE_DAY = new Date().getDate();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    phbname: String
  },

  /**
   * 组件的初始数据
   */
  data: {
    indicatordots: false,
    pickindex: 1,
    maxMonth: 5,
    days: [],
    years: [],
    months: [
      [1, 2, 3, 4, 5, 6],
      [7, 8, 9, 10, 11, 12]
    ],
    phbs: [{
      name: '供应商排行榜',
      key: 1
    }, {
      name: '商品排行榜',
      key: 2
    }],
    phbindex: 0,
    weekStr: ['日', '一', '二', '三', '四', '五', '六'],
    stime: '',
    etime: '',
    isshow4: false,
    scrollinto: 'idaaa',
    dateList: [],
    firsttime: true
  },
  ready() {
    var _this = this;
    var si = wx.getStorageSync('systemInfo')
    if (si) {
      this.setData({
        systemInfo: si
      });
    } else {
      wx.getSystemInfo({
        success: function(res) {
          _this.setData({
            systemInfo: res

          });
          wx.setStorageSync('systemInfo', res)
        }
      })
    }
    this.inityear()
    this.initmonth()
    //console.log(this.properties.phbname)
    this.setData({
      phbname: this.properties.phbname
    })
    this.createDateListData()

  },

  /**
   * 组件的方法列表
   */
  methods: {
    siscroll(e) {
      this.createDateListData()
    },
    phbchange(e) {
      console.log(e.detail.value)
      this.setData({
        phbindex: e.detail.value
      })
      this.triggerEvent('typechange', {
        type: parseInt(e.detail.value) + 1
      }, {
        bubbles: false, //事件是否冒泡
        composed: false, //事件是否可以穿越组件边界
        capturePhase: false //事件是否拥有捕获阶段
      })
    },
    databack() {
      this.triggerEvent('click', {
        type: this.data.pickindex,
        day: this.data.nowday.toString().padStart(2, '0'),
        month: this.data.nowmonth.toString().padStart(2, '0'),
        year: this.data.nowyear,
        stime: this.data.stime,
        etime: this.data.etime
      }, {
        bubbles: false, //事件是否冒泡
        composed: false, //事件是否可以穿越组件边界
        capturePhase: false //事件是否拥有捕获阶段
      })
    },

    daysel(e) {
      this.setData({
        nowday: e.currentTarget.dataset.day
      })
      this.databack()
    },
    monthsel(e) {
      this.setData({
        nowmonth: e.currentTarget.dataset.month
      })
      this.initdays(1)
      this.databack()
    },
    yearsel(e) {
      this.setData({
        nowyear: e.currentTarget.dataset.year
      })
      this.databack()
    },
    initdays(kind) {
      var daynum = new Date(this.data.nowyear, this.data.nowmonth, 0).getDate()
      var nowday = new Date().getDate()
      var dayindex = 0
      var days = []
      for (var i = 1; i <= daynum; i++) {
        var x = parseInt(i / 7)
        if (!days[x]) {
          days[x] = []
        }
        if (i === nowday) {
          dayindex = x
        }
        days[x].push(i)
      }
      console.log(days)
      this.setData({
        days: days,
        nowday: nowday,
        dayindex: dayindex
      })
      if (!kind) {
        this.databack()
      }
    },

    initmonth() {
      this.setData({
        nowmonth: new Date().getMonth() + 1,
        monthindex: parseInt((new Date().getMonth() + 1) / 7)
      })
      this.initdays()
    },
    yearchange(e) {
      if (e.detail.current === 0) {
        this.addyears()
      }
    },

    addyears() {
      var years = this.data.years
      var firstyear = years.length > 0 ? years[1][0] : this.data.nowyear
      for (var i = 0; i < 4; i++) {
        var y = []
        for (var j = 0; j < 5; j++) {
          y.unshift(firstyear - (i * 5 + j))
        }
        years.unshift(y)
      }
      this.setData({
        years: years,
        yearindex: this.data.yearindex ? this.data.yearindex : years.length - 1
      })

    },
    inityear() {
      this.setData({
        nowyear: new Date().getFullYear()
      })
      this.addyears()
    },



    getTotalDayByMonth: function(year, month) {
      month = parseInt(month, 10);
      var d = new Date(year, month, 0);
      return d.getDate();
    },
    /*
     * 获取月的第一天是星期几
     */
    getWeek: function(year, month, day) {
      var d = new Date(year, month - 1, day);
      return d.getDay();
    },
    setindex(e) {
      var index = parseInt(e.currentTarget.dataset.index)
      this.setData({
        pickindex: index
      })
      if (index === 1 && this.data.nowday) {
        this.databack()
      }
      if (index === 2 && this.data.nowmonth) {
        this.databack()
      }
      if (index === 3 && this.data.nowyear) {
        this.databack()
      }
      if (index === 4 && this.data.stime && this.data.etime) {
        this.databack()
      }

    },
    hidetime() {
      this.setData({
        isshow4: false,
      })
    },
    setime() {

      this.setData({

        isshow4: true,
      })
      this.freshPressStyle()
      if (this.data.firsttime) {
        var now = new Date();
        this.setData({
          scrollinto: 'idaaa',
          firsttime: false
        })
      }
      if (this.data.stime) {
        var st = this.data.stime.split('-')
        this.renderPressStyle(st[0], parseInt(st[1]), parseInt(st[2]), true)
      }
      if (this.data.etime) {
        var st = this.data.etime.split('-')
        this.renderPressStyle(st[0], parseInt(st[1]), parseInt(st[2]), false)
      }
    },
    onPressDate: function(e) {
      var {
        year,
        month,
        day
      } = e.currentTarget.dataset;
      //当前选择的日期为同一个月并小于今天，或者点击了空白处（即day<0），不执行
      // if ((day < DATE_DAY && month == DATE_MONTH) || day <= 0) return;
      this.freshPressStyle()
      var tempMonth = month;
      var tempDay = day;

      if (month < 10) tempMonth = '0' + month
      if (day < 10) tempDay = '0' + day

      var date = year + '-' + tempMonth + '-' + tempDay;

      if (this.data.markcheckInDate) {
        if (date < this.data.checkInDate) {
          wx.showToast({
            title: '返程日期不能早于出发日期',
            icon: 'none',
            duration: 2000
          })
          return
        }
        this.setData({
          checkOutDate: date,
          markcheckInDate: false,
          dateList: DATE_LIST.concat()
        })
      } else {
        this.setData({
          checkInDate: date,
          markcheckInDate: true,
          dateList: DATE_LIST.concat()
        });
      }

      //设缓存，返回页面时，可在onShow时获取缓存起来的日期
      wx.setStorage({
        key: 'ROOM_SOURCE_DATE',
        data: {
          checkInDate: this.data.checkInDate,
          checkOutDate: this.data.checkOutDate
        }
      });
      // wx.navigateBack({
      //   delta: 1, // 回退前 delta(默认为1) 页面
      // });
      this.renderPressStyle(year, month, day, this.data.markcheckInDate);
      if (!this.data.markcheckInDate) {
        this.setData({
          stime: this.data.checkInDate,
          etime: this.data.checkOutDate,
          isshow4: false,
          pickindex: 4
        })
        this.databack()
      }

    },
    freshPressStyle() {
      var dateList = this.data.dateList;
      //渲染点击样式
      for (var i = 0; i < dateList.length; i++) {
        var dateItem = dateList[i];

        var days = dateItem.days;
        for (var j = 0; j < days.length; j++) {
          days[j].class = days[j].class.split(' ')[0]
          delete days[j].inday
          delete days[j].outday
        }

      }
      this.setData({
        dateList: dateList
      });
    },
    renderPressStyle: function(year, month, day, inorout) {
      var dateList = this.data.dateList;
      //渲染点击样式
      for (var i = 0; i < dateList.length; i++) {
        var dateItem = dateList[i];
        var id = dateItem.id;
        if (id === year + '-' + month) {
          var days = dateItem.days;
          for (var j = 0; j < days.length; j++) {
            // if (days[j].day >= day) {
            //   days[j].class = days[j].class + ' bgitem';
            // } else {
            //   days[j].class = ''
            // }
            var tempDay = days[j].day;
            if (tempDay == day) {
              days[j].class = days[j].class + ' active';
              if (inorout) {
                days[j].inday = true;
              } else {
                days[j].outday = true;
              }
              break;
            }
          }
          break;
        }
      }
      this.setData({
        dateList: dateList
      });
    },
    createDateListData: function() {
      wx.showLoading({
        title: '',
      })
      var dateList = this.data.dateList;
      var now
      var scrollid = ''
      /*
      设置日期为 年-月-01,否则可能会出现跨月的问题
      比如：2017-01-31为now ,月份直接+1（now.setMonth(now.getMonth()+1)），则会直接跳到跳到2017-03-03月份.
        原因是由于2月份没有31号，顺推下去变成了了03-03
    */
      if (dateList.length == 0) {
        now = new Date();
        now = new Date(now.getFullYear(), now.getMonth(), 1);
      } else {
        now = new Date(dateList[0].year, dateList[0].month, 1);
        scrollid = 'id' + dateList[0].year + 'a' + dateList[0].month
        now.setMonth(now.getMonth() - 2)
      }

      for (var i = 0; i >= 0 - this.data.maxMonth; i--) {
        var momentDate = Moment(now).add(this.data.maxMonth - (this.data.maxMonth - i), 'month').date;
        var year = momentDate.getFullYear();
        var month = momentDate.getMonth() + 1;

        var days = [];
        var totalDay = this.getTotalDayByMonth(year, month);
        var week = this.getWeek(year, month, 1);
        //-week是为了使当月第一天的日期可以正确的显示到对应的周几位置上，比如星期三(week = 2)，
        //则当月的1号是从列的第三个位置开始渲染的，前面会占用-2，-1，0的位置,从1开正常渲染
        for (var j = -week + 1; j <= totalDay; j++) {
          var tempWeek = -1;
          if (j > 0)
            tempWeek = this.getWeek(year, month, j);
          var clazz = '';
          if (tempWeek == 0 || tempWeek == 6)
            clazz = 'week'
          /** if (j < DATE_DAY && year == DATE_YEAR && month == DATE_MONTH)
             //当天之前的日期不可用
             clazz = 'unavailable ' + clazz;
           else
             clazz = '' + clazz
             **/
          days.push({
            day: j,
            class: clazz
          })
        }
        var dateItem = {
          id: year + '-' + month,
          year: year,
          month: month,
          days: days

        }

        dateList.unshift(dateItem);
      }
      // var sFtv = this.data.sFtv;
      // for (let i = 0; i < dateList.length; i++) { //加入公历节日
      //   for (let k = 0; k < sFtv.length; k++) {
      //     if (dateList[i].month == sFtv[k].month) {
      //       let days = dateList[i].days;
      //       for (let j = 0; j < days.length; j++) {
      //         if (days[j].day == sFtv[k].day) {
      //           days[j].daytext = sFtv[k].name
      //         }
      //       }
      //     }
      //   }
      // }
      this.setData({
        dateList: dateList,
        //+ dateList[0].year + 'a' + dateList[0].month

      }, function() {
        this.setData({
          scrollinto: scrollid
        })
      });
      DATE_LIST = dateList;
      wx.hideLoading()
    }
  }
})