const app = getApp()
const util = require("../../../utils/util");
const mallapi = require('../../../api/mall.js');
var dateTimePicker = require('../../../utils/dateTimePicker.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    leaveTypeList: [],
    subTypeList: [],
    arrnameA: ['请选择'],
    arrnameB: [],
    chooseLeaveTypeIndex: 0,
    chooseLeaveTypeValue: null,
    chooseLeaveSubIndex: 0,
    chooseLeaveSubValue: null,

    leaveStartTime: null,
    leaveEndTime: null,
    leaveReason: null,


    dateTimeKS: '', //插件日期
    dateTimeJS: '', //插件日期
    dateTimeArray: '', //插件日期
    // startT: '',

    picUrls: [],
    files: [],
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let index = e.detail.value - 1;
    if (index == -1) {
      return;
    }

    let temparr = this.data.leaveTypeList[index].subList;
    let tempB = [];
    temparr.forEach(c => {
      tempB.push(c.typeName);
    })

    this.setData({
      chooseLeaveTypeValue: this.data.leaveTypeList[index].id,
      chooseLeaveTypeIndex: index + 1,
      subTypeList: temparr,
      arrnameB: tempB,
      chooseLeaveSubValue: temparr[0].id,
    })
  },

  bindPickerChangeB: function (e) {
    console.log('pickerB发送选择改变，携带值为', e.detail.value)
    this.setData({
      chooseLeaveSubValue: this.data.subTypeList[e.detail.value].id,
      chooseLeaveSubIndex:e.detail.value
    })
  },
  changeDateTime(e) {
    //获取时间日期 
    // console.log(e.detail.value);
    let leaveStartTime = dateTimePicker.formatPickerDateTime(this.data.dateTimeArray, e.detail.value)
    this.setData({
      dateTimeKS:e.detail.value,
      leaveStartTime: leaveStartTime,
    })
  },
  changeDateTimeEnd(e) {
    //获取时间日期 
    // console.log(e.detail.value);
    let leaveEndTime = dateTimePicker.formatPickerDateTime(this.data.dateTimeArray, e.detail.value)
    this.setData({
      dateTimeJS:e.detail.value,
      leaveEndTime: leaveEndTime,
    })
  },
  bindleaveReason(e){
    this.setData({
      leaveReason: e.detail.value,
    })
  },

  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },

  chooseImage: function (e) {
    if (this.data.files.length >= 4) {
      util.showErrorToast('只能上传四张图片')
      return false;
    }

    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
        console.info(res.tempFilePaths[0])
        that.upload(res)

      }
    })
  },


  upload: function (res) {
    var that = this;
    const uploadTask = wx.uploadFile({
      url: mallapi.StorageUpload(),
      filePath: res.tempFilePaths[0],
      name: 'file',
      formData:{'X-JZ-Token':wx.getStorageSync('token')},
      success: function (res) {
        var _res = JSON.parse(res.data);
        if (_res.errno === 0) {
          var url = _res.data.fileUrl
          var pics = that.data.picUrls;
          pics.push(url);
          that.setData({
            hasPicture: true,
            picUrls: pics
          })
        }
      },
      fail: function (e) {
        wx.showModal({
          title: '错误',
          content: '上传失败',
          showCancel: false
        })
      },
    })

    // uploadTask.onProgressUpdate((res) => {
    //   console.log('上传进度', res.progress)
    //   console.log('已经上传的数据长度', res.totalBytesSent)
    //   console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    // })

  },
  commitLeave() {
    if (this.data.chooseLeaveSubValue == null || this.data.chooseLeaveSubValue == '') {
      this.myshowtost("请选择请假子类型")
      return;
    }
    if (this.data.leaveReason == null || this.data.leaveReason == '') {
      this.myshowtost("请输入请假原因")
      return;
    }

    let req = {
      "leaveTypeId": this.data.chooseLeaveSubValue,
      // "workerNo":"s0000464",
      "leaveStartTime": this.data.leaveStartTime,
      "leaveEndTime": this.data.leaveEndTime,
      "leaveReason": this.data.leaveReason,
      "leaveImages": this.data.picUrls.join(',')
    }
    console.log(req);
    let that=this;
    util.request(mallapi.SubmitLeave,req,"POST").then(function (res) {
      if (res.errno === 0) { 
        that.myshowtost("提交成功");
        wx.navigateBack();
      }else{
        that.myshowtost(res.errmsg)
      }
    });
    
  },

 
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getLeaveTypeList();

    var start =util.formatDate(new Date())+" 00:00"; //'2022-08-27 00:00:00'
    var obj = dateTimePicker.dateTimePicker(2022, 2030, start);
    this.setData({
      dateTimeKS: obj.dateTime,
      dateTimeJS: obj.dateTime,
      dateTimeArray: obj.dateTimeArray
    });
    var leaveStartTime = dateTimePicker.formatPickerDateTime(this.data.dateTimeArray, this.data.dateTimeKS)
    this.setData({
      leaveStartTime: leaveStartTime,
      leaveEndTime: leaveStartTime,
    })

  },
  getLeaveTypeList() {
    let that = this;
    util.request(mallapi.GetLeaveAllType, {}, 'GET').then(function (res) {
      if (res.errno === 0) {
        let arrname = ['请选择'];
        res.data.forEach(c => {
          arrname.push(c.typeName);
        })
        that.setData({
          leaveTypeList: res.data,
          arrnameA: arrname
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

  },

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

  },

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

  },

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

  },

  myshowtost: function (v) {
    wx.showToast({
      title: v,
      icon: 'none',
      duration: 2000
    })
  },
})