// pages/change_course/change_course.js
const { formatNumber } = require('../../utils/util.js')
const { thisMonthLenth } = require('../../utils/changeCourseTime.js')
const app = getApp()
const DATE = new Date()
const yearList = []
const monthList = []
const dayList = []
const nowYear = DATE.getFullYear()
const nowMonth = DATE.getMonth() + 1
const nowDay = DATE.getDate()
const nowDate = `${formatNumber(nowYear)}/${formatNumber(nowMonth)}/${formatNumber(nowDay)}`

for (let i = nowYear; i <= nowYear + 10; i++) {
  yearList.push(i)
}

for (let i = 1; i <= 12; i++) {
  monthList.push(i)
}

for (let i = 1; i <= 31; i++) {
  dayList.push(i)
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShowModal: false,
    yearList,
    monthList,
    dayList,
    dateValue: [0, 0, 0],
    adjustReason: '',
    oldPlanTime: '',
    currentPlanTime: '',
    nowYear,
    nowMonth,
    nowDay,
    nowDate,
    year: nowYear,
    month: nowMonth,
    day: nowDay,
    weeks: [
      {
        text: '周一'
      },
      {
        text: '周二'
      },
      {
        text: '周三'
      },
      {
        text: '周四'
      },
      {
        text: '周五'
      },
      {
        text: '周六'
      },
      {
        text: '周日'
      }
    ],
    daysIndex: -1,
    days: [],
    oldDate: '',
    oldTime: '',
    newDate: '',
    newTime: '',
    items: [
      {
        text: '临时有其他安排',
        style: ''
      },
      {
        text: '假期旅游',
        style: ''
      },
      {
        text: '学校调课',
        style: ''
      },
      {
        text: '考前冲刺',
        style: ''
      },
      {
        text: '期末复习',
        style: ''
      },
      {
        text: '临时加课',
        style: ''
      },
      {
        text: '学生状态不好',
        style: ''
      },
      {
        text: '家长要求',
        style: ''
      },
      {
        text: '老师个人原因',
        style: ''
      }
    ],
    timeValue: [0],
    timeList: [
      // {
      //   "startTime": "08:00",
      //   "endTime": "10:00"
      // },
      // {
      //   "startTime": "10:00",
      //   "endTime": "12:00"
      // },
      // {
      //   "startTime": "15:30",
      //   "endTime": "17:30"
      // }
    ],
    courseList: [
      // {
      //   "date": "2018-09-10",
      //   "type": 1,
      //   "courses": [
      //     {
      //       "courseId": "12131313132",
      //       "startTime": "09:00",
      //       "endTime": "11:00"
      //     },
      //     {
      //       "courseId": "12131313132",
      //       "startTime": "09:00",
      //       "endTime": "11:00"
      //     }
      //   ]
      // },
      // {
      //   "date": "2018-10-01",
      //   "type": 1,
      //   "courses": [
      //     {
      //       "courseId": "12131313132",
      //       "startTime": "09:00",
      //       "endTime": "11:00"
      //     },
      //     {
      //       "courseId": "12131313132",
      //       "startTime": "09:00",
      //       "endTime": "11:00"
      //     }
      //   ]
      // },
      // {
      //   "date": "2018-10-02",
      //   "type": 2,
      //   "courses": [
      //     {
      //       "courseId": "12131313132",
      //       "startTime": "09:00",
      //       "endTime": "11:00"
      //     },
      //     {
      //       "courseId": "12131313132",
      //       "startTime": "09:00",
      //       "endTime": "11:00"
      //     },
      //     {
      //       "courseId": "12131313132",
      //       "startTime": "09:00",
      //       "endTime": "11:00"
      //     },
      //     {
      //       "courseId": "12131313132",
      //       "startTime": "09:00",
      //       "endTime": "11:00"
      //     },
      //     {
      //       "courseId": "12131313132",
      //       "startTime": "09:00",
      //       "endTime": "11:00"
      //     },
      //     {
      //       "courseId": "12131313132",
      //       "startTime": "09:00",
      //       "endTime": "11:00"
      //     },
      //     {
      //       "courseId": "12131313132",
      //       "startTime": "09:00",
      //       "endTime": "11:00"
      //     },
      //     {
      //       "courseId": "12131313132",
      //       "startTime": "09:00",
      //       "endTime": "11:00"
      //     }
      //   ]
      // },
      // {
      //   "date": "2018-10-10",
      //   "type": 3,
      //   "courses": [
      //     {
      //       "courseId": "12131313132",
      //       "startTime": "09:00",
      //       "endTime": "11:00"
      //     },
      //     {
      //       "courseId": "12131313132",
      //       "startTime": "09:00",
      //       "endTime": "11:00"
      //     }
      //   ]
      // },
      // {
      //   "date": "2018-10-15",
      //   "type": 3,
      //   "courses": [
      //     {
      //       "courseId": "12131313132",
      //       "startTime": "09:00",
      //       "endTime": "11:00"
      //     },
      //     {
      //       "courseId": "12131313132",
      //       "startTime": "09:00",
      //       "endTime": "11:00"
      //     }
      //   ]
      // }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ options })
    console.log(options)
    this.getCourseList()
  },

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

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

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

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

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getCourseList(res => {
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },
  true:function(){},
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (app.sharePageDefaultCtl) {
      return app.sharePageDefaultCtl()
    }
  },

  /**
   * 获取所有排课列表
   */
  getCourseList: function (cb) {
    const postData = { fn: this.getCourseList, param: { ...arguments } }
    const { year, month, options } = this.data
    const time = `${formatNumber(year)}-${formatNumber(month)}-01`
    const { bizId } = options
    app.post('/api/parents/parents/V2/getStudentCourseData', { bizId, time }, 0, postData).then(res => {
      this.setData({ courseList: res.data.list || [] })
      this.getCalendar()
      cb && cb()
    }).catch(res => {
      cb && cb()
    })
  },

  /**
   * 获取新日期下所有新时间段
   */
  getTimeList: function () {
    const { options, newDate } = this.data
    const { teacherId } = options
    const queryTime = newDate
    const postData = { fn: this.getTimeList, param: { ...arguments } }
    app.post('/api/parents/parents/V2/getTeacherCourseTimeDetail', { teacherId, queryTime }, 0, postData).then(res => {
      const { list } = res.data
      if (list.length > 0) {
        this.setData({ timeList: list, timeValue: [0], newTime: list[0]['startTime'] + ':00', currentPlanTime: newDate + ' ' + list[0]['startTime'] + ':00' })
      } else {
        this.setData({ timeList: [], newTime: '', currentPlanTime: ''})
        wx.showToast({
          title: '当天无空挡,请重选日期',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 获取日历
   */
  getCalendar: function () {
    const { year, month, courseList, nowDate, oldDate } = this.data
    const week = new Date(`${year}/${month}/01`).getDay() || 7
    const days = []
    for (let i = 1; i < week; i++) {
      days.push({
        text: '',
        isActive: 0,
      })
    }
    for (let i = 1; i < thisMonthLenth(year, month) + 1; i++) {
      const dateTemp = `${formatNumber(year)}/${formatNumber(month)}/${formatNumber(i)}`
      const date = `${formatNumber(year)}-${formatNumber(month)}-${formatNumber(i)}`
      const isLess = new Date(dateTemp) < new Date(nowDate)
      days.push({
        date,
        text: formatNumber(i),
        isLess,
        type: 0,
        isActive: 0,
        courses: [],
        coursesIndex: -1
      })
    }
    let isActive = false
    let daysIndex = -1
    let date = oldDate
    for (let i in days) {
      for (let j in courseList) {
        if (days[i]['date'] == courseList[j]['date']) {
          days[i]['type'] = courseList[j]['type']
          days[i]['courses'] = courseList[j]['courses']
          if (!isActive && (courseList[j]['type'] == 2 || courseList[j]['type'] == 3)) {
            days[i]['isActive'] = 1
            daysIndex = i
            date = days[i]['date']
            isActive = true
          }
        }
      }
    }
    this.setData({ days, daysIndex, oldDate: date })
  },

  /**
   * 切换年月
   */
  checkMonthCtl: function (e) {
    const { type } = e.currentTarget.dataset
    let { year, month } = this.data
    if (type == 1) {
      if (month < 2) {
        month = 12
        year--
      } else {
        month--
      }
    } else if (type == 2) {
      if (month > 11) {
        month = 1
        year++
      } else {
        month++
      }
    }
    this.setData({ year, month })
    this.getCourseList()
  },

  /**
   * 选择需要调课日期
   */
  checkDayCtl: function (e) {
    const { index } = e.currentTarget.dataset
    const { days, daysIndex } = this.data
    const { courses, type, isActive, date, text } = days[index]
    if (daysIndex == index || isActive) {
      return
    }
    if (!(type == 2 || type == 3)) {
      wx.showToast({
        title: '只能选择未上过课日期',
        icon: 'none'
      })
      return
    }
    const temp = {}
    for (let i in days) {
      if (i == index) {
        days[i]['isActive'] = 1
      } else {
        days[i]['isActive'] = 0
      }
    }
    this.setData({ days, daysIndex: index, oldDate: date, day: text })
  },

  /**
   * 选择需要调课时间段
   */
  checkTimeCtl: function (e) {
    const { index } = e.currentTarget.dataset
    const { days, daysIndex, yearList, monthList, dayList, oldDate } = this.data
    const { courses, coursesIndex, date } = days[daysIndex]
    const { courseId, startTime, endTime } = courses[index]
    const dateValue = ((v, a) => {
      const arr = []
      for (let i in v) {
        for (let j in a[i]) {
          if (v[i] == a[i][j]) {
            arr.push(j)
            break
          }
        }
      }
      return arr
    })(date.split('-'), [yearList, monthList, dayList])
    days[daysIndex].coursesIndex = index
    this.setData({ days, dateValue, bizId: courseId, oldTime: startTime + ':00', oldPlanTime: oldDate + ' ' + startTime + ':00', newDate: oldDate, isShowModal: true})
    this.getTimeList()
  },

  /**
   * 获取新调课日期
   */
  changeDateCtl: function (e) {
    const { value } = e.detail
    const { yearList, monthList, dayList, dateValue, nowDate } = this.data
    const { date, year, month, day} = ((v, a) => {
      const date = [], 
      year = formatNumber(a[0][v[0]]),
      month = formatNumber(a[1][v[1]]),
      day = formatNumber(a[2][v[2]])
      for (let i in v) {
        date.push(formatNumber(a[i][v[i]]))
      }
      return { date: date.join('-'), year, month, day }
    })(value, [yearList, monthList, dayList])
    if (thisMonthLenth(year, month) < day) {
      wx.showToast({
        title: '当前月份没有该天,请重新选择',
        icon: 'none'
      })
      this.setData({ dateValue })
      return
    }
    if (new Date(date.replace(/\-/g, '/')) < new Date(nowDate)) {
      wx.showToast({
        title: '不能选择今天之前的日期',
        icon: 'none'
      })
      this.setData({ dateValue })
      return
    }
    this.setData({ newDate: date, dateValue: value })
    this.getTimeList()
  },

  /**
   * 获取新调课时间段
   */
  changeTimeCtl: function (e) {
    const { value } = e.detail
    const { timeList, newDate } = this.data
    this.setData({ timeValue: value, newTime: timeList[value[0]]['startTime'] + ':00', currentPlanTime: newDate + ' ' + timeList[value[0]]['startTime'] + ':00'})
  },

  /**
   * 选择调课事由
   */
  checkReasonCtl: function (e) {
    const { index } = e.currentTarget.dataset
    let { items, adjustReason } = this.data
    if (items[index]['style'] == 'active') {
      return
    }
    for (let i in items) {
      if (i == index) {
        items[i]['style'] = 'active'
        adjustReason = items[i]['text']
      } else {
        items[i]['style'] = ''
      }
    }
    this.setData({ items, adjustReason })
  },

  /**
   * 确定调课
   */
  submitCtl: function (e) {
    const { type } = e.currentTarget.dataset
    this.setData({ isShowModal: false })
    if (type == 1) {
      const { oldPlanTime, currentPlanTime, oldDate, oldTime, newDate, newTime, adjustReason, bizId } = this.data
      if (!newTime) {
        wx.showToast({
          title: '请选择调课时间段',
          icon: 'none'
        })
        return
      }
      if (!adjustReason) {
        wx.showToast({
          title: '请选择调课事由',
          icon: 'none'
        })
        return
      }
      console.log(JSON.stringify({ bizId, oldPlanTime, adjustReason, currentPlanTime }))
      const postData = { fn: this.submitCtl, param: { ...arguments } }
      app.post('/api/parents/parents/V2/applyCourseTime', { courseId:bizId, oldPlanTime, adjustReason, currentPlanTime }, 0, postData).then(res => {
        wx.showToast({
          title: '调课成功'
        })
        this.getCourseList()
        setTimeout(() => {
          wx.showModal({
            title: '',
            content: '是否继续调课?',
            success: res => {
              if (res.cancel) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
        }, 800)
      }).catch(res => {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      })
    }
  }
})