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

    /**
     * 页面的初始数据
     */
    data: {
        maxDate:new Date(2088,1,1).getTime(),
        minDate:new Date().getTime()+(3600*48*1000),
        projectId:"",
        projectName:"",
        loginName:"",
        userName:"",
        rectifierData:[],
        loadShow:false,
        showHis:false,
        inspectInfoData:[
            {
                image_upload:[]
            }
        ],
        lordSent:"",
        lordSentUser:"",
    },

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

    //查询项目人员数据
    getAllProjectUserData(){
        let that = this
        wx.request({
            url: app.globalData.reqUrl+'/wechat/projectuserinfo/selectProjectUnitUser',
            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
                    })
                }
            }
        })
    },

    getHisInfo(){
        //这里查询当前登录人上次提交隐患，自动填充整改人，复检人，抄送人
        let that = this
        wx.request({
            url: app.globalData.reqUrl+'/wechat/projectProblemmodify/findDraftLastDataByParams',
            method:"get",
            data:{
                projectId:that.data.projectId,
                createUser:that.data.loginName,
                infoType:0
            },
            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
                    })
                }
            }
        })
    },

    // list  上传图片
    onImagesArr(e){
        var index = e.currentTarget.dataset.index
        var data = this.data.inspectInfoData
        data[index].image_upload = e.detail
        this.setData({
            inspectInfoData:data
        })
    },

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

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

    //保存
    onProblemSubmitSave(){
        this.setData({
            loadShow:true
        })
        let that = this
        let {projectId,projectName,lordSent,lordSentUser,loginName,inspectInfoData} =  that.data;
        //数据效验
        if(projectId==""||loginName==""){
            app.toast("数据异常，请刷新页面重试!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(lordSent==""||lordSentUser==""){
            app.toast("请选择整改人!")
            that.setData({
                loadShow:false
            })
            return;
        }
        let fileUrls = [];
        inspectInfoData.forEach(async (item)=>{
            let beforeCheckUrl = []; 
            item.image_upload.forEach(async (it)=>{
                let uploadUrl = app.globalData.uploadUrl+'/common/upload'
                let name = "file";
                //这里复杂的图片上传，改为同步上传，因为小程序只能上传一张图片
                let obj = await that.syncUploadImage(uploadUrl,it,name);
                beforeCheckUrl.push(obj.data.fileName);
                if(beforeCheckUrl.length >= item.image_upload.length){
                    fileUrls.push(beforeCheckUrl);
                }
                 //验证图片上传完毕
                if(fileUrls.length >= inspectInfoData.length){
                    let params = {
                        projectId,
                        infoType:"0",
                        problemArea:projectName,
                        lordSent,
                        lordSentUser,
                        checkState:0,
                        fileUrls:fileUrls,
                        createUser:loginName
                    }
                    wx.request({
                        url: app.globalData.reqUrl + '/wechat/projectProblemmodify/addQualityDraft',
                        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(()=>{
                                    if(wx.getStorageSync('nav-menu')=="list"){
                                        wx.redirectTo({
                                            url: '../list/index',
                                        })
                                    }else{
                                        wx.redirectTo({
                                            url: '../../../../pages/safety_manage/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)
            }
            });
        })
    },

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

    //新增问题
    onNewIssues(){
        var data = this.data.inspectInfoData
        if(data.length==5){
            app.toast("一次最多只能提交5个问题!");
            return false;
        }
        data.push(
            {
                image_upload:[]
            }
        )
        this.setData({
            inspectInfoData:data
        })
    },

    //删除
    onNewIssuesDelete(e){
        var index = e.currentTarget.dataset.index
        var data = this.data.inspectInfoData
        data.splice(index, 1)　
        this.setData({
            inspectInfoData:data
        })
    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})