import {
    getDictCache
} from '../../../api/publics'
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        maxDate: new Date(2088, 1, 1).getTime(),
        minDate: new Date(2001, 1, 1).getTime(),
        deptId: "",
        deptName: "",
        userId: "",
        nickName: "",
        loginName: "",
        projectId: "",
        projectName: "",
        remark: "",
        filesData: [],
        limit: 30,
        fileType: ["pdf", "png", "jpg", "jpeg"],
        procDefId: "",
        approveTitle: "",
        deploymentId: "",
        activeName: "",
        flowNodeList: [],
        flowNodes: [],
        isFiles: false,
        imageInfoData: [],
        active: 0,
        fbAptitude: false,
        subDeptType: "",
        subDeptTypes: [],
        subDeptScope: "",
        subDeptScopes: [],
        subDeptName: "",
        subDeptAptitude: "",
        subDeptChairman: "",
        subDeptSafetyCertificate: "",
        subDeptCustodian: "",
        subDeptCustodianCardId: "",
        subDeptApproachDate: "",
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let {
            procDefId,
            approveTitle,
            deploymentId,
            procDefKey
        } = options
        if (procDefKey == "flow_fbzzsp_fbszzsp") {
            this.getDicts();
            this.setData({
                fbAptitude: true
            })
        }
        //获取缓存数据
        wx.getStorage({
            key: 'userinfo',
            success: res => {
                this.setData({
                    projectId: app.globalData.projectId,
                    projectName: app.globalData.projectName,
                    procDefId,
                    approveTitle,
                    deploymentId,
                    deptId: res.data.deptId,
                    deptName: res.data.deptName,
                    userId: res.data.userId,
                    nickName: res.data.nickName,
                    loginName: res.data.loginName
                })
                this.getFlowNodes();
            }
        })
    },

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

    //获取字典信息
    getDicts() {
        let that = this;
        /*关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面*/
        getDictCache('flow_sub_dept_type').then(res => {
            if (res.code == 200) {
                let typeList = [];
                res.data.forEach(item => {
                    typeList.push({
                        "id": item.dictValue,
                        "text": item.dictLabel
                    });
                })
                that.setData({
                    subDeptTypes: typeList,
                    subDeptType: typeList[0].id,
                })
            }
        });
        getDictCache('flow_sub_dept_scope').then(res => {
            if (res.code == 200) {
                let scopeList = [];
                res.data.forEach(item => {
                    scopeList.push({
                        "id": item.dictValue,
                        "text": item.dictLabel
                    });
                })
                that.setData({
                    subDeptScopes: scopeList,
                    subDeptScope: scopeList[0].id,
                })
            }
        });
    },

    //选择分包类型
    onSelectSubDeptTypes(e) {
        this.setData({
            subDeptType: e.detail.id
        })
    },

    //选择分包范围
    onSelectSubDeptScopes(e) {
        let list = [];
        e.detail.forEach(it =>{
           if(it.id){
            list.push(it.id)
           }
        })
        this.setData({
            subDeptScope: list.toString()
        })
    },

    //输入分包单位名称
    inputSubDeptName(e) {
        this.setData({
            subDeptName: e.detail.value
        })
    },

    //输入分包单位资质
    inputSubDeptAptitude(e) {
        this.setData({
            subDeptAptitude: e.detail.value
        })
    },

    //输入分包单位法人代表
    inputSubDeptChairman(e) {
        this.setData({
            subDeptChairman: e.detail.value
        })
    },

    //输入分包单位安全证书
    inputSubDeptSafetyCertificate(e) {
        this.setData({
            subDeptSafetyCertificate: e.detail.value
        })
    },

    //输入分包单位项目经理
    inputSubDeptCustodian(e) {
        this.setData({
            subDeptCustodian: e.detail.value
        })
    },

    //输入分包单位名称
    inputSubDeptCustodianCardId(e) {
        this.setData({
            subDeptCustodianCardId: e.detail.value
        })
    },

    //选择分包进场时间
    inputSubDeptApproachDate(e) {
        this.setData({
            subDeptApproachDate: e.detail
        })
    },

    /**
     * 获取流程节点
     * @param {*} val 
     */
    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;
                list.push({
                    id: flowNodeList[i].id,
                    name: flowNodeList[i].name,
                    text: flowNodeList[i].name.length > 4 ? flowNodeList[i].name.substring(0, 4) : flowNodeList[i].name
                });
                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/' + this.data.deploymentId,
            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,
                            text: res.data[0].name
                        });
                        that.setData({
                            flowNodes: list
                        })
                        return that.getFlowNode(res.data[0].outgoingFlows[0].targetRef);
                    }
                } else {
                    app.toast(res.msg);
                }
            }
        })
    },

    //保存
    onSave() {
        this.setData({
            loadShow: true
        })
        let {
            procDefId,
            projectId,
            userId,
            loginName,
            remark,
            filesData,
            fbAptitude,
            subDeptType,
            subDeptScope,
            subDeptName,
            subDeptAptitude,
            subDeptChairman,
            subDeptSafetyCertificate,
            subDeptCustodian,
            subDeptCustodianCardId,
            subDeptApproachDate
        } = this.data;
        //数据效验
        if (projectId == "" || loginName == "" || userId == "" || procDefId == "") {
            app.toast("数据异常,请刷新页面重试!")
            this.setData({
                loadShow: false
            })
            return;
        }
        //分包资质审批数据效验
        if (fbAptitude) {
            if (subDeptType == "") {
                app.toast("请选择分包类型!")
                this.setData({
                    loadShow: false
                })
                return;
            }
            if (subDeptScope == "") {
                app.toast("请选择分包范围!")
                this.setData({
                    loadShow: false
                })
                return;
            }
            if (subDeptName == "") {
                app.toast("请填写分包单位名称!")
                this.setData({
                    loadShow: false
                })
                return;
            }
            if (subDeptAptitude == "") {
                app.toast("请填写分包单位资质!")
                this.setData({
                    loadShow: false
                })
                return;
            }
            if (subDeptChairman == "") {
                app.toast("请填写分包单位法人代表!")
                this.setData({
                    loadShow: false
                })
                return;
            }
            if (subDeptSafetyCertificate == "") {
                app.toast("请填写分包单位安全生产许可证!")
                this.setData({
                    loadShow: false
                })
                return;
            }
            if (subDeptCustodian == "") {
                app.toast("请填写分包单位项目经理!")
                this.setData({
                    loadShow: false
                })
                return;
            }
            if (subDeptCustodianCardId == "") {
                app.toast("请填写分包单位项目经理身份证号!")
                this.setData({
                    loadShow: false
                })
                return;
            }
            if (subDeptApproachDate == "") {
                app.toast("请选择分包单位进场时间!")
                this.setData({
                    loadShow: false
                })
                return;
            }
        }
        if (filesData.length == 0 && this.data.imageInfoData.length == 0) {
            app.toast("请上传审批内容!")
            this.setData({
                loadShow: false
            });
            return;
        }
        if (remark == "") {
            app.toast("请填写申请说明!")
            this.setData({
                loadShow: false
            })
            return;
        }
        for (let i = 0; i < filesData.length; i++) {
            let _fileType = filesData[0].path.split('.');
            _fileType = _fileType[_fileType.length - 1].toLowerCase();
            //判断附件类型,如果是图片直接展示,非图片则显示附件
            if (this.data.fileType.indexOf(_fileType) == -1) {
                app.toast("申批内容不支持 [ " + _fileType + " ] 格式!请上传PDF文件。")
                this.setData({
                    loadShow: false
                });
                return;
            }
        }
        let that = this;
        wx.showModal({
            title: '提示',
            content: '是否确定提交' + this.data.approveTitle + '?',
            success: function (sm) {
                if (sm.confirm) {
                    // 用户点击了确定 可以调用了
                    that.submit()
                } else if (sm.cancel) {
                    that.setData({
                        loadShow: false
                    });
                    console.log('用户点击取消');
                }
            }
        })

    },

    submit() {
        let that = this
        let {
            procDefId,
            projectId,
            projectName,
            userId,
            loginName,
            nickName,
            remark,
            filesData,
            imageInfoData,
            fbAptitude,
            subDeptType,
            subDeptScope,
            subDeptName,
            subDeptAptitude,
            subDeptChairman,
            subDeptSafetyCertificate,
            subDeptCustodian,
            subDeptCustodianCardId,
            subDeptApproachDate
        } = that.data;
        let fileUrls = [];
        filesData.forEach(f => {
            imageInfoData.push(f.path);
        });
        imageInfoData.forEach(async (item) => {
            let uploadUrl = app.globalData.uploadUrl + '/common/upload'
            let name = "file"
            //这里复杂的图片上传,改为同步上传,因为小程序只能上传一张图片
            let obj = await that.syncUploadImage(uploadUrl, item, name);
            fileUrls.push(obj.data.fileName);
            //验证图片上传完毕
            if (fileUrls.length == imageInfoData.length) {
                //分包单位资质审批参数
                let fbAptitudeParams = {};
                if(fbAptitude){
                    fbAptitudeParams = {
                        subDeptType,
                        subDeptScope,
                        subDeptName,
                        subDeptAptitude,
                        subDeptChairman,
                        subDeptSafetyCertificate,
                        subDeptCustodian,
                        subDeptCustodianCardId,
                        subDeptApproachDate
                    }
                }
                let params = {
                    procDefId,
                    userId,
                    userName: loginName,
                    nickName,
                    variables: {
                        businessKey: projectId,
                        projectName,
                        files: fileUrls.toString(),
                        remark,
                        ...fbAptitudeParams
                    }
                }
                wx.request({
                    url: app.globalData.reqUrl + '/wechat/flowTask/startProcessInstance',
                    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("提交申请成功!")
                            setTimeout(() => {
                                wx.redirectTo({
                                    url: '../myProcessIns/index',
                                })
                            }, 200)
                        } else {
                            app.toast(res.msg);
                        }
                    }
                })
            }
        })
    },

    /**
     * 这里考虑上传图片异步问题,封装为同步
     */
    syncUploadImage(url, uploadFile, name) {
        return new Promise((resolve, reject) => {
            wx.uploadFile({
                url, // 上传的服务器接口地址
                filePath: uploadFile,
                header: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
                },
                name, //上传的所需字段,后端提供
                formData: {
                    user: 'test'
                },
                success: (res) => {
                    // 上传完成操作
                    const data = JSON.parse(res.data)
                    resolve({
                        data: data
                    })
                },
                fail: (err) => {
                    //上传失败:修改pedding为reject
                    console.log("访问接口失败", err);
                    wx.showToast({
                        title: "网络出错,上传失败",
                        icon: 'none',
                        duration: 1000
                    });
                    reject(err)
                }
            });
        })
    },

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

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

    // list  上传图片
    onImagesArr(e) {
        var data = this.data.imageInfoData
        data = e.detail
        this.setData({
            imageInfoData: data
        })
    },

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

    /**
     * 切换上传文件类型
     * @param {*} e 
     */
    switchFiles(e) {
        this.setData({
            isFiles: !this.data.isFiles,
        });
        if (this.data.isFiles) {
            if (this.data.filesData.length == 0) {
                let myImages = this.selectComponent("#myImage");
                myImages.upload();
            }
        } else {
            if (this.data.imageInfoData.length == 0) {
                let myFiles = this.selectComponent("#myFiles");
                myFiles.upload();
            }
        }
    },

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

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})