const util = require("../../../../utils/util");
const app = getApp();
Component({
  properties: {
    chackedDate: {
      type: String,
      observer: function (newVal) {
        if (this.data.chackedDate){
          let arr = newVal.split('-');
          let newDate=arr[0]+'-'+parseInt(arr[1])+'-'+parseInt(arr[2]);
         
          this.setData({ 
            chackedDate: newDate,
            todayMonth:parseInt(arr[1]),
            todayYear:arr[0]
           });
        }
      }
    },
    leaderUid: {
      type: String,
      observer: function (newVal) {
        this.setData({leaderUid:newVal});
      }
    },
    show: {
      type: Boolean,
      observer: function (newVal) {
        let arr = this.data.chackedDate.split('-');
        this.setData({ 
          show: newVal,
          month:parseInt(arr[1]),
          year:arr[0]
        });
        if (this.data.show) this.onloadData();
      }
    },
  },
  data: {
    height:'65%',
    show:false,
    leaderUid:'',
    inputMonth:'',//传入的月份
    chackedDate:'',
    slideOne: "",  // 左右滑动的class样式
    slideFlag: false,  // 左右滑动定义的状态变量
    // 页面输出的数据
    week: ['日','一', '二', '三', '四', '五', '六'],
    months: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
    calendar:'',//输入日历
    month: new Date().getMonth() + 1,//当前页面的月
    year: new Date().getFullYear(),//当前页面的年
    today: '',//今天
    todaySecond: new Date().getTime(),//今天的秒
    todayYear: new Date().getFullYear(),//今天所在的年
    todayMonth: new Date().getMonth() + 1,//今天坐在的月
    clickDate:'',
    activeData:[],//活动列表
    imgPath: util.config.imgPath
  },
  methods: {
    // 弹窗关闭
    close(e) {
      this.triggerEvent("close", e.detail);
    },
    onloadData(){
      let date = new Date()
      this.setData({ 
        today: this.data.chackedDate? this.data.chackedDate : this.formatDate(),  
        clickDate: this.data.chackedDate? this.data.chackedDate : this.formatDate()   
      });
      this.generateAllDays(this.data.year, this.data.month)
      this.setBarTitle(this.data.todayMonth)
    },
    
  setBarTitle(month){
    this.setData({
      title:month + '月'
    })
  },
  digit: function (n) {
    if (n == null || n === "" || n == undefined) {
      return "";
    } else {
      n = n.toString();
      return n[1] ? n : '' + n;
    }
  },
  //生成日期格式：2019-5-7
  formatDate: function (date = new Date()) {
    // 年月日
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    // 返回值
    return [year, this.digit(month), this.digit(day)].map(this.digit).join('-');
  },
  //生成当前需要显示的全部日期
  generateAllDays(year, month) {
    let lastMonth = this.lastMonthDays(year, month),
        thisMonth = this.currentMonthDays(year, month),
        nextMonth = this.nextMonthDays(year, month),
        days = [].concat(lastMonth, thisMonth, nextMonth)
    let that =this,data={};
    data.startDate=days[0].date;
    data.endDate=days[days.length-1].date;
    if (that.data.leaderUid !='') {
      data.leaderUid=that.data.leaderUid
    }
    util.ajax({
      func: "v2/gwcourse/schedule",
      // data: { "startDate": days[0].date, "endDate": days[days.length-1].date }
      data:data
    }, function (res) {
      if (res.code == 0) {
        let data = res.data;
        if (!util.isObjEmpty(data)){
          days.forEach((item,index)=>{
             data.forEach((el,i)=>{
               if (util.formatDate(item.date,'yyyy-MM-dd', false) == el.date){
                item.num = el.num;
              }
            })
          })
        that.setData({ calendar: days});
        }
      }else{
        util.showTips(res.reason);
      }
    })
    that.setData({ calendar: days });
  },
  //生成需要显示的上月值
  lastMonthDays(year, month) {
    const lastMonth = parseInt(month)===1?12: parseInt(month) - 1,
      lastMonthYear = parseInt(month) === 1 && parseInt(lastMonth) === 12 ? `${parseInt(year) - 1}` : year,
        lastNum = this.getNumOfDays(lastMonthYear, lastMonth) //上月天数
    let startWeek = this.getWeekOfDate(year, month - 1, 1), days = []
    if (startWeek == 6) {
      return days
    }
    const startDay = lastNum - startWeek
    return this.generateDays(lastMonthYear, lastMonth, lastNum, { startNum: startDay, notCurrent: true })
  },
  //生成本月的值
  currentMonthDays(year, month) {
    const numOfDays = this.getNumOfDays(year, month)
    return this.generateDays(year, month, numOfDays)
  },
  /**
  * 生成下个月应显示天
  * @param {any} year 
  * @param {any} month
  * @returns 
  */
  nextMonthDays(year, month) {
    const nextMonth = parseInt(month) === 12?1:parseInt(month) + 1,
      nextMonthYear = parseInt(month) === 12 && parseInt(nextMonth) === 1 ? `${parseInt(year) + 1}` : year,
      nextNum = this.getNumOfDays(nextMonthYear, nextMonth) //下月天数
    let endWeek = this.getWeekOfDate(year, month), days = [], daysNum = 0
    if (endWeek == 6) {
      return days
    } else if (endWeek == 7) {
      daysNum = 6
    } else {
      daysNum = 6 - endWeek
    }
    return this.generateDays(nextMonthYear, nextMonth, daysNum, { startNum: 1, notCurrent: true })
  },
  //生成本月的上，或者中，或者下
  generateDays(year, month, daysNum, option = {startNum: 1, notCurrent: false}) {
    const weekMap = ['一', '二', '三', '四', '五', '六', '日']
    let days = []
    for (let i = option.startNum; i <= daysNum; i++) {
      let week = weekMap[new Date(year, month - 1, i).getUTCDay()]
      let day = i;
      days.push({
        date: `${year}-${month}-${day}`,
        event: false,
        day,
        week,
        month,
        year,
        dateSecond: new Date(`${year}/${month}/${day}`).getTime()
      })
    }
    return days
  },
  getNumOfDays(year, month, day = 0) {
    return new Date(year, month, day).getDate()
  },
  getWeekOfDate(year, month, day = 0) {
    let dateOfMonth = new Date(year, month, 0).getUTCDay() + 1;
    dateOfMonth == 7 ? dateOfMonth = 0 : '';
    return dateOfMonth;
  },
  formatDay(day) {
    return `${(day + '').length > 1 ? '' : '0'}${day}`
  },
  formatMonth(month) {
    let monthStr = ''
    if (month > 12 || month < 1) {
      monthStr = Math.abs(month - 12) + ''
    } else {
      monthStr = month + ''
    }
    monthStr = `${monthStr.length > 1 ? '' : '0'}${monthStr}`
    return monthStr
  },
  filterData(data){
    let n = data.map((item,index)=>{
      data[index].date = this.filterDate(item.date)
      return data[index]
      
    })
    return n;
  },
  //处理日期带0的格式
  filterDate(data){
    let date = data.split("-"),
        year = date[0],
        month = date[1] ,
        day = date[2] ;
      if(month.slice(0,1)==0) month = month.slice(1, 2);
      if(day.slice(0, 1) == 0) day = day.slice(1, 2);
    return `${year}-${month}-${day}`
  },
  touchStart(e) {
    this.setData({
      startX: e.changedTouches[0].pageX
    })
  },
  touchEnd(e) {
    if (!this.data.slideFlag) {
      this.setData({
        slideFlag: true,
        endX: e.changedTouches[0].pageX
      })
      let disX = e.changedTouches[0].pageX - this.data.startX;
      if (disX < -60) {
        this.setData({
          slideOne: "animated fadeOutLeft"
        })
        setTimeout(() => {
          this.tapNext();
        }, 300);
        setTimeout(() => {
          this.setData({
            slideFlag: false,
            slideOne: ""
          })
        }, 800);
      } else if (disX > 60) {
        let date = new Date();
        if ((this.data.year + '-' + this.data.month) == date.getFullYear() + '-' + (date.getMonth() + 1)){
          this.setData({
            slideFlag: false
          })
          return false;
        }
        
        this.setData({
          slideOne: "animated fadeOutRight"
        })
        setTimeout(() => {
          this.tapPrev();
        }, 300);
        setTimeout(() => {
          this.setData({
            slideFlag: false,
            slideOne: ""
          })
        }, 800);
      } else {
        this.setData({
          slideFlag: false
        })
      }
    }
  },
  /**
   * 左右滑动调用的函数
   */
  tapPrev() {//上一页
    let year = this.data.year, month = this.data.month;
    month--;
    if (month < 1) {
      year--;
      month = 12;
    }
    this.setBarTitle(month)
    this.getData(year, month)
  },
  tapNext() {//下一页
    let year = this.data.year, month = this.data.month;
    month++;
    if (month > 12){
      year++;
      month = 1;
    }
    this.setBarTitle(month)
    this.getData(year, month)
  },
  getData(year, month){
    this.setData({
       month, year
    })
    this.generateAllDays(year, month)
  },
  //点击具体的日期
  bindDayTap(e){
    let data = e.currentTarget.dataset;
    if (data.datesecond > this.data.todaySecond || data.date == this.data.today){//大于等于今天
      this.setData({ clickDate: data.date })
      if (data.month != this.data.month){
        this.getData(data.year, data.month)//获取上下月
        this.setBarTitle(data.month)
      }
      let date = data.year + "-" + this.formatMonth(data.month) + "-" + this.formatDay(data.day);
      this.getActiveDetail(date)
    }
  },
  getActiveDetail(date){
    this.setData({
      month:this.data.inputMonth
    })
    this.triggerEvent("getCalendarInfo", date);
  },
  }
})