// pageage/safetyManagement/addSafetyInspect/index.js
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        maxDate:new Date(2088,1,1).getTime(),
        deptName:"",
        userId:"",
        nickName:"",
        loginName:"",
        projectId:"",
        projectName:"",
        procInsId:"",
        infoData:{},
        procDefName:"",
        deployId:"",
        activeName:"",
        flowNodeList:[],
        flowNodes:[],
        comment:"",
        taskId:"",
        procInsId:"",
        backShow:false,
        targetKey:"",
        targetKeyList:[],
        taskName:"",
        passState:true,
        backName:"",
        ret:"",
        remark:"",
        beginDate:"",
        endDate:"",
        day:0,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let {deployId,procInsId,procDefName,deptName,nickName,taskId,taskName,projectName,ret} = options
        //获取缓存数据
        wx.getStorage({
        key: 'userinfo',
        success:res=>{
            this.setData({
                projectId:app.globalData.projectId,
                projectName,
                procInsId,
                procDefName,
                deployId,
                deptName,
                nickName,
                taskId,
                taskName,
                ret,
                userId:res.data.userId,
                loginName:res.data.loginName,
            })
            this.initTargetKeyList();
            this.getFlowNodes();
            this.getFlowRecordList();
            this.getFormDatasList();
        }  
        }) 
    },

    getFlowNode(val){
        let flowNodeList = this.data.flowNodeList;
        for(let i=0;i<flowNodeList.length;i++){
            if(flowNodeList[i].id==val){
                let list = this.data.flowNodes;
                if(this.data.passState){
                    if(flowNodeList[i].name==this.data.taskName){
                        list.push({id:flowNodeList[i].id,name:flowNodeList[i].name,state:'transact'});
                        this.setData({
                            passState:false
                        })
                    }else{
                        list.push({id:flowNodeList[i].id,name:flowNodeList[i].name,state:'pass'});
                    }
                }else{
                    list.push({id:flowNodeList[i].id,name:flowNodeList[i].name,state:'none'});
                }
                this.setData({
                    flowNodes:list
                })
                if(flowNodeList[i].outgoingFlows && flowNodeList[i].outgoingFlows.length>0){
                    return this.getFlowNode(flowNodeList[i].outgoingFlows[0].targetRef);
                }
            }
        }
    },

    //查询工作流节点
    getFlowNodes(){
        let that = this;
        wx.request({
            url: app.globalData.reqUrl + '/wechat/flowTask/readNotes/'+that.data.deployId,
            method:"get",
            data:{},
            header: {
                "Content-Type": "application/json"
            },
            success(res){
                res = res.data
                if(res.code == 200){
                    that.setData({
                        flowNodeList:res.data
                    })
                    if(res.data.length>0){
                        let list = that.data.flowNodes;
                        list.push({id:res.data[0].id,name:res.data[0].name,state:'pass'});
                        that.setData({
                            flowNodes:list
                        })
                        return that.getFlowNode(res.data[0].outgoingFlows[0].targetRef);
                    }
                }else{
                    app.toast(res.msg);
                }
            }
        })
    },

    //查询审批日志
    getFlowRecordList(){
        let that = this;
        wx.request({
            url: app.globalData.reqUrl + '/wechat/flowTask/findCommentByProcInsId',
            method:"get",
            data:{
                procInsId:this.data.procInsId
            },
            header: {
                "Content-Type": "application/json"
            },
            success(res){
                res = res.data
                if(res.code == 200){
                    that.setData({
                        flowRecordList:res.data
                    })
                    let list=[];
                    res.data.forEach(item=>{
                        if(item.deleteReason){
                            item.deleteReason=that.getDeleteReason(item.deleteReason);
                        }
                        if(item.duration){
                            item.duration=that.getDurationDate(item.duration);
                        }
                        list.push(item);
                    })
                    that.setData({
                        flowRecordList:list
                    })
                }else{
                    app.toast(res.msg);
                }
            }
        })
    },

    //查询审批表单参数
    getFormDatasList(){
        let that = this;
        wx.request({
            url: app.globalData.reqUrl + '/wechat/flowTask/findFormDatasByProcInsId',
            method:"get",
            data:{
                procInsId:this.data.procInsId
            },
            header: {
                "Content-Type": "application/json"
            },
            success(res){
                res = res.data
                if(res.code == 200){
                    that.setData({
                        infoData:res.data,
                        beginDate:res.data.beginDate,
                        endDate:res.data.endDate,
                        day:res.data.day
                    })
                }else{
                    app.toast(res.msg);
                }
            }
        })
    },

    //初始化退回节点
    initTargetKeyList(){
        let that = this;
        wx.request({
            url: app.globalData.reqUrl + '/wechat/flowTask/returnList',
            method:"post",
            data:{
                taskId:that.data.taskId
            },
            header: {
                "Content-Type": "application/json"
            },
            success(res){
                res = res.data
                if(res.code == 200){
                    let list = [{id:'',text:''}];
                    res.data.forEach(item=>{
                        list.push({id:item.id,text:item.name})
                    })
                    that.setData({
                        targetKeyList:list
                    })
                }else{
                    app.toast(res.msg);
                }
            }
        })
    },

    //保存
    onSave(){
        this.setData({
            loadShow:true
        })
        let {procDefId,projectId,userId,loginName,remark,beginDate,endDate} =  this.data;
        //数据效验
        if(projectId==""||loginName==""||userId==""||procDefId==""){
            app.toast("数据异常，请刷新页面重试!")
            this.setData({
                loadShow:false
            })
            return;
        }
        if(beginDate==""){
            app.toast("请选择请假开始时间!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(endDate==""){
            app.toast("请选择请假结束时间!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(remark==""){
            app.toast("请填写请假事由!")
            that.setData({
                loadShow:false
            })
            return;
        }
        let that = this;
        wx.showModal({
            title: '提示',
            content: '是否确定提交'+this.data.procDefName+'？',
            success: function (sm) {
              if (sm.confirm) {
                  // 用户点击了确定 可以调用了
                  that.submit()
                } else if (sm.cancel) {
                    that.setData({
                        loadShow:false
                    });
                  console.log('用户点击取消');
                }
            }
        }) 
    },

    submit(){
        let that = this
        let {taskId,procInsId,projectId,projectName,userId,loginName,nickName,remark,beginDate,endDate,day} =  that.data;
        let date = new Date();
        let params = {
            taskId,
            instanceId:procInsId,
            userId,
            assignee:nickName,
            variables:{
                businessKey:projectId,
                projectName,
                date:that.dateFormat("yyyy-MM-dd HH:ss",date),
                beginDate,
                endDate,
                day,
                remark,
                INITIATOR:that.data.infoData.INITIATOR
            }
        }
        wx.request({
            url: app.globalData.reqUrl + '/wechat/flowTask/complete',
            method:"POST",
            data:params,
            header: {
                "Username": loginName,
                "Content-Type": "application/json"
            },
            success(res){
                that.setData({
                    loadShow:false
                })
                res = res.data
                if(res.code == 200){
                    app.toast("提交申请成功!")
                    if(that.data.ret=="await"){
                        setTimeout(()=>{
                            wx.redirectTo({
                                url: '../await/index',
                            })
                        },200)
                    }else{
                        setTimeout(()=>{
                            wx.redirectTo({
                                url: '../myFlowDefinition/index',
                            })
                        },200)
                    }
                }else{
                    app.toast(res.msg);
                }
            }
        })
    },

    //申请说明
    remarkblur: function (options) {
        this.data.remark = options.detail.value;
    },

   //开始时间
   onbeginDate(e){
    this.setData({
        beginDate:e.detail
    })
    if(this.data.endDate==""){
        this.setData({
            endDate:e.detail
        })
    }
    this.setDay();
  },
  //结束时间
  onendDate(e){
    this.setData({
      endDate:e.detail
    })
    this.setDay();
  },

  setDay(){
    if(this.data.beginDate && this.data.endDate){
        let time = (new Date(this.data.endDate).getTime())-(new Date(this.data.beginDate).getTime());
        if(time<0){
            this.setData({
                day:0
            })
        }else{
            let hours = time/(3600000);
            let day = (hours/24)+1;//这里默认加1天，PS:2023-09-10 2023-09-11实际请假应该为2天，而不是一天
            if(hours%24>0) day++;
            this.setData({
                day
            })
        }
    }
  },

  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;
  },

  // 手风琴
  onChange(event) {
    this.setData({
      activeName: event.detail,
    });
  },

  getDeleteReason(val){
    val = val.replace("Change activity to ","");
    let flowRecordList = this.data.flowRecordList;
    for(let i=0;i<flowRecordList.length;i++){
      if(flowRecordList[i].taskDefKey==val){
        return "驳回至"+flowRecordList[i].taskName;
      }
    }
  },

  getDurationDate(val){
    // 计算出相差天数
    let days = Math.floor(val / (24 * 3600 * 1000))
    // 计算出小时数
    let leave1 = val % (24 * 3600 * 1000) // 计算天数后剩余的毫秒数
    let hours = Math.floor(leave1 / (3600 * 1000))
    // 计算相差分钟数
    let leave2 = leave1 % (3600 * 1000) // 计算小时数后剩余的毫秒数
    let minutes = Math.floor(leave2 / (60 * 1000))
    // 计算相差秒数
    let leave3 = leave2 % (60 * 1000) // 计算分钟数后剩余的毫秒数
    let seconds = Math.round(leave3 / 1000)
    if(days>0){
      if(days<10) days = "0"+days;
      if(hours<10) hours = "0"+hours;
      if(minutes<10) minutes = "0"+minutes;
      if(seconds<10) seconds = "0"+seconds;
      return days + '天' + hours + '小时' + minutes + '分钟' + seconds + '秒';
    }
    if(hours>0){
      if(hours<10) hours = "0"+hours;
      if(minutes<10) minutes = "0"+minutes;
      if(seconds<10) seconds = "0"+seconds;
      return hours + '小时' + minutes + '分钟' + seconds + '秒';
    }
    if(minutes>0){
      if(minutes<10) minutes = "0"+minutes;
      if(seconds<10) seconds = "0"+seconds;
      return minutes + '分钟' + seconds + '秒';
    }
    if(seconds>0){
      if(seconds<10) seconds = "0"+seconds;
      return seconds + '秒';
    }
  },

    //选择退回节点
    onSelectTargetKey(e){
        this.setData({
            targetKey:e.detail.id,
            backName:e.detail.name
        })
    },
          
    returnToPage: function () {
        /*关闭当前页面，跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面*/
        if(this.data.ret=="await"){
            wx.redirectTo({
                url: '../await/index',
            })
        }else{
            wx.redirectTo({
                url: '../myFlowDefinition/index'
            })
        }
    },

    //取消页面
    cancelSaveView(){
        /*关闭当前页面，跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面*/
        if(this.data.ret=="await"){
            wx.redirectTo({
                url: '../await/index',
            })
        }else{
            wx.redirectTo({
                url: '../myFlowDefinition/index'
            })
        }
    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})