import config from '../../../config'
import {
    getToken
} from '../../../utils/auth'
import {
    findInfo,
    findAuditInfos,
    modifyProblemmodify
} from '../../../api/problemmodify'
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        infoData: {},
        loadShow: false,
        auditInfo1: {},
        auditInfo3: {},
        auditInfo4: {},
        form: {},
        imageInfoData: [],
        imageList: [],
        auditImageList: [],
        active: 2,
        flowNodes: [{
            text: '开始'
        }, {
            text: '提交隐患'
        }, {
            text: '隐患整改'
        }, {
            text: '隐患复检'
        }, {
            text: '结束'
        }]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (!getToken()) {
            wx.redirectTo({
                url: '../../login/login',
            })
        }
        this.setData({
            type: options.type,
            typeName: options.type == 1 ? "质量" : "安全",
        });
        this.getInfo(options.id);
        this.getAuditInfos(options.id);
    },

    /**
     * 查详隐患详情
     * @param {*} id 
     */
    getInfo(id) {
        findInfo(id).then(res => {
            if (res.code == 200) {
                let state = this.data.active;
                if (res.data.checkState == "0") {
                    state = 2;
                } else if (res.data.checkState == "1") {
                    state = 3;
                } else if (res.data.checkState == "3") {
                    state = 2;
                }
                this.setData({
                    active: state
                })
                let urls = [];
                if (res.data.smarkUrl) {
                    res.data.smarkUrl.split(',').forEach(item => {
                        urls.push(config.baseImgUrl + item);
                    });
                }
                this.setData({
                    infoData: res.data,
                    imageList: urls,
                    "form.mainId": res.data.id,
                })
            }
        })
    },

    /**
     * 查详隐患流程
     * @param {*} id 
     */
    getAuditInfos(id) {
        findAuditInfos(id).then(res => {
            if (res.code == 200 && res.data.length > 0) {
                res.data.forEach(item => {
                    if (item.processState == "0") {
                        let urls = [];
                        if (item.files.length > 0) {
                            item.files.forEach(_file => {
                                urls.push(config.baseImgUrl + _file.fileUrl);
                            });
                        }
                        this.setData({
                            auditInfo1: item,
                            auditImageList: urls
                        })
                    } else if (item.processState == "1") {
                        this.setData({
                            auditInfo4: item
                        })
                    } else if (item.processState == "2") {
                        this.setData({
                            auditInfo3: item
                        })
                    }
                });
            }
        });
    },

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

    //保存
    onSubmitSave() {
        let _form = {
            ...this.data.form
        };
        let {
            imageInfoData
        } = this.data
        //数据效验
        if (!_form.mainId) {
            app.toast("数据异常,请刷新页面重试!")
            return false;
        }
        if (!_form.opinion) {
            app.toast("请填写整改说明!")
            return false;
        }
        if (imageInfoData.length == 0) {
            app.toast("请上传整改后图片!")
            return false;
        }
        this.setData({
            loadShow: true
        })
        let that = this
        let fileUrls = [];
        imageInfoData.forEach(async (item) => {
            let obj = await that.syncUploadImage(item);
            fileUrls.push(obj.data.data.url);
            //验证图片上传完毕
            if (fileUrls.length == imageInfoData.length) {
                _form.processState = "0";
                _form.images = fileUrls.toString();
                modifyProblemmodify(_form).then(res => {
                    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)
                }
            });
        })
    },

    //展示图片
    showImg: function (e) {
        let img = e.target.dataset.set;
        wx.previewImage({
            urls: img.split(','),
            current: 0
        })
    },

    returnToPage: function () {
        wx.redirectTo({
            url: `../list/index?type=${this.data.type}`
        })
    },

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

    },

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

    },

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

    },

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

    },

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

    },

    // 整改说明
    onInputOpinion(e) {
        this.setData({
            "form.opinion": e.detail.value
        })
    },

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

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

    },

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

    }
})