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

    /**
     * 页面的初始数据
     */
    data: {
        id:"",
        maxDate:new Date(2088,1,1).getTime(),
        currentDate:new Date().getTime(),
        projectId:"",
        projectName:"",
        loginName:"",
        imageInfoData:[],
        signFileData:[],
        alterationFileData:[],
        limit:1,
        showBgd:false,
        rectifierData:[],
        materialName:"",
        usePosition:"",
        contractBrand:"",
        useBrand:"",
        sealDate:"",
        witnessUser:"",
        witnessUserName:"",
        activeName:"",
        flowRecordList:[],
        infoData:{},
        request:app.globalData.reqUrl
    },

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

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

    //添加监理专员
    onAddSend(e){
        if(e.detail.length>0){
            let phoneNumbers="";
            let userNames="";
            e.detail.forEach(it =>{
                phoneNumbers+=","+it.phoneNumber;
                userNames+=","+it.userName;
            });
            this.setData({
                "infoData.witnessUserName":userNames.substring(1),
                "infoData.witnessUser":phoneNumbers.substring(1)
            })
        }else{
            this.setData({
                "infoData.witnessUser":"",
                "infoData.witnessUserName":""
            })
        }
    },

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

       /**
     * 获取安全检查详情信息
     * 
     */
    getInfo(){
        let {id} = this.data
        let that = this
        wx.request({
          url: app.globalData.reqUrl+'/wechat/projectMaterialSeal/info',
          method:"get",
          data:{
              id:id          
          },
          success(res){
            res = res.data
            if(res.code == 200){
                let imageInfoData = [];
                if(res.data.imageUrls){
                  res.data.imageUrls.split(',').forEach(element => {
                    imageInfoData.push(that.data.request+element+'.min.jpg');
                  });
                }
                let signFileData = [];
                //判断附件
                if(res.data.signFiles){
                  res.data.signFiles.split(',').forEach(element => {
                    let type = element.split('.');
                    type = type[type.length-1].toUpperCase();
                    if(type=="PDF"){
                        app.toast("小程序不支持修改PDF格式的会签单，请前往PC后台修改!");
                        setTimeout(()=>{
                        wx.redirectTo({
                            url: '../list/index'
                        })
                        },200)
                    }  
                    //let it = element.split('/');
                    //signFileData.push({name:it[it.length-1],path:element});
                    signFileData.push(that.data.request+element+'.min.jpg');
                  });
                }
                let alterationFileData = [];
                //判断附件
                if(res.data.alterationFiles){
                  res.data.alterationFiles.split(',').forEach(element => {
                    let type = element.split('.');
                    type = type[type.length-1].toUpperCase();
                    if(type=="PDF"){
                        app.toast("小程序不支持修改PDF格式的变更单，请前往PC后台修改!");
                        setTimeout(()=>{
                        wx.redirectTo({
                            url: '../list/index'
                        })
                        },200)
                    }
                    //let it = element.split('/');
                    //alterationFileData.push({name:it[it.length-1],path:element});
                    alterationFileData.push(that.data.request+element+'.min.jpg');
                  });
                }
                that.setData({
                    infoData:res.data,
                    signFileData,
                    alterationFileData,
                    imageInfoData,
                    loadShow:false
                })
                that.showBgdLabel(res.data);
            }
          }
        })
    },

    /**
     * 查询流程日志
     */
    getAuditinfo(){
        let that = this
        wx.request({
          url: app.globalData.reqUrl+'/wechat/projectAuditinfo/selectProjectAuditinfo',
          method:"get",
          data:{
              fromType:"4",
              fromId:this.data.id          
          },
          success(res){
            res = res.data
            if(res.code == 200){
              that.setData({
                flowRecordList:res.data
              })
            }
          }
        })
    },
  
    // 手风琴
    onChange(event) {
      this.setData({
        activeName: event.detail,
      });
    },

    //保存
    onSave(){
        this.setData({
            loadShow:true
        })
        let that = this
        let {id,loginName,imageInfoData,signFileData,alterationFileData,infoData} =  that.data;
        //数据效验
        if(id==""){
            app.toast("数据异常，请刷新页面重试!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(imageInfoData.length==0){
            app.toast("请上传封样现场图片!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(infoData.materialName==""){
            app.toast("请填写封样名称!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(infoData.usePosition==""){
            app.toast("请填写使用部位!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(infoData.contractBrand==""){
            app.toast("请填写合同指定品牌!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(infoData.useBrand==""){
            app.toast("请填写拟用品牌!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(infoData.sealDate==""){
            app.toast("请选择封样时间!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(infoData.witnessUser==""||infoData.witnessUserName==""){
            app.toast("请选择监理专员!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(signFileData.length==0){
            app.toast("请上传会签单照片!")
            that.setData({
                loadShow:false
            });
            return;
        }
        if(infoData.contractBrand.indexOf(infoData.useBrand)==-1 && alterationFileData.length==0){
            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){
                fileUrls.push(item.replace(that.data.request,"").replace(".min.jpg",""));
            }else{
                let obj = await that.syncUploadImage(uploadUrl,item,name);
                fileUrls.push(obj.data.fileName);
            }
            //验证图片上传完毕
            if(fileUrls.length == imageInfoData.length){
                let signFilePath="";
                if(signFileData[0].indexOf(that.data.request)>-1){
                    signFilePath = signFileData[0].replace(that.data.request,"").replace(".min.jpg","");
                }else{
                    //上传会签单
                    let signFile = await that.syncUploadImage(uploadUrl,signFileData[0],name);
                    signFilePath = signFile.data.fileName;
                }
                //上传变更单
                let alterationFilePath = "";
                if(alterationFileData.length>0){
                    if(alterationFileData[0].indexOf(that.data.request)>-1){
                        alterationFilePath = alterationFileData[0].replace(that.data.request,"").replace(".min.jpg","");
                    }else{
                        //上传会签单
                        let alterationFile = await that.syncUploadImage(uploadUrl,alterationFileData[0],name);
                        alterationFilePath = alterationFile.data.fileName;
                    }
                }
                let params = {
                    id,
                    imageUrls:fileUrls.toString(),
                    materialName:infoData.materialName,
                    usePosition:infoData.usePosition,
                    contractBrand:infoData.contractBrand,
                    useBrand:infoData.useBrand,
                    sealDate:infoData.sealDate+":00",
                    witnessUser:infoData.witnessUser,
                    witnessUserName:infoData.witnessUserName,
                    signFiles:signFilePath,
                    alterationFiles:alterationFilePath,
                    approveStatus:"1",
                    updateBy:loginName
                }
                wx.request({
                    url: app.globalData.reqUrl + "/wechat/projectMaterialSeal/edit",
                    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)
            }
            });
        })
    },

    materialNameAction: function (options) {
        this.data.infoData.materialName = options.detail.value;
    },
    usePositionAction: function (options) {
        this.data.infoData.usePosition = options.detail.value
    },
    contractBrandAction: function (options) {
        this.data.infoData.contractBrand = options.detail.value;
        this.showBgdLabel(this.data.infoData);
    },
    useBrandAction: function (options) {
        this.data.infoData.useBrand = options.detail.value;
        this.showBgdLabel(this.data.infoData);
    },

    //演练训练时间
    onInputTime(e){
        let sealDate = e.detail
        this.setData({
            "infoData.sealDate":sealDate
        })
    },

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

    showBgdLabel(data){
        if(data.contractBrand!="" && data.useBrand!="" && data.contractBrand.indexOf(data.useBrand)==-1){
            this.setData({
                showBgd:true
            })
        }else{
            this.setData({
                showBgd:false
            })
        }
    },

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

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})