// pages/educations-add/index.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loadShow:false,
    loginName:'',
    userName:'',
    deptId:'',
    projectName:'',
    projectId:'',
    //参数
    fileDataList:[],
    educationTypeList:[],
    cooperationTeamList:[],
    trainingType:'',
    trainingStartTime:'',
    trainingEndTime:'',

    trainingStartTime2:'',
    trainingEndTime2:'',

    trainingContent:'',
    collaborateRanksId:'',
    collaborateRanksName:'',
    attendNumber:'',
    activeName:'',
    activeIndex:'',
    // defaultStartTime:"",
    // defaultEndTime:"",
    maxDate:new Date(2100,1,1).getTime(),

  },

  //选择培训类型
  onSelectEducationType(e){
    this.setData({
      trainingType:e.detail.id
    })
    if(e.detail.id == 4) {
      this.setData({
        trainingStartTime:this.dateFormat("yyyy-MM-dd",new Date()),
        trainingStartTime2:new Date().getTime(),
        trainingEndTime:this.addDay(this.dateFormat("yyyy-MM-dd",new Date()),8),
        trainingEndTime2:new Date(this.addDay(this.dateFormat("yyyy-MM-dd",new Date()),8)).getTime()
      })
    } else {
      this.setData({
        trainingStartTime:this.dateFormat("yyyy-MM-dd",new Date()),
        trainingStartTime2:new Date().getTime(),
        trainingEndTime:this.dateFormat("yyyy-MM-dd",new Date()),
        trainingEndTime2:new Date().getTime()
      })
    }
  },
  //培训开始时间
  onStartTime(e){
    var that = this
    that.setData({
      trainingStartTime:e.detail,
      trainingStartTime2:new Date(e.detail).getTime()
    })
    let trainingEndTime = e.detail 
    let trainingEndTime2 = new Date(e.detail).getTime()
    if(that.data.trainingType == 4) {
      trainingEndTime = that.addDay(e.detail,8) 
      trainingEndTime2 = new Date(that.addDay(e.detail,8)).getTime()
    } 
    that.setData({
      trainingEndTime:trainingEndTime,
      trainingEndTime2 :trainingEndTime2
    })
    
  },
  //培训结束时间
  onEndTime(e){
    this.setData({
      trainingEndTime:e.detail
    })
  },
  //培训内容
  onInputContent(e){
    this.setData({
      trainingContent:e.detail.value
    })
  },
  //协作队伍
  onCooperationTeam(e){
    let collaborateRanksId = '';
    let collaborateRanksName = '';
    for(let i = 0;i<e.detail.length;i++){
      collaborateRanksId += e.detail[i].id+ ","
      collaborateRanksName += e.detail[i].text+ ","
    }
    if (collaborateRanksId.length > 0) {
      collaborateRanksId = collaborateRanksId.substr(0, collaborateRanksId.length - 1);
    }if (collaborateRanksName.length > 0) {
      collaborateRanksName = collaborateRanksName.substr(0, collaborateRanksName.length - 1);
    }

    this.setData({
      collaborateRanksId:collaborateRanksId,
      collaborateRanksName:collaborateRanksName,
    })
  },
  //参与人数
  onInputNumber(e){
    this.setData({
      attendNumber:e.detail.value
    })
  },

  onClickShow() {
    this.setData({ loadShow: true });
  },

  onClickHide() {
    this.setData({ loadShow: false });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    //获取缓存数据
    wx.getStorage({
      key: 'userinfo',
      success:function(res){
        let educationTypeList = [{text:'三级安全教育',id:4},{text:'班前讲话',id:5},{text:'专项培训',id:3},{text:'应急演练',id:6}];
        let activeName;
        let activeIndex;
        let trainingType;
        let trainingStartTime = that.getNowDate()
        let trainingEndTime;
        for(let i = 0;i<educationTypeList.length;i++){
          if(options.activeState == educationTypeList[i].id){
            activeName = educationTypeList[i].text;
            activeIndex = i;
            trainingType = educationTypeList[i].id;
            break;
          }
        }
        if(trainingType == 4) {
          trainingEndTime = that.addDay(that.dateFormat("yyyy-MM-dd",new Date()),8)
          
        } else {
          trainingEndTime = that.getNowDate()
        }
        that.setData({
          loginName:res.data.loginName,
          userName:res.data.userName,
          deptId:res.data.deptId,
          projectId:options.projectId,
          projectName:options.projectName,
          activeName:activeName,
          activeIndex:activeIndex,
          educationTypeList:educationTypeList,
          trainingType:trainingType,
          trainingStartTime:trainingStartTime,
          trainingStartTime2:new Date(trainingStartTime).getTime(),
          trainingEndTime:trainingEndTime,
          trainingEndTime2:new Date(trainingEndTime).getTime()
        })  

        that.getCollaborativeTeam();
      }
    }) 
  },

  /**
   * 获取当前年月日
   */
  getNowDate(){
    var date = new Date(); 
    var year = date.getFullYear(); 
    var month = date.getMonth() + 1;
    var day = date.getDate();
    month = (month > 9) ? month : ("0" + month);
    day = (day < 10) ? ("0" + day) : day;
    var today = year + "-" + month + "-" + day;
    console.log(today);
    return today;
  },

   addDay(datetime, days) {
             var old_time = new Date(datetime.replace(/-/g, "/")); //替换字符，js不认2013-01-31,只认2013/01/31
             var fd = new Date(old_time.valueOf() + days * 24 * 60 * 60 * 1000); //日期加上指定的天数
             var new_time = fd.getFullYear() + "-";
             var month = fd.getMonth() + 1;
             if (month >= 10) {
                 new_time += month + "-";
             } else {
                //在小于10的月份上补0
                new_time += "0" + month + "-";
            }
            if (fd.getDate() >= 10) {
                new_time += fd.getDate();
            } else {
                //在小于10的日期上补0
                new_time += "0" + fd.getDate();
           }
            return new_time; //输出格式：2013-01-02
    },

  dateFormat(fmt, date) {
    let ret;
    const opt = {
        'y+': date.getFullYear().toString(), // 年
        'M+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'm+': date.getMinutes().toString(), // 分
        's+': date.getSeconds().toString(), // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0'));
        }
    }
    return fmt;
  },


  /**
   * 协助队伍
   */
  getCollaborativeTeam(){
    var that = this;
    wx.request({
      url: app.globalData.reqUrl+'/weixin/training/getCollaborativeTeam',
      data:{
        "projectId":this.data.projectId,
      },
      method:"get",
      success:function(res){
        let array = [];
        for(let i =0;i<res.data.length;i++){
          if(array.length <= 0){
            array.push({
              "id":res.data[i].unitId,
              "text":res.data[i].uninName,
              "type":false
            })
          }else{
            if(!array.some(item1=>item1.id == res.data[i].unitId)){
              array.push({
                "id":res.data[i].unitId,
                "text":res.data[i].uninName,
                "type":false
              })
            }
          }

        }
     
        that.setData({
          cooperationTeamList:array
        })
      }
    })
  },

  onImagesArr(e){
    this.setData({fileDataList:[]});
    let fileDataList = [];
    for(let i = 0;i<e.detail.length;i++){
      wx.uploadFile({
        //图片上传地址
        url: app.globalData.reqUrl+'/weixin/security/fileUpload',
        filePath: e.detail[i],
        name: 'file',
        header: {
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
        },
        formData: { user: 'test' },
        success:res => {
          let data = JSON.parse(res.data);
          fileDataList.push(data.url);
        },
      });
    }
    this.setData({ fileDataList:fileDataList});
  },
  
  add:function(){
    //判断值是否为空
    if(this.data.trainingType == '' || this.data.trainingType == undefined){
      app.toast("请选择培训类型");
      return;
    }else if(this.data.trainingStartTime == '' || this.data.trainingStartTime == undefined){
      app.toast("请选择培训开始时间");
      return;
    }else if(this.data.trainingEndTime == '' || this.data.trainingEndTime == undefined){
      app.toast("请选择培训结束时间");
      return;
    }else if(this.data.trainingContent == '' || this.data.trainingContent == undefined){
      app.toast("请填写培训内容");
      return;
    }else if(this.data.collaborateRanksId == '' || this.data.collaborateRanksId == undefined){
      app.toast("请选择协作队伍");
      return;
    }else if(this.data.attendNumber == '' || this.data.attendNumber == undefined){
      app.toast("请选择参加人数");
      return;
    }
   
    wx.request({
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      url:app.globalData.reqUrl+'/weixin/training/addTrainingData',
      data:{
        projectId:this.data.projectId,
        projectName:this.data.projectName,
        trainingType:this.data.trainingType,
        trainingStartTime:this.data.trainingStartTime,
        trainingEndTime:this.data.trainingEndTime,
        trainingContent:this.data.trainingContent,
        collaborateRanksId:this.data.collaborateRanksId,
        collaborateRanksName:this.data.collaborateRanksName,
        attendNumber:this.data.attendNumber,
        createUser:this.data.loginName,
        fileDataList:JSON.stringify(this.data.fileDataList)
      },
      method:"POST",
     success:function(res){
       if(res.data.code == 0){
        wx.redirectTo({
          url: '../educations-list/index',
        })
       }else{
         app.toast("添加失败");
         return;
       }
     }
    })
  },

  /**
   * 返回教育培训列表
   */
  goGCLB:function(){
    wx.redirectTo({
      url: '../educations-list/index'
    })
  },
})