const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        maxDate: new Date(2088, 1, 1).getTime(),
        minDate: new Date().getTime() + (3600 * 48 * 1000),
        projectId: "",
        projectName: "",
        loginName: "",
        userName: "",
        rectifierData: [],
        rectifierData2: [],
        rectifierData3: [],
        imageInfoData: [],
        //验收时间
        nickedTime: '',
        loadShow: false,
        lordSent: "",
        lordSentUser: "",
        copySend: "",
        copySendUser: "",
        recheckSend: "",
        recheckSendUser: "",
        workParts: "",
        changeInfo: "",
        dangerType: "1",
        dangerTypeList: [],
        selectValue: "",
        selectIndex: "",
        problemType: "1",
        showHis: false,
        problemTypeList: [{
            id: "1",
            text: "常规检查"
        }, {
            id: "2",
            text: "专项检查"
        }],
        flowNodes:[{text:'开始'},{text:'提交隐患'},{text:'隐患整改'},{text:'隐患复检'},{text:'结束'}],
        active: 0 
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let {
            ts
        } = options
        this.setData({
            projectId: app.globalData.projectId,
            projectName: app.globalData.projectName,
            loginName: res.data.loginName,
            userName: res.data.nickName,
            recheckSend: res.data.nickName,
            recheckSendUser: res.data.loginName
        });
        //获取缓存数据
        wx.getStorage({
            key: 'YanZhu-XD-App-UserInfoKey',
            success: res => {
                this.setData({
                    projectId: app.globalData.projectId,
                    projectName: app.globalData.projectName,
                    loginName: res.data.loginName,
                    userName: res.data.nickName,
                    recheckSend: res.data.nickName,
                    recheckSendUser: res.data.loginName
                });
                this.getAllProjectUserData();
                this.getDangerTypeList();
                this.getHisInfo();
            }
        })
    },

    //查询项目人员数据
    getAllProjectUserData() {
        let that = this
        wx.request({
            url: app.globalData.reqUrl + '/wechat/projectuserinfo/queryAllProjectUserByParams',
            method: "get",
            data: {
                projectId: that.data.projectId,
                loginName: that.data.loginName
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success(res) {
                res = res.data
                if (res.code == 200) {
                    that.setData({
                        rectifierData: res.data,
                        rectifierData3: res.data,
                    })
                }
            }
        })

        wx.request({
            url: app.globalData.reqUrl + '/wechat/projectuserinfo/queryAllProjectUserByParams',
            method: "get",
            data: {
                projectId: that.data.projectId,
                loginName: that.data.loginName,
                selectMy: 'Y'
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success(res) {
                res = res.data;
                if (res.code == 200) {
                    let findMy = false;
                    res.data.forEach(it => {
                        if (it.userinfoList.length > 0) {
                            it.userinfoList.forEach(u => {
                                if (that.data.loginName == u.phonenumber) {
                                    findMy = true;
                                }
                            });
                        }
                    });
                    if(!findMy){
                        res.data[0].userinfoList.push({state:false,nickName:that.data.userName,jobTypeName:'集团公司',phonenumber:that.data.loginName});
                    }
                    that.setData({
                        rectifierData2: res.data,
                    })
                }
            }
        })
    },

    getHisInfo() {
        //这里查询当前登录人上次提交隐患,自动填充整改人,复检人,抄送人
        let that = this
        wx.request({
            url: app.globalData.reqUrl + '/wechat/projectProblemmodify/findLastDataByParams',
            method: "get",
            data: {
                projectId: that.data.projectId,
                createUser: that.data.loginName,
                infoType: 1
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success(res) {
                res = res.data
                if (res.code == 200 && res.data) {
                    that.setData({
                        showHis: true,
                        lordSent: res.data.lordSent,
                        lordSentUser: res.data.lordSentUser,
                        recheckSend: res.data.recheckSend,
                        recheckSendUser: res.data.recheckSendUser,
                        copySend: res.data.copySend,
                        copySendUser: res.data.copySendUser
                    })
                }
            }
        })
    },

    getDangerTypeList() {
        let that = this
        wx.request({
            url: app.globalData.reqUrl + '/wechat/projectProblemmodify/queryDangerType',
            method: "get",
            data: {
                type: 'ssp_zlyhlx'
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success(res) {
                res = res.data
                if (res.code == 200) {
                    let list = [];
                    res.data.forEach(it => {
                        list.push({
                            "id": it.dictValue,
                            "text": it.dictLabel
                        });
                    })
                    that.setData({
                        dangerTypeList: list
                    })
                }
            }
        })
    },

    //隐患描述
    onInputWorkParts(e) {
        let workParts = e.detail.value
        this.setData({
            workParts
        })
    },

    //整改要求
    onInputChangeInfoValue(e) {
        let changeInfo = e.detail.value
        this.setData({
            changeInfo
        })
    },

    //验收时间
    onInputTime(e) {
        let nickedTime = e.detail
        this.setData({
            nickedTime
        })
    },

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

    //添加整改人
    onAddLordSent(e) {
        if (e.detail.length > 0) {
            this.setData({
                lordSent: e.detail[0].userName,
                lordSentUser: e.detail[0].phoneNumber
            })
        }
    },

    //添加抄送人
    onAddCopySend(e) {
        if (e.detail.length > 0) {
            let phoneNumbers = "";
            let userNames = "";
            e.detail.forEach(it => {
                phoneNumbers += "," + it.phoneNumber;
                userNames += "," + it.userName;
            });
            this.setData({
                copySend: userNames.substring(1),
                copySendUser: phoneNumbers.substring(1)
            })
        } else {
            this.setData({
                copySend: "",
                copySendUser: ""
            })
        }
    },

    //添加复检人
    onAddRecheckSend(e) {
        if (e.detail.length > 0) {
            this.setData({
                recheckSend: e.detail[0].userName,
                recheckSendUser: e.detail[0].phoneNumber
            })
        }
    },

    //取消页面
    cancelSaveView() {
        this.returnToPage()
    },

    //保存
    onProblemSubmitSave() {
        this.setData({
            loadShow: true
        })
        let that = this
        let {
            projectId,
            projectName,
            dangerType,
            lordSent,
            lordSentUser,
            copySend,
            copySendUser,
            workParts,
            changeInfo,
            nickedTime,
            recheckSend,
            recheckSendUser,
            imageInfoData,
            loginName,
            problemType,
            userName
        } = that.data;
        //数据效验
        if (projectId == "" || loginName == "") {
            app.toast("数据异常,请刷新页面重试!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (imageInfoData.length == 0) {
            app.toast("请上传隐患现场图片!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (problemType == "") {
            app.toast("请选择检查类型!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (dangerType == "") {
            app.toast("请选择隐患类型!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (workParts == "") {
            app.toast("请填写隐患描述!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (changeInfo == "") {
            app.toast("请填写隐患整改要求!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (nickedTime == "") {
            app.toast("请选择整改截至时间!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (lordSent == "" || lordSentUser == "") {
            app.toast("请选择整改人!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (recheckSend == "" || recheckSendUser == "") {
            app.toast("请选择复检人!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (copySend == "" || copySendUser == "") {
            app.toast("请选择抄送人!")
            that.setData({
                loadShow: false
            })
            return;
        }
        let pos = copySend.split(",");
        pos.forEach(it => {
            if (it == lordSent) {
                app.toast("抄送人中不能包含整改人!")
                that.setData({
                    loadShow: false
                })
                return;
            }
        });
        let fileUrls = [];
        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 params = {
                    projectId,
                    infoType: "1",
                    problemArea: projectName,
                    problemType,
                    workParts,
                    changeInfo,
                    lordSent,
                    lordSentUser,
                    copySend,
                    copySendUser,
                    checkState: 0,
                    nickedTime: nickedTime + " 23:59:59",
                    smarkUrl: fileUrls.toString(),
                    createUser: loginName,
                    dangerType,
                    recheckSend,
                    recheckSendUser
                }
                wx.request({
                    url: app.globalData.reqUrl + '/wechat/projectProblemmodify/addQuality',
                    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: '../list/index',
                                })
                            }, 200)
                        }
                    }
                })
            }
        })
    },

    /**
     * 这里考虑上传图片异步问题,封装为同步
     */
    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)
                }
            });
        })
    },

    //选择检查类型
    onSelectProblemType(e) {
        this.setData({
            problemType: e.detail.id
        })
    },

    //选择隐患类型
    onSelectDangerType(e) {
        this.setData({
            dangerType: e.detail.id
        })
    },

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

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})