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

    /**
     * 页面的初始数据
     */
    data: {
        maxDate:new Date(2088,1,1).getTime(),
        deptId:"",
        projectId:"",
        projectName:"",
        loginName:"",
        userName:"",
        imageInfoData:[],
        trainTitle:"",
        trainParticipants:"",
        beginDate:"",
        trainContent:"",
        trainFileData:[],
        limit:1,
        trainType:"",
        title:"",
        minTitle:"",
        showDept:false,
        projectDeptList:[],
        navs:[],
        deptNames:"",
        fileType:["doc","docx","xls","xlsx","ppt","pptx","txt","pdf","png","jpg","jpeg","mp4"]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let {projectId,projectName,trainType} = options
        //获取缓存数据
        wx.getStorage({
        key: 'userinfo',
        success:res=>{
            let title="";
            let minTitle="";
            if(trainType=="0"){
                title="专项培训";
                minTitle="培训";
            }else{
                title="应急演练";
                minTitle="演练";
            }
            this.setData({
            projectId,
            projectName,
            trainType,
            title,
            minTitle,
            deptId:res.data.deptId,
            loginName:res.data.loginName,
            userName:res.data.nickName
            })
            this.getProjectDeptList(projectId,res.data.deptId,res.data.minRoleId); 
        }  
        }) 
    },

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

    //获取项目单位
    getProjectDeptList(projectId,deptId,minRoleId){
        let that = this
        wx.request({
          url: app.globalData.reqUrl+'/wechat/projectTrain/queryUnitList',
          method:"get",
          data:{
            projectId:projectId,
            nowDept:deptId,
            nowRole:minRoleId   
          },
          success(res){
            res = res.data
            if(res.code == 200){
                let temdata=[];
                res.data.forEach((item)=>{
                    item.state='0';
                    temdata.push(item);
                })
                that.setData({
                    projectDeptList:temdata
                })
            }
          }
        })
    },

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

    //保存
    onSave(){
        this.setData({
            loadShow:true
        })
        let that = this
        let {projectId,projectName,loginName,imageInfoData,trainType,trainTitle,trainParticipants,beginDate,trainContent,trainFileData,minTitle,deptId} =  that.data;
        //数据效验
        if(projectId==""||loginName==""){
            app.toast("数据异常，请刷新页面重试!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(imageInfoData.length==0){
            app.toast("请上传"+minTitle+"图片!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(trainTitle==""){
            app.toast("请填写"+minTitle+"标题!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(beginDate==""){
            app.toast("请选择"+minTitle+"时间!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(trainParticipants==""){
            app.toast("请填写参与人数!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(trainContent==""){
            app.toast("请填写"+minTitle+"内容!")
            that.setData({
                loadShow:false
            })
            return;
        }
        if(trainFileData.length==0){
            app.toast("请上传相关文件!")
            that.setData({
                loadShow:false
            });
            return;
        }
        let _fileType = trainFileData[0].path.split('.');
        _fileType = _fileType[_fileType.length-1].toLowerCase();
        //判断附件类型，如果是图片直接展示，非图片则显示附件
        if(this.data.fileType.indexOf(_fileType)==-1){
            app.toast("当前 [ "+_fileType+" ] 文件不支持上传!")
            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){
                //上传文件
                obj = await that.syncUploadImage(uploadUrl,trainFileData[0].path,name);
                let depts = [];
                this.data.navs.forEach((it)=>{
                    depts.push({deptId:that.data.projectDeptList[it].unitId});
                });
                let params = {
                    projectId,
                    projectName,
                    mainImage:fileUrls.toString(),
                    trainType,
                    trainTitle,
                    beginDate:beginDate+" 12:00:00",
                    trainParticipants,
                    trainContent,
                    trainFile:obj.data.fileName,
                    deptId,
                    workTrainDeptList:depts,
                    createBy:loginName
                }
                let url="";
                if(trainType=="0"){
                   url="/wechat/projectTrain/addTrain";
                }else{
                   url="/wechat/projectTrain/addEmergencyDrill";
                }
                wx.request({
                    url: app.globalData.reqUrl + url,
                    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?trainType='+trainType,
                            })
                            },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)
            }
            });
        })
    },

    trainTitleAction: function (options) {
        this.data.trainTitle = options.detail.value;
    },
    onInputNumber: function (options) {
        let value = options.detail.value;
        value = value.replace(/[^0-9]/g, ''); // 正则表达式替换非数字为空
        this.setData({
            trainParticipants: value
        });
    },
    trainContent: function (options) {
        this.data.trainContent = options.detail.value
    },

    fileUpload(e){
        this.setData({
            trainFileData:e.detail
        });
    },

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

    onShowDept(){
        this.setData({
            showDept:true
        })
    },

    onCloseDept(){
        this.setData({
            showDept:false
        })
    },

    changeDept(event){
        let idx = event.target.dataset.index;
        let data = this.data.projectDeptList;
        if(this.data.navs.indexOf(idx)>-1){
            this.data.navs.splice(this.data.navs.indexOf(idx), 1);
            data[idx].state='0';
        }else{
            this.data.navs.push(idx);
            data[idx].state='1';
        }
        let deptNames = "";
        this.data.navs.forEach((it)=>{
            deptNames+=","+data[idx].unitName;
        });
        this.setData({
            deptNames:deptNames.substring(1),
            projectDeptList:data
        })
    },

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

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})