import {
    syncFileUpload
} from '../../../utils/request'
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        maxDate: new Date(2088, 1, 1).getTime(),
        deptId: "",
        projectId: "",
        projectName: "",
        loginName: "",
        rectifierData: [],
        loadShow: false,
        checkTypeList: [],
        checkType: "1",
        materialName: "",
        usePosition: "",
        sampleNum: "",
        qualifiedFlag: "Y",
        witnessUser: "",
        witnessUserName: "",
        checkTime: "",
        laboratoryName: "",
        qualifiedFlagList: [{
            id: 'Y',
            text: "是"
        }, {
            id: 'N',
            text: "否"
        }],
        flowNodes: [{
            text: '开始'
        }, {
            text: '提交申请'
        }, {
            text: '检测报告'
        }, {
            text: '监理审批'
        }, {
            text: '结束'
        }],
        active: 0,
        trustDeed: [],
        attachment: [],
        fileType: ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "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.getProjectUserData();
                this.getTypeList();
            }
        })
    },

    //查询项目人员数据
    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
                    })
                }
            }
        })
    },

    getTypeList() {
        let that = this
        wx.request({
            url: app.globalData.reqUrl + '/wechat/projectDetection/queryType',
            method: "get",
            data: {},
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success(res) {
                res = res.data
                if (res.code == 200) {
                    let list = [];
                    res.data.forEach(it => {
                        list.push({
                            "id": it.dictValue,
                            "text": it.dictLabel
                        });
                    })
                    that.setData({
                        checkTypeList: list
                    })
                }
            }
        })
    },

    //材料名称
    onInputMaterialNameValue(e) {
        let materialName = e.detail.value
        this.setData({
            materialName
        })
    },

    //使用部位
    onInputUsePositionValue(e) {
        let usePosition = e.detail.value
        this.setData({
            usePosition
        })
    },
    //取样数量
    onInputSampleNumValue(e) {
        let sampleNum = e.detail.value
        this.setData({
            sampleNum
        })
    },
    //送检实验室名称
    onInputLaboratoryNameValue(e) {
        let laboratoryName = e.detail.value
        this.setData({
            laboratoryName
        })
    },

    //验收时间
    onInputTime(e) {
        let checkTime = e.detail
        this.setData({
            checkTime
        })
    },

    //添加监理专员
    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() {
        this.returnToPage()
    },

    //保存
    onSubmitSave() {
        this.setData({
            loadShow: true
        })
        let that = this
        let {
            projectId,
            deptId,
            checkType,
            materialName,
            usePosition,
            sampleNum,
            qualifiedFlag,
            witnessUser,
            witnessUserName,
            checkTime,
            laboratoryName,
            loginName,
            trustDeed,
            attachment
        } = that.data;
        //数据效验
        if (projectId == "" || loginName == "" || deptId == "") {
            app.toast("数据异常,请刷新页面重试!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (checkType == "") {
            app.toast("请选择送检类型!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (materialName == "") {
            app.toast("请填写材料名称!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (sampleNum == "") {
            app.toast("请填写取样数量!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (usePosition == "") {
            app.toast("请填写使用部位!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (qualifiedFlag == "") {
            app.toast("请选择是否提供合格证!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (qualifiedFlag == "") {
            app.toast("请选择是否提供合格证!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (witnessUser == "" || witnessUserName == "") {
            app.toast("请选择见证人!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (checkTime == "") {
            app.toast("请选择送检时间!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (laboratoryName == "") {
            app.toast("请填写送检实验室名称!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (trustDeed.length == 0) {
            app.toast("请上传检验委托单!")
            that.setData({
                loadShow: false
            })
            return;
        }
        if (attachment.length > 0) {
            for (let i = 0; i < attachment.length; i++) {
                let _fileType = attachment[i].path.split('.');
                _fileType = _fileType[_fileType.length - 1].toLowerCase();
                //判断附件类型,如果是图片直接展示,非图片则显示附件
                if (this.data.fileType.indexOf(_fileType) == -1) {
                    app.toast("当前 [ " + _fileType + " ] 文件不支持上传!")
                    that.setData({
                        loadShow: false
                    });
                    return;
                }
            }
        }
        let _files = [];
        trustDeed.forEach(item => {
            syncFileUpload(item).then(res => {
                if (res.code == 200) {
                    let params = {
                        projectId,
                        deptId,
                        checkType,
                        materialName,
                        usePosition,
                        sampleNum,
                        qualifiedFlag,
                        witnessUser,
                        witnessUserName,
                        checkTime: checkTime,
                        laboratoryName,
                        createBy: loginName,
                        trustDeed: res.fileName
                    }
                    if (attachment.length > 0) {
                        attachment.forEach(file => {
                            syncFileUpload(file.path).then(res => {
                                _files.push(res.fileName);
                                if (attachment.length == _files.length) {
                                    params.attachment = JSON.stringify(_files);
                                    this.submitForm(params);
                                }
                            });
                        });
                    } else {
                        this.submitForm(params);
                    }
                }
            });
        });
    },

    /**
     * 提交表单
     * @param {*} params 
     */
    submitForm(params) {
        let that = this;
        wx.request({
            url: app.globalData.reqUrl + '/wechat/projectDetection/add',
            method: "POST",
            data: params,
            header: {
                "Username": that.data.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)
                }
            }
        })
    },

    //选择检测类型
    onSelectCheckType(e) {
        this.setData({
            checkType: e.detail.id
        })
    },
    //选择是否提供合格证
    onSelectQualifiedFlag(e) {
        this.setData({
            qualified: e.detail.id
        })
    },

    // list  上传图片
    onImagesArr(e) {
        this.setData({
            trustDeed: e.detail
        })
    },

    /**
     * 相关附件上传
     * @param {*} options 
     */
    otherFileUpload(options) {
        let file = options.detail;
        this.setData({
            attachment: file
        });
    },

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

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})