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

    /**
     * 页面的初始数据
     */
    data: {
        maxDate:new Date(2088,1,1).getTime(),
        deptId:"",
        projectId:"",
        projectName:"",
        loginName:"",
        name:"",
        sex:"1",
        phoneNumber:"",
        specialType:"1",
        credentialNumber:"",
        credentialExpirationTime:"",
        sexList:[{id:"1",text:"男"},{id:"2",text:"女"},{id:"3",text:"未知"}],
        specialTypeList:[],
        credentialFileData:[],
        limit:1,
        fileType:["pdf","png","jpg","jpeg"]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    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.getDictData(); 
        }  
        }) 
    },

    //获取字典数据
    getDictData(){
        let that = this
        wx.request({
          url: app.globalData.reqUrl+'/wechat/projectSpecial/querySpecialType',
          method:"get",
          data:{},
          success(res){
            res = res.data
            if(res.code == 200){
                let temData=[];
                res.data.forEach(item =>{
                    temData.push({id:item.dictValue,text:item.dictLabel});
                });
                that.setData({
                    specialTypeList:temData
                })
            }
          }
        })
    },

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

    //保存
    onSave(){
        this.setData({
            loadShow:true
        })
        let that = this
        let {projectId,projectName,deptId,loginName,name,sex,phoneNumber,specialType,credentialNumber,credentialExpirationTime,credentialFileData} =  that.data;
        //数据效验
        if(projectId==""||loginName==""||deptId==""){
            app.toast("数据异常，请刷新页面重试!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(name==""){
            app.toast("请填写人员姓名!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(sex==""){
            app.toast("请选择人员性别!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(phoneNumber==""){
            app.toast("请填写联系方式!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(phoneNumber.length!=11){
            app.toast("人员联系方式格式错误!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(specialType==""){
            app.toast("请选择人员类型!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(credentialNumber==""){
            app.toast("请填写证书编号!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(credentialExpirationTime==""){
            app.toast("请选择证书过期时间!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(credentialFileData.length==0){
            app.toast("请上传证书附件!")
            that.setData({
                loadShow:false
            });
            return;
        }
        let _fileType = credentialFileData[0].path.split('.');
        _fileType = _fileType[_fileType.length-1].toLowerCase();
        //判断附件类型，如果是图片直接展示，非图片则显示附件
        if(this.data.fileType.indexOf(_fileType)==-1){
            app.toast("证书附件不支持 [ "+_fileType+" ] 格式!")
            that.setData({
                loadShow:false
            });
            return;
        }
        credentialFileData.forEach(async (item)=>{
            let uploadUrl = app.globalData.uploadUrl+'/common/upload'
            let uploadName = "file" 
            //这里复杂的图片上传，改为同步上传，因为小程序只能上传一张图片
            let obj = await that.syncUploadImage(uploadUrl,credentialFileData[0].path,uploadName);
            let params = {
                projectId,
                projectName,
                deptId,
                specialType,
                name,sex,phoneNumber,credentialNumber,credentialExpirationTime,
                credentialFile:obj.data.fileName,
                isCredential:"Y",
                isDel:0,
                createBy:loginName
            }

            wx.request({
                url: app.globalData.reqUrl + "/wechat/projectSpecial/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)
            }
            });
        })
    },

    nameAction: function (options) {
        this.data.name = options.detail.value;
    },
    
    phoneAction: function (options) {
        let value = options.detail.value;
        value = value.replace(/[^0-9]/g, ''); // 正则表达式替换非数字为空
        this.setData({
            phoneNumber: value
        });
    },
    credentialNumberAction: function (options) {
        this.data.credentialNumber = options.detail.value
    },

    fileUpload(options){
        let file=options.detail;
        this.setData({
            credentialFileData: file
        });
    },

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

    //切换性别
    onSelectSex(e){
        this.setData({
            sex:e.detail.id
        })
    },
    //切换人员类型
    onSelectSpecialType(e){
        this.setData({
            specialType:e.detail.id
        })
    },
          
    returnToPage: function () {
        /*关闭当前页面，跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面*/
        wx.redirectTo({
            url: '../list/index',
        })
    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})