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

    /**
     * 页面的初始数据
     */
    data: {
        maxDate:new Date(2099,1,1).getTime(),
        projectId:"",
        loginName:"",
        userName:"",
        personnelShow:false,
        rectifierData:[],
        inspectInfoData:[
            {
                existing_problems:'',
                image_upload:[],
                person_responsible:[]
            },
        ],
        stateNav:2,
        checkType:1,
        //检查部位名称
        checkSiteName:'',
        //检查时间
        checkTime:'',
        //检查限制时间
        checkImposeTime:'',
        loadShow:false
    },
       /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let {projectId} = options
        //获取缓存数据
        wx.getStorage({
        key: 'userinfo',
        success:res=>{
            this.setData({
            projectId,
            loginName:res.data.loginName,
            userName:res.data.userName
            }) 
            this.getRectifierData()
        }  
        }) 
    },
    //获取选中人信息
    getRectifierData(){
        let that = this
        let {projectId} = this.data
        wx.request({
            url: app.globalData.szhUrl+'/system/checkDutyUser/list',
            method:"POST",
            data:{
                projectId
            },
            header:{
              'content-type': 'application/x-www-form-urlencoded'  
            },
            success(res){
                res = res.data
                if(res.code == 0 && res.rows.length > 0){
                    let tempdata = []
                    res.rows.forEach(item=>{
                        tempdata.push({
                            state:false,
                            name:item.userName,
                            url: item.photoUrl,
                            loginName:item.loginName,
                            userId:item.userId  
                       })
                    })
                    that.setData({
                        rectifierData:tempdata  
                    })
                }
            }
        })
    },

    //切换检查类型
    onStateSelect(e){
        let state = e.currentTarget.dataset.set;
        this.setData({
            stateNav:state,  
        });
    },

    //检查部位
    onInputValue(e){
        let checkSiteName = e.detail.value
        this.setData({
            checkSiteName
        })
    },

    //检查时间
    onStartTime(e){
        let checkTime = e.detail
        this.setData({
            checkTime
        })
    },

    //限期整改时间
    onEndTime(e){
        let checkImposeTime = e.detail
        this.setData({
            checkImposeTime
        })
    },

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

    //新增问题
    onNewIssues(){
        var data = this.data.inspectInfoData
        data.push(
            {
                existing_problems:'',
                image_upload:[],
                person_responsible:[]
            }
        )
        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
        })
    },

    // 存在问题input
    onPositionInput(e){
        var index = e.currentTarget.dataset.index
        var data = this.data.inspectInfoData
        data[index].existing_problems = e.detail.value
        this.setData({
            inspectInfoData:data
        })
    },

    //添加整改责任人
    onAddResponsible(e){
        var index = e.currentTarget.dataset.index
        var data = this.data.inspectInfoData
        data[index].person_responsible = e.detail
        this.setData({
            inspectInfoData:data
        })
       
    },

    //取消页面
    cancelSaveView(){
        wx.navigateBack()
    },



    //保存
    onProblemSubmitSave(){
        this.setData({
            loadShow:true
        })
        let that = this
        let {projectId,loginName,userName,checkType,stateNav,checkSiteName,checkTime,checkImposeTime,inspectInfoData} =  that.data
        if(stateNav == '3'){
            stateNav = '2'
            checkType = '2'
        }
        
        
        //数据校验
        if(!checkSiteName || checkSiteName.length<=0 || !checkTime || checkTime.length <= 0 || !checkImposeTime || checkImposeTime.length <= 0){
            app.toast("数据填写不完整!")
            that.setData({
                loadShow:false
            })
            return;    
        }
        //校验信息
        let flag = false
        for(let i = 0;i <inspectInfoData.length;i++){
            if(inspectInfoData[i].existing_problems.length <= 0){
                flag = true
                app.toast("存在问题不能为空!")
                that.setData({
                    loadShow:false
                })
                break;
            }
            if(inspectInfoData[i].image_upload.length <= 0){
                flag = true
                app.toast("检查图片不能为空!")
                that.setData({
                    loadShow:false
                })
                break;
            }

            if(inspectInfoData[i].person_responsible <= 0){
                flag = true
                app.toast("责任整改人不能为空!")
                that.setData({
                    loadShow:false
                })
                break;
            }
        }
        if(flag){
            return;
        }

        let tempInspectInfoData = []
        inspectInfoData.forEach(async (item)=>{
            console.log(app.globalData.reqUrl+'/weixin/security/fileUploads')
            let beforeCheckUrl = [] 
            item.image_upload.forEach(async (item1)=>{
               let requestUrl = app.globalData.reqUrl+'/weixin/security/fileUpload'
               let name = "file" 
               //这里复杂的图片上传，改为同步上传，因为小程序只能上传一张图片
               let photoUrlObj = await that.syncUploadImage(requestUrl,item1,name)
               beforeCheckUrl.push(photoUrlObj.data.url)   
               if(beforeCheckUrl.length >= item.image_upload.length){
                tempInspectInfoData.push({
                    issueContext:item.existing_problems,
                    beforeCheckUrl:beforeCheckUrl.join(","),
                    checkUserId:item.person_responsible[0].userId,
                    checkUserName:item.person_responsible[0].name,
                    checkLoginName:item.person_responsible[0].loginName,
                })
               }
               if(tempInspectInfoData.length >= inspectInfoData.length){
                let params = {
                    projectId,
                    checkLoginName:loginName,
                    checkType,
                    userName,
                    deptId:"131",
                    checkTitle:stateNav,
                    checkSiteName,
                    checkTime,
                    checkImposeTime,
                    saftCheckIssueItemList:tempInspectInfoData
                }
                wx.request({
                  url: app.globalData.szhUrl + '/system/saftcheckissue/addJson',
                  method:"POST",
                  data:params,
                  header: {
                    "Content-Type": "application/json"
                  },
                  success(res){
                    that.setData({
                        loadShow:true
                    })
                    res =res.data
                    if(res.code == 0){
                        app.toast("添加成功!")
                        setTimeout(()=>{
                           wx.navigateTo({
                             url: '../securityCheckGR/index',
                           })
                        },2000)
                    }
                   
                  }
                })
                }
            })
           
        
           
           
        })



    
    
    
    },



    /**
     * 这里考虑上传图片异步问题，封装为同步
     */

    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)
            }
            });
        })
          
    
    
    },






 

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})