import config from '../../../config'
import {
    readDeployNotes,
    findCommentByProcInsId
} from '../../../api/flowable'
import {
    findProSubDeptsInfoById,
    findProSubDeptsUserInfoById
} from '../../../api/project'
import {
	getToken
} from '../../../utils/auth'
const app = getApp()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        options: {},
        active: 100,
        rejectNode: false,
        stepList: [],
        activeName: "",
        flowRecordList: [],
        subDeptData: {
            subDeptInfos: {}
        },
        subDeptUserData: {
            user: {},
        },
        stopShow: false,
        deleteShow: false,
        revocationShow: false,
        fileNames: [],
        minImageList: [],
        imgTypes: ["png", "jpg", "jpeg"],
        stopBtnShow: false,
        comment: "",
        imgBaseUrl: config.baseImgUrl
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            options: options
        })
        this.findFlowNodes();
        this.findCommentByProcInsId();
        this.findApplyDataInfo();
    },

    //查询工作流节点
    findFlowNodes() {
        readDeployNotes(this.data.options.deployId).then(res => {
            let list = [{
                text: '开始'
            }];
            let index = this.data.active;
            res.data.forEach((item,idx) => {
                console.log("this.data.options.taskName",this.data.options.taskName)
                console.log("item.name",item.name)
                if(this.data.options.taskName==item.name){
                    index = idx+1;
                }
                list.push({
                    text: item.name.substr(0,5),
                    desc: ''
                });
            });
            list.push({
                text: '结束'
            });
            this.setData({
                active: index,
                stepList: list
            })
        });
    },

    //查询审批日志
    findCommentByProcInsId() {
        findCommentByProcInsId({
            procInsId: this.data.options.procInsId
        }).then(res => {
            this.setData({
                flowRecordList: res.data
            })
            let list = [];
            res.data.forEach((item, idx) => {
                if (idx == 1 && (item.commentType == "3" || item.commentType == "2")) {
                    that.setData({
                        rejectNode: true
                    })
                }
                if (item.deleteReason) {
                    item.deleteReason = this.getDeleteReason(item.deleteReason);
                }
                if (item.duration) {
                    item.duration = app.getDurationDate(item.duration);
                }
                list.push(item);
            })
            this.setData({
                flowRecordList: list
            })
        });
    },

    //查询审批表单参数
    findApplyDataInfo() {
        findProSubDeptsUserInfoById(this.data.options.businessKey).then(res => {
            if (res.data.eduFilePath) {
                let files = res.data.eduFilePath.split('/');
                res.data.eduFileName = files[files.length - 1];
            }
            if(res.data.userInfos){
                res.data.userInfos = JSON.parse(res.data.userInfos);
            }
            this.setData({
                subDeptUserData: res.data
            })
            //查询单位信息
            this.getSubDeptInfo(res.data.subDeptId);
        })
    },

    //查询审批表单参数
    getSubDeptInfo(subDeptId) {
        findProSubDeptsInfoById(subDeptId).then(res => {
            res.data.subDeptInfos = JSON.parse(res.data.subDeptInfos);
            this.setData({
                subDeptData: res.data
            })
        })
    },

    //流程退回
    onStop() {
        if (!this.data.stopBtnShow) {
            app.toast("请填写终止原因!")
            this.setData({
                stopBtnShow: true
            })
            return;
        } else {
            if (this.data.comment == "") {
                app.toast("请填写终止原因!")
                this.setData({
                    stopBtnShow: true
                })
                return;
            }
        }
        let that = this
        //弹出确认
        wx.showModal({
            title: '提示',
            content: '是否终止当前流程申请?',
            success: function (sm) {
                if (sm.confirm) {
                    that.submitStopProcess();
                }
            }
        })
    },

    /**
     * 确认撤回
     */
    submitStopProcess() {
        stopProcess({
            instanceId: this.data.options.procInsId,
            comment: this.data.comment
        }).then(res => {
            if (res.code == 200) {
                app.toast("终止流程申请成功!")
                setTimeout(() => {
                    wx.redirectTo({
                        url: '../../index/index',
                    })
                }, 500)
            }
        });
    },

    //流程删除
    onDelete() {
        let that = this
        //弹出确认
        wx.showModal({
            title: '提示',
            content: '是否确认删除流程申请?',
            success: function (sm) {
                if (sm.confirm) {
                    that.submitDeleteInstance();
                }
            }
        })
    },

    /**
     * 流程删除
     */
    submitDeleteInstance() {
        deleteInstance(this.data.options.procInsId).then(res => {
            if (res.code == 200) {
                app.toast("删除流程申请成功!")
                setTimeout(() => {
                    wx.redirectTo({
                        url: '../../index/index',
                    })
                }, 500)
            }
        });
    },

    //流程撤回
    onRevocation() {
        let that = this
        //弹出确认
        wx.showModal({
            title: '提示',
            content: '是否确认撤回当前任务流程?',
            success: function (sm) {
                if (sm.confirm) {
                    that.submitRevokeProcess();
                }
            }
        });
    },

    /**
     * 流程撤回
     */
    submitRevokeProcess() {
        revokeProcess({
            procInsId: this.data.options.procInsId,
            instanceId: this.data.options.procInsId,
            taskId: this.data.options.taskId
        }).then(res => {
            if (res.code == 200) {
                app.toast("撤回流程申请成功!")
                setTimeout(() => {
                    wx.redirectTo({
                        url: '../../index/index',
                    })
                }, 500)
            }
        });
    },

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

    /**
     * 获取驳回节点
     * @param {*} val 
     */
    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;
            }
        }
    },

    //终止原因
    commentblur: function (options) {
        this.data.comment = options.detail.value;
    },

    /**
     * 下载并打开文档
     * @param {*} e 
     */
    downFile: function (e) {
        let path = this.data.subDeptUserData.eduFilePath;
        wx.downloadFile({
            // 示例 url,并非真实存在
            url: config.baseUrl + '/file/download?fileName=' + path,
            header: {
                'Authorization': 'Bearer ' + getToken()
            },
            success: function (res) {
                const filePath = res.tempFilePath
                let fpt = path.split(".");
                wx.openDocument({
                    filePath: filePath,
                    fileType: fpt[fpt.length - 1],
                    success: function (res) {
                        console.log('打开文档成功')
                    },
                    fail: function (res) {
                        console.log(res)
                    }
                })
            }
        })
    },

    //选择退回节点
    onSelectTargetKey(e) {
        this.setData({
            targetKey: e.detail.id,
            backName: e.detail.name
        })
    },

    returnToPage: function () {
        /*关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面*/
        if (wx.getStorageSync('nav-types') == "depts") {
            wx.redirectTo({
                url: '../subDepts/index',
            })
        } else if (wx.getStorageSync('nav-types') == "users") {
            wx.redirectTo({
                url: '../subDeptsUsers/index',
            })
        }
    },

    //展示图片
    showImg:function(e){
        let paths = e.target.dataset.set;
        let path = [];
        paths.split(',').forEach(url => {
            path.push(config.baseImgUrl + url);
        });
        wx.previewImage({
            urls: path,
            current: path[0]
        })
    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})