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

    /**
     * 页面的初始数据
     */
    data: {
        maxDate:new Date(2088,1,1).getTime(),
        currentDate:new Date().getTime(),
        deptId:"",
        projectId:"",
        loginName:"",
        userName:"",
        imageInfoData:[],
        data:{},
        projectType:"",
        projectTypeName:"",
        uploadImages:[],
        request:app.globalData.reqUrl
    },

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

    //查询项目历史形象进度数据
    getProjectScheduleData(){
        let that = this
        wx.request({
            url: app.globalData.reqUrl+'/wechat/projectSchedule/lastInfo',
            method:"get",
            data:{
                projectId:that.data.projectId
            },
            header:{
              'content-type': 'application/x-www-form-urlencoded'  
            },
            success(res){
                res = res.data
                if(res.code == 200){
                    let type = res.data.projectType;
                    let typeName = "";
                    switch(type){
                        case "1" : typeName = "在建"; break;
                        case "2" : typeName = "拟建"; break;
                        case "3" : typeName = "前期"; break;
                        case "4" : typeName = "完工"; break;
                    }
                    let minUrls = [];
                    if(res.data.image){
                        res.data.image.split(',').forEach(element => {
                          minUrls.push(that.data.request+element+'.min.jpg');
                        });
                    }
                    that.setData({
                        data:res.data,
                        projectType:type,
                        projectTypeName:typeName,
                        uploadImages:minUrls,
                        imageInfoData:minUrls
                    })
                }
            }
        })
    },

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

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

    //保存
    onProblemSubmitSave(){
        this.setData({
            loadShow:true
        })
        let that = this
        let {projectId,loginName,imageInfoData,data,projectType} =  that.data;
        //数据效验
        if(projectId==""||loginName==""){
            app.toast("数据异常，请刷新页面重试!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(imageInfoData.length==0){
            app.toast("请上传形象进度图片!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(data.plannedNode==""){
            app.toast("请填写计划节点描述!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(data.actualNode==""){
            app.toast("请填写实际节点描述!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(data.purchaseProgress==""){
            if(projectType==4){
                app.toast("请填写结算进展描述!")
            }else{
                app.toast("请填写报建、设计进展描述!")
            }
            that.setData({
                loadShow:false
            })
            return;
        }
        if(data.designProgress==""){
            if(projectType==4){
                app.toast("请填写运维进展描述!")
            }else{
                app.toast("请填写报建、设计进展描述!")
            }
            that.setData({
                loadShow:false
            })
            return;
        }
        if(data.constructionProgress==""){
            app.toast("请填施工进展描述!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(data.acceptanceProgress==""){
            app.toast("请填写验收进展描述!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(data.planForNextWeek==""){
            app.toast("请填写下周计划描述!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(data.existingProblem==""){
            app.toast("请填写存在问题描述!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(data.problemProgress==""){
            app.toast("请填写问题推进情况描述!")
            that.setData({
                loadShow:false
            })
            return;
        }
        
        let fileUrls = [];
        imageInfoData.forEach(async (item)=>{
            let uploadUrl = app.globalData.uploadUrl+'/common/upload'
            let name = "file" 
            //这里复杂的图片上传，改为同步上传，因为小程序只能上传一张图片
            if(item.indexOf(that.data.request)==-1){
                let obj = await that.syncUploadImage(uploadUrl,item,name);
                fileUrls.push(obj.data.fileName);
            }else{
                fileUrls.push(item.replace(that.data.request,"").replace(".min.jpg",""));
            }
            //验证图片上传完毕
            if(fileUrls.length == imageInfoData.length){
                let params = {
                    projectId,
                    image:fileUrls.toString(),
                    plannedNode:data.plannedNode,
                    actualNode:data.actualNode,
                    purchaseProgress:data.purchaseProgress,
                    designProgress:data.designProgress,
                    constructionProgress:data.constructionProgress,
                    acceptanceProgress:data.acceptanceProgress,
                    planForNextWeek:data.planForNextWeek,
                    existingProblem:data.existingProblem,
                    problemProgress:data.problemProgress,
                    dataTemplate:projectType,
                    createBy:loginName
                }
                wx.request({
                    url: app.globalData.reqUrl + '/wechat/projectSchedule/add',
                    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.navigateTo({
                                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)
            }
            });
        })
    },

    plannedNodeAction: function (options) {
        this.data.data.plannedNode = options.detail.value;
    },
    actualNodeAction: function (options) {
        this.data.data.actualNode=options.detail.value;
    },
    purchaseProgressAction: function (options) {
        this.data.data.purchaseProgress = options.detail.value
    },
    designProgressAction: function (options) {
        this.data.data.designProgress = options.detail.value
    },
    constructionProgressAction: function (options) {
        this.data.data.constructionProgress = options.detail.value
    },
    acceptanceProgressAction: function (options) {
        this.data.data.acceptanceProgress = options.detail.value
    },
    planForNextWeekAction: function (options) {
        this.data.data.planForNextWeek = options.detail.value
    },
    existingProblemAction: function (options) {
        this.data.data.existingProblem = options.detail.value
    },
    problemProgressAction: function (options) {
        this.data.data.problemProgress = options.detail.value
    },

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

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})