import {
    complete,
    stopProcess,
    readDeployNotes,
    findCommentByProcInsId
} from '../../../api/flowable'
import {
    findMyDeptList,
    findAllByCategory,
    findProjectApplyData
} from '../../../api/publics'
import {
    updateProjectApply
} from '../../../api/projectApply'
import {
    syncFileUpload
} from '../../../utils/request'
import config from '../../../config'
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        maxDate: new Date(2088, 1, 1).getTime(),
        deptList: [],
        deployId: "",
        procInsId: "",
        procDefName: "",
        deptName: "",
        nickName: "",
        taskId: "",
        taskName: "",
        category: "",
        projectName: "",
        businessKey: "",
        businessDeptId: "",
        projectParName: "",
        infoData: {},
        active: 100,
        stepList: [],
        rejectNode: false,
        limit: 9,
        imgTypes: ["png", "jpg", "jpeg"],
        fileTypes: ["pdf", "doc", "docx", "xls", "xlsx"],
        fileNames: [],
        minImageList: [],
        detailDataList: [],
        dataList: [],
        stopShow: false,
        stopBtnShow: false,
        activeName: "",
        comment: "",
        useDeptIdIndex: 0,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let {
            deployId,
            procInsId,
            procDefName,
            deptName,
            nickName,
            taskId,
            taskName,
            category,
            businessKey,
            projectName,
            businessDeptId,
            projectParName,
            startUserId
        } = options
        this.setData({
            businessKey,
            projectName,
            procInsId,
            procDefName,
            deployId,
            deptName,
            nickName,
            taskId,
            taskName,
            category,
            businessDeptId,
            projectParName,
            initData: {
                id: businessKey,
                text: projectName
            },
            stopShow: startUserId == app.globalData.userData?.userId,
        })
        debugger
        this.initDeptList();
        this.findMyDeptAssetsList();
        this.findFlowNodes();
        this.findCommentByProcInsId();
    },

    //查询部门资产列表信息
    findMyDeptAssetsList() {
        findAllByCategory(this.data.category).then(res => {
            if (res.code == '200') {
                let list = [];
                res.data.forEach(item => {
                    let children = [];
                    item.childrenAssetsTypeList.forEach(child => {
                        children.push({
                            id: child.id,
                            text: child.name,
                            units: child.unit,
                            detailName: item.name + ' > ' + child.name
                        });
                    })
                    list.push({
                        id: item.id,
                        text: item.name,
                        children: children
                    });
                });
                this.findApplyDataInfo();
                this.setData({
                    dataList: list
                })
            }
        });
    },

    /**
     * 初始化部门列表
     */
    initDeptList() {
        findMyDeptList().then(res => {
            let list = [];
            res.data.forEach(item => {
                list.push({
                    "id": item.deptId,
                    "text": item.deptName
                });
            });
            this.setData({
                deptList: list
            })
        });
    },

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

    //查询审批日志
    findCommentByProcInsId() {
        findCommentByProcInsId({
            procInsId: this.data.procInsId
        }).then(res => {
            this.setData({
                flowRecordList: res.data
            })
            let list = [];
            res.data.forEach((item, idx) => {
                if (idx == 1 && (item.commentType == "3" || item.commentType == "2")) {
                    this.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() {
        findProjectApplyData(this.data.businessKey).then(res => {
            let imgList = [];
            let fileNames = [];
            if (res.data.applyFiles) {
                res.data.applyFiles.split(',').forEach(files => {
                    if(files){
                        let fileType = files.split(".")[files.split(".").length - 1].toLowerCase();
                        if (this.data.imgTypes.indexOf(fileType) == -1) {
                            let it = files.split('/');
                            fileNames.push({
                                name: it[it.length - 1],
                                path: files
                            });
                        } else {
                            imgList.push(config.baseUrl + files + '.min.jpg');
                        }
                    }
                });
            }
            if (res.data.proProjectApplyDetailList.length > 0) {
                let data = [];
                res.data.proProjectApplyDetailList.forEach(item => {
                    let activeId = [];
                    activeId.push(item.typeId);
                    let mainActiveIndex = 0;
                    let useUnitIndex = 0;
                    let assetsUnits = [];
                    this.data.dataList.forEach((_it, _itIndex) => {
                        if (_it.id == item.typeId) {
                            mainActiveIndex = _itIndex;
                            _it.children.forEach((_children, _childrenIndex) => {
                                if (_children.id == item.assetsId && _children.units) {
                                    let unitList = _children.units.split(',');
                                    if (unitList.length > 0) {
                                        unitList.forEach((unit, idx) => {
                                            if (unit == item.assetsUnit) {
                                                useUnitIndex = idx;
                                            }
                                            assetsUnits.push({
                                                id: idx,
                                                text: unit
                                            });
                                        });
                                    }
                                }
                            });
                        }
                    });
                    data.push({
                        detailId: item.assetsId,
                        detailName: item.assetsName,
                        showDetailsName: item.typeName + ' > ' + item.assetsName,
                        showDetailsPopup: false,
                        mainActiveIndex: mainActiveIndex,
                        activeId: activeId,
                        useUnit: item.assetsUnit,
                        assetsUnits: assetsUnits,
                        useUnitIndex: useUnitIndex,
                        applyNumber: item.number,
                        assetsVersion: item.assetsVersion,
                        useReason: item.useReason
                    })
                });
                this.setData({
                    detailDataList: data
                })
            }
            this.setData({
                infoData: res.data,
                fileNames: fileNames,
                minImageList: imgList,
            })
        })
    },

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

    //保存申请
    onSaveApply() {
        let {
            procInsId,
            initData,
            infoData,
            detailDataList,
            fileNames,
            minImageList
        } = this.data;
        //数据效验
        if (!procInsId || !initData.id) {
            app.toast("数据异常,请刷新页面重试!")
            return false;
        }
        if (!infoData.deptId) {
            app.toast("请选择使用单位!")
            return false;
        }
        if (!infoData.useTime) {
            app.toast("请选择使用时间!")
            return false;
        }
        if (!infoData.applyReason) {
            app.toast("请填写申请原因!")
            return false;
        }
        if (detailDataList.length > 0) {
            for (let i = 0; i < detailDataList.length; i++) {
                if (!detailDataList[i].detailId || !detailDataList[i].detailName || detailDataList[i].activeId.length == 0) {
                    app.toast("请选择申请明细!")
                    return false;
                }
                if (!detailDataList[i].applyNumber) {
                    app.toast("请填写申请数量!")
                    return false;
                }
                if (!detailDataList[i].useUnit) {
                    app.toast("请选择单位名称!")
                    return false;
                }
            }
        } else {
            app.toast("请添加申请明细!")
        }
        if (fileNames.length > 0) {
            for (let i = 0; i < fileNames.length; i++) {
                if(fileNames[0]){
                    let _fileType = fileNames[0].path.split('.');
                    _fileType = _fileType[_fileType.length - 1].toLowerCase();
                    if (this.data.fileTypes.indexOf(_fileType) == -1) {
                        app.toast("申请附件不支持 [ " + _fileType + " ] 格式!请检查第" + (i + 1) + "个附件")
                        return false;
                    }
                }
            }
        }
        let that = this;
        wx.showModal({
            title: '提示',
            content: '是否确定提交流程申请?',
            success: function (sm) {
                if (sm.confirm) {
                    that.submitBefore();
                } else if (sm.cancel) {
                    console.log('用户点击取消');
                }
            }
        })
    },

    /**
     * 提交前数据准备
     */
    submitBefore() {
        let {
            fileNames,
            minImageList
        } = this.data;
        if (fileNames.length > 0) {
            fileNames.forEach(item => {
                minImageList.push(item.path);
            });
        }
        let fileUrls = [];
        if (minImageList.length > 0) {
            minImageList.forEach(item => {
                //这里复杂的图片上传,改为同步上传,因为小程序只能上传一张图片
                if (item.indexOf("/profile/") > -1) {
                    fileUrls.push(item.replace(config.baseUrl, "").replace(".min.jpg", ""));
                    if (fileUrls.length == minImageList.length) {
                        //上传完毕
                        this.submitApply(fileUrls);
                    }
                } else {
                    syncFileUpload(item).then(res => {
                        fileUrls.push(res.fileName);
                        //验证图片上传完毕
                        if (fileUrls.length == minImageList.length) {
                            this.submitApply(fileUrls);
                        }
                    });
                }
            });
        } else {
            this.submitApply(fileUrls);
        }
    },

    /**
     * 提交表单
     */
    submitApply(fileData) {
        if (this.data.taskName == '提交申请') {
            let {
                taskId,
                procInsId,
                infoData,
                category,
                dataList,
                detailDataList
            } = this.data;
            let applyDetailList = [];
            detailDataList.forEach(detail => {
                applyDetailList.push({
                    superTypeKey: category,
                    typeId: dataList[detail.mainActiveIndex].id,
                    typeName: dataList[detail.mainActiveIndex].text,
                    assetsId: detail.detailId,
                    assetsName: detail.detailName,
                    number: detail.applyNumber,
                    assetsUnit: detail.useUnit,
                    assetsVersion: detail.assetsVersion,
                    useReason: detail.useReason
                });
            });
            let params = {
                taskId,
                instanceId: procInsId,
                comment:"修改并重新提交申请",
                variables: {},
                proProjectApply: {
                    id: infoData.id,
                    deptId: infoData.deptId,
                    projId: infoData.projId,
                    projName: infoData.projName,
                    applyType: infoData.applyType,
                    applyStatus: 1,
                    useTime: infoData.useTime,
                    applyReason: infoData.applyReason,
                    applyFiles: fileData.toString(),
                    proProjectApplyDetailList: applyDetailList
                }
            }
            complete(params).then(res => {
                if (res.code == 200) {
                    app.toast("修改申请信息成功!")
                    setTimeout(() => {
                        wx.redirectTo({
                            url: `../../index/index`,
                        })
                    }, 300)
                }
            });
        } else {
            this.submitData(fileData);
        }
    },

    /**
     * 提交表单
     */
    submitData(fileData) {
        let {
            infoData,
            category,
            dataList,
            detailDataList
        } = this.data;
        let applyDetailList = [];
        detailDataList.forEach(detail => {
            applyDetailList.push({
                superTypeKey: category,
                typeId: dataList[detail.mainActiveIndex].id,
                typeName: dataList[detail.mainActiveIndex].text,
                assetsId: detail.detailId,
                assetsName: detail.detailName,
                number: detail.applyNumber,
                assetsUnit: detail.useUnit,
                assetsVersion: detail.assetsVersion,
                useReason: detail.useReason
            });
        });
        let params = {
            id: infoData.id,
            deptId: infoData.deptId,
            projId: infoData.projId,
            projName: infoData.projName,
            applyType: infoData.applyType,
            applyStatus: 1,
            useTime: infoData.useTime,
            applyReason: infoData.applyReason,
            applyFiles: fileData.toString(),
            proProjectApplyDetailList: applyDetailList
        }
        updateProjectApply(params).then(res => {
            if (res.code == 200) {
                app.toast("修改申请信息成功!")
                setTimeout(() => {
                    wx.redirectTo({
                        url: `../approveTask/index?deployId=${this.data.deployId}&procInsId=${this.data.procInsId}&nickName=${this.data.nickName}&deptName=${this.data.deptName}&procDefName=${this.data.procDefName}&taskId=${this.data.taskId}&taskName=${this.data.taskName}&category=${this.data.category}&projectName=${this.data.projectName}&businessKey=${this.data.businessKey}&businessKeyParName=${this.data.businessKeyParName}&businessDeptId=${this.data.businessDeptId}&startUserId=${this.data.startUserId}`,
                    })
                }, 300)
            }
        });
    },

    //申请说明输入
    applyReasonblur: function (options) {
        this.data.infoData.applyReason = options.detail.value;
    },

    //使用单位 
    onSelectDept(e) {
        this.setData({
            "infoData.deptId": e.detail.id
        })
    },

    //使用时间
    onInputTime(e) {
        this.setData({
            "infoData.useTime": e.detail
        })
    },

    /**
     * 图片上传
     * @param {*} options 
     */
    imgUpload(options) {
        let imgs = options.detail;
        this.setData({
            minImageList: imgs
        });
    },

    /**
     * 文件上传
     * @param {*} options 
     */
    fileUpload(options) {
        let files = options.detail;
        this.setData({
            fileNames: files
        });
    },

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

    returnToPage: function () {
        /*关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面*/
        wx.redirectTo({
            url: '../await/index',
        })
    },

    /**
     * 栏目触发事件
     */
    onClickNav(e) {
        var index = e.currentTarget.dataset.index
        let list = this.data.detailDataList;
        list[index].activeId = null;
        list[index].mainActiveIndex = e.detail.index;
        this.setData({
            detailDataList: list
        })
        console.log(e.detail.index, this.data.dataList);
    },

    /**
     * 选项触发事件
     */
    onClickItem(e) {
        var index = e.currentTarget.dataset.index
        let list = this.data.detailDataList;
        list[index].detailId = e.detail.id;
        list[index].detailName = e.detail.text;
        list[index].showDetailsName = e.detail.detailName;
        if (e.detail.units) {
            let itemList = [];
            e.detail.units.split(',').forEach((item, idx) => {
                if (idx == 0) {
                    list[index].useUnitIndex = idx;
                    list[index].useUnit = item;
                }
                itemList.push({
                    id: idx,
                    text: item
                });
            });
            list[index].assetsUnits = itemList;
        }
        list[index].activeId = e.detail.id;
        list[index].showDetailsPopup = false;
        this.setData({
            detailDataList: list
        })
    },

    //新增问题
    newApplyDetail() {
        var data = this.data.detailDataList
        data.push({
            detailId: '',
            detailName: '',
            showDetailsName: '',
            showDetailsPopup: false,
            mainActiveIndex: 0,
            activeId: [],
            useUnit: "",
            useUnitIndex: "",
            assetsUnits: [],
            applyNumber: "",
            assetsVersion: "",
            useReason: ""
        })
        this.setData({
            detailDataList: data
        })
    },

    /**
     * 删除申请详情
     * @param {*} e 
     */
    delApplyDetail(e) {
        var index = e.currentTarget.dataset.index
        var data = this.data.detailDataList
        data.splice(index, 1);
        this.setData({
            detailDataList: data
        })
    },

    //输入申请数量
    onInputNumber(e) {
        var index = e.currentTarget.dataset.index
        let list = this.data.detailDataList;
        let value = e.detail.value;
        list[index].applyNumber = value;
        this.setData({
            detailDataList: list
        })
    },

    //选择资产单位
    onSelectUnit(e) {
        var index = e.currentTarget.dataset.index
        let list = this.data.detailDataList;
        list[index].useUnit = e.detail.text;
        list[index].useUnitIndex = e.detail.id;
        this.setData({
            detailDataList: list
        })
    },

    //输入规格型号
    onInputVersion(e) {
        var index = e.currentTarget.dataset.index
        let list = this.data.detailDataList;
        list[index].assetsVersion = e.detail.value;
        this.setData({
            detailDataList: list
        })
    },

    //输入使用说明
    onInputUseReason(e) {
        var index = e.currentTarget.dataset.index
        let list = this.data.detailDataList;
        list[index].useReason = e.detail.value;
        this.setData({
            detailDataList: list
        })
    },

    //关闭申请明细选择
    onShowPopup(e) {
        var index = e.currentTarget.dataset.index
        let list = this.data.detailDataList;
        list[index].showDetailsPopup = true;
        this.setData({
            detailDataList: list
        })
    },

    //关闭申请明细选择
    onClosePopup(e) {
        var index = e.currentTarget.dataset.index
        let list = this.data.detailDataList;
        list[index].showDetailsPopup = false;
        this.setData({
            detailDataList: list
        })
    },

    /**
     * 切换临建项目
     * @param {*} e 
     */
    onProjectSelect: function (e) {
        let projectId = e.detail.id;
        let projectName = e.detail.text;
        app.globalData.useProjectId = projectId;
        app.globalData.useProjectName = projectName;
        this.setData({
            initData: {
                id: app.globalData.useProjectId,
                text: app.globalData.useProjectName
            }
        })
    },

    //流程退回
    onStopApply() {
        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.procInsId,
            comment: this.data.comment
        }).then(res => {
            if (res.code == 200) {
                app.toast("终止流程申请成功!")
                setTimeout(() => {
                    wx.redirectTo({
                        url: '../../index/index',
                    })
                }, 500)
            }
        });
    },

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

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})