import config from '../../../config'
import {
    getToken,
    getUserInfo
} from '../../../utils/auth'
import {
    findDictCache
} from '../../../api/publics'
import {
    findProjectDeptUsers
} from '../../../api/project'
import {
    addDraft,
    findMyLastProblemmodify
} from '../../../api/problemmodify'
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        type: "",
        typeName: "",
        problemTypeList: [],
        form: {
            projectId: "",
            projectName: "",
            infoType: "",
            problemType: "1",
            lordSent: "",
            lordSentUser: "",
        },
        active: 1,
        flowNodes: [{
            text: '开始'
        }, {
            text: '提交隐患'
        }, {
            text: '隐患整改'
        }, {
            text: '隐患复检'
        }, {
            text: '结束'
        }],
        lordSentList: [],
        loadShow: false,
        showHis: false,
        inspectInfoData: [{
            image_upload: []
        }]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (!getToken()) {
            wx.redirectTo({
                url: '../../../login/login',
            })
        }
        const proUserInfo = getUserInfo();
        this.setData({
            type: options.type,
            typeName: options.type == 1 ? "质量" : "安全",
            "form.comId": proUserInfo.projectUserInfo.comId,
            "form.projectId": app.globalData.useProjectId,
            "form.projectName": app.globalData.useProjectName,
            "form.infoType": options.type
        });
        this.getDictCache();
        this.getHisInfo(options.type);
        this.getProjectUsers();
    },

    /**
     * 获取字典缓存数据
     */
    getDictCache() {
        // 初始化检查类型
        findDictCache("ssp_proble_type").then(res => {
            if (res.code == 200) {
                let list = [];
                res.data.forEach(item => {
                    list.push({
                        "id": item.dictValue,
                        "text": item.dictLabel
                    });
                });
                this.setData({
                    problemTypeList: list
                });
            }
        });
    },

    /**
     * 查询项目人员数据
     * 获取项目所有人员,在页面组装数据...
     */
    getProjectUsers() {
        findProjectDeptUsers(app.globalData.useProjectId).then(res => {
            if (res.code == 200) {
                this.setData({
                    lordSentList: res.data.lordSentList
                });
            }
        });
    },

    /**
     * 这里查询当前登录人上次提交隐患
     * 自动填充整改人,复检人,抄送人
     * @param {*} type 
     */
    getHisInfo(type) {
        findMyLastProblemmodify(app.globalData.useProjectId, type).then(res => {
            if (res.code == 200 && res.data && res.data.length > 0) {
                this.setData({
                    showHis: true,
                    "form.lordSent": res.data[0].lordSent,
                    "form.lordSentUser": res.data[0].lordSentUser
                })
            }
        });
    },

    // 上传图片
    onImagesArr(e) {
        var index = e.currentTarget.dataset.index
        var data = this.data.inspectInfoData
        data[index].image_upload = e.detail
        this.setData({
            inspectInfoData: data
        })
    },

    //添加整改人
    onAddLordSent(e) {
        if (e.detail.length > 0) {
            this.setData({
                "form.lordSent": e.detail[0].userId,
                "form.lordSentUser": e.detail[0].userName
            })
        }
    },

    // 取消页面
    cancelSaveView() {
        this.returnToPage()
    },

    // 保存
    submitSave() {
        let _form = {
            ...this.data.form
        };
        let {
            inspectInfoData
        } = this.data
        //数据效验
        if (!_form.comId || !_form.projectId) {
            app.toast("数据异常,请刷新页面重试!");
            return false;
        }
        if (!_form.problemType) {
            app.toast("请选择检查类型!");
            return false;
        }
        if (!_form.lordSent || !_form.lordSentUser) {
            app.toast("请选择整改人!");
            return false;
        }

        if (inspectInfoData.length > 0) {
            for (let i = 0; i < inspectInfoData.length; i++) {
                if (inspectInfoData[i].image_upload.length == 0) {
                    app.toast("请上传问题“" + (i + 1) + "”的隐患图片或删除问题项!");
                    return false;
                }
            }
        }
        this.setData({
            loadShow: true
        })
        let fileUrls = [];
        let that = this;
        inspectInfoData.forEach(async (item) => {
            let beforeCheckUrl = [];
            item.image_upload.forEach(async (itFile) => {
                //这里复杂的图片上传,改为同步上传,因为小程序只能上传一张图片
                let obj = await that.syncUploadImage(itFile);
                beforeCheckUrl.push(obj.data.data.url);
                if (beforeCheckUrl.length >= item.image_upload.length) {
                    fileUrls.push(beforeCheckUrl);
                }
                //验证图片上传完毕
                if (fileUrls.length >= inspectInfoData.length) {
                    _form.smarkUrls = fileUrls;
                    addDraft(_form).then(res => {
                        this.setData({
                            loadShow: false
                        });
                        if (res.code == 200) {
                            app.toast("新增数据成功!")
                            setTimeout(() => {
                                wx.redirectTo({
                                    url: `../list/index?type=${this.data.type}`,
                                })
                            }, 200);
                        }
                    });
                }
            });
        })
    },

    /**
     * 这里考虑上传图片异步问题,封装为同步
     */
    syncUploadImage(file) {
        let _baseUrl = config.baseUrl;
        return new Promise((resolve, reject) => {
            wx.uploadFile({
                url: _baseUrl + "/file/upload", // 上传的服务器接口地址
                filePath: file,
                header: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
                    'Authorization': 'Bearer ' + getToken()
                },
                name: "file", //上传的所需字段,后端提供
                formData: {},
                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)
                }
            });
        })
    },

    /**
     * 选择问题类型
     * @param {*} e 
     */
    onSelectProblemType(e) {
        this.setData({
            "form.problemType": e.detail.id,
        })
    },

    returnToPage: function () {
        if (wx.getStorageSync('nav-menu') == "list") {
            wx.redirectTo({
                url: `../list/index?type=${this.data.type}`
            })
        } else {
            wx.redirectTo({
                url: `../list/index?type=${this.data.type}`
            })
        }
    },

    //新增问题
    onNewIssues() {
        var data = this.data.inspectInfoData
        if (data.length == 5) {
            app.toast("一次最多只能提交5个问题!");
            return false;
        }
        data.push({
            image_upload: []
        })
        this.setData({
            inspectInfoData: data
        })
    },

    //删除
    onNewIssuesDelete(e) {
        var index = e.currentTarget.dataset.index
        var data = this.data.inspectInfoData
        data.splice(index, 1)
        this.setData({
            inspectInfoData: data
        })
    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})