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

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

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let {projectId,projectName} = options
        //获取缓存数据
        wx.getStorage({
        key: 'userinfo',
        success:res=>{
            this.setData({
            projectId,
            projectName,
            deptId:res.data.deptId,
            loginName:res.data.loginName
            })
            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({
                witnessUserName:userNames.substring(1),
                witnessUser:phoneNumbers.substring(1)
            })
        }else{
            this.setData({
                witnessUser:"",
                witnessUserName:""
            })
        }
    },

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

    //保存
    onSave(){
        this.setData({
            loadShow:true
        })
        let that = this
        let {projectId,projectName,deptId,loginName,imageInfoData,materialName,
        usePosition,contractBrand,useBrand,sealDate,witnessUser,witnessUserName,signFileData,alterationFileData} =  that.data;
        //数据效验
        if(projectId==""||loginName==""||deptId==""){
            app.toast("数据异常，请刷新页面重试!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(imageInfoData.length==0){
            app.toast("请上传封样现场图片!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(materialName==""){
            app.toast("请填写封样名称!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(usePosition==""){
            app.toast("请填写使用部位!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(contractBrand==""){
            app.toast("请填写合同指定品牌!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(useBrand==""){
            app.toast("请填写拟用品牌!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(sealDate==""){
            app.toast("请选择封样时间!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(witnessUser==""||witnessUserName==""){
            app.toast("请选择监理专员!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(signFileData.length==0){
            app.toast("请上传会签单照片!")
            that.setData({
                loadShow:false
            });
            return;
        }
        if(contractBrand.indexOf(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" 
            //这里复杂的图片上传，改为同步上传，因为小程序只能上传一张图片
            let obj = await that.syncUploadImage(uploadUrl,item,name);
            fileUrls.push(obj.data.fileName);
            //验证图片上传完毕
            if(fileUrls.length == imageInfoData.length){
                //上传会签单
                let signFile = await that.syncUploadImage(uploadUrl,signFileData[0],name);
                //上传变更单
                let alterationFilePath = "";
                if(alterationFileData.length>0){
                   obj = await that.syncUploadImage(uploadUrl,alterationFileData[0],name);
                   alterationFilePath = obj.data.fileName
                }
                let params = {
                    projectId,
                    projectName,
                    deptId,
                    imageUrls:fileUrls.toString(),
                    materialName,
                    usePosition,
                    contractBrand,
                    useBrand,
                    sealDate:sealDate+":00",
                    witnessUser,
                    witnessUserName,
                    signFiles:signFile.data.fileName,
                    alterationFiles:alterationFilePath,
                    approveStatus:"1",
                    createBy:loginName
                }
                wx.request({
                    url: app.globalData.reqUrl + "/wechat/projectMaterialSeal/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.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.materialName = options.detail.value;
    },
    usePositionAction: function (options) {
        this.data.usePosition = options.detail.value
    },
    contractBrandAction: function (options) {
        this.data.contractBrand = options.detail.value
        this.showBgdLabel()
    },
    useBrandAction: function (options) {
        this.data.useBrand = options.detail.value
        this.showBgdLabel()
    },

    //查询项目人员数据
    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(){
        if(this.data.contractBrand!="" && this.data.useBrand!="" && this.data.contractBrand.indexOf(this.data.useBrand)==-1){
            this.setData({
                showBgd:true
            })
        }else{
            this.setData({
                showBgd:false
            })
        }
    },

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

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

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})