// pages/leaveDetail/leaveDetail.js
const app = getApp()
const util = require("../../utils/util")
const urlDef = require("../../utils/urls")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: 0,
    array: ['事假', '病假', '其他'],
    item: {},
    content: ''
  },

  getText: function (e) {
    this.setData({ content: e.detail.value })
  },

  bindPickerChange: function (e) {
    const index = e.detail.value
    this.setData({
      index
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let o = JSON.parse(options.data)
    let s = o.source
    s.bt = s.beginTime.substring(0, 5)
    this.setData({ item: s })

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },
  toSave: function () {
    if (this.data.item.leaveCount <= 0) {
      wx.showToast({
        title: '该课程剩余请假次数不足,请联系前台!'
      });
      return;
    }
    const urls = urlDef.urls;
    let stu = wx.getStorageSync('student')
    util.apiPost(urls.get_params + '&q.orgId=' + stu.orgId + '&q.detailId=1000_1').then((rs) => {
      let timeoutDay = 0;
      if (rs && rs.length > 0) {
        timeoutDay = parseInt(rs[0].sysVal, 10);
      }
      if (timeoutDay > 0) {// 计算本课程上课时间,跟当前时间相隔多少天,这个天不能超过 timeoutDay
        let courseDate = new Date(this.data.item.attenceDate)
        let now = new Date();
        let day = Math.ceil((courseDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
        if (day > timeoutDay) { // 超过请假范围了
          wx.showToast({ title: '只能请' + timeoutDay + '天内的假' });
          return;
        }
      }
      let that = this
      wx.showModal({
        title: '确认信息',
        content: '确定要执行请假申请?',
        showCancel: true,
        cancelText: "否",
        confirmText: "是",
        success: function (res) {
          if (res.cancel) { } else {
            that.doRealSave()
          }
        }
      })
    });


  },
  doRealSave: function () {

    const urls = urlDef.urls;
    let stu = wx.getStorageSync('student')
    let today = util.curTime().substring(0, 10).replace(/\//g, '-')

    let leaveReason = this.data.array[this.data.index];
    if (this.data.index == 2) {
      leaveReason = this.data.content
    }
    let attenceData = {
      status: '1',
      studentId: stu.studentId,
      operator: stu.studentId,
      orgId: stu.orgId,
      leaveDate: today,
      leaveReason: leaveReason,
      goodList: [
        {
          beginTime: this.data.item.beginTime,
          attenceStudentId: this.data.item.id,
          attenceTeacherId: this.data.item.attenceTeacherId,
          kindId: this.data.item.kindId,
          status: this.data.item.status,
          switchingId: this.data.item.switchingId
        }
      ]
    };

    util.apiPost(urls.student_leave, attenceData, 'application/json').then(rs => {
      if (rs.message) {
        wx.showToast({
          title: '请假失败,' + rs.message,
          icon: 'none'
        })
        return
      }

      wx.showModal({
        title: '请假申请成功',
        content: '需要立即预约补课吗?',
        showCancel: true,
        cancelText: "取消",
        confirmText: "预约补课",
        success: function (res) {
          if (res.cancel) {
            setTimeout(() => {
              wx.navigateBack({
                delta: 1, // 返回上一级页面。
                success: function () {
                  console.log('成功!')
                }
              })
            }, 1000)
          } else {
            wx.redirectTo({
              url: "/pages/lessons/lessons"
            })
          }
        }
      })
    })
  }
})