import {
    readNotes,
    readDeployNotes,
    startProcessInstance
} from '../../../api/flowable'
import {
    findMyDeptList,
    findAllByCategory
} from '../../../api/publics'
import config from '../../../config'
import {
    getToken
} from '../../../utils/auth'
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        maxDate: new Date(2088, 1, 1).getTime(),
        options: {},
        initData: {},
        deptList: [],
        dataList: [],
        useDeptId: "",
        useTime: "",
        applyReason: "",
        limit: 9,
        detailDataList: [],
        filesData: [],
        fileType: ["png", "jpg", "jpeg"],
        flowNodeList: [],
        flowNodes: [],
        stepList: [],
        active: "",
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            options: options,
            initData: {
                id: app.globalData.useProjectId,
                text: app.globalData.useProjectName
            }
        })
        this.initDeptList();
        this.findMyDeptAssetsList();
        this.findFlowNodes();
        this.newApplyDetail();
    },

    /**
     * 栏目触发事件
     */
    onClickNav(e) {
        var index = e.currentTarget.dataset.index
        let list = this.data.detailDataList;
        list[index].activeId = null;
        list[index].mainActiveIndex = e.detail.index;
        this.setData({
            detailDataList: list
        })
        console.log(e.detail.index, this.data.dataList);
    },

    /**
     * 选项触发事件
     */
    onClickItem(e) {
        var index = e.currentTarget.dataset.index
        let list = this.data.detailDataList;
        list[index].detailId = e.detail.id;
        list[index].detailName = e.detail.text;
        list[index].showDetailsName = e.detail.detailName;
        if (e.detail.units) {
            let itemList = [];
            e.detail.units.split(',').forEach((item, idx) => {
                if (idx == 0) {
                    list[index].useUnitIndex = idx;
                    list[index].useUnit = item;
                }
                itemList.push({
                    id: idx,
                    text: item
                });
            });
            list[index].assetsUnits = itemList;
        }
        list[index].activeId = e.detail.id;
        list[index].showDetailsPopup = false;
        this.setData({
            detailDataList: list
        })
    },

    /**
     * 初始化部门列表
     */
    initDeptList() {
        findMyDeptList().then(res => {
            let list = [];
            res.data.forEach(item => {
                list.push({
                    "id": item.deptId,
                    "text": item.deptName
                });
            });
            this.setData({
                deptList: list,
                useDeptId: app.globalData.userData?.deptId,
            })
        });
    },

    //查询工作流节点
    findFlowNodes() {
        //readNotes
        readDeployNotes(this.data.options.deploymentId).then(res => {
            if (res.code == 200) {
                let list = [{
                    text: '开始'
                }];
                res.data.forEach(item => {
                    list.push({
                        text: item.name,
                        desc: ''
                    });
                });
                list.push({
                    text: '结束'
                });
                this.setData({
                    stepList: list
                })
            }
        });
    },

    //新增问题
    newApplyDetail() {
        var data = this.data.detailDataList
        data.push({
            detailId: '',
            detailName: '',
            showDetailsName: '',
            showDetailsPopup: false,
            mainActiveIndex: 0,
            activeId: [],
            useUnit: "",
            useUnitIndex: "",
            assetsUnits: [],
            applyNumber: "",
            assetsVersion: "",
            useReason: ""
        })
        this.setData({
            detailDataList: data
        })
    },

    /**
     * 删除申请详情
     * @param {*} e 
     */
    delApplyDetail(e) {
        var index = e.currentTarget.dataset.index
        var data = this.data.detailDataList
        data.splice(index, 1);
        this.setData({
            detailDataList: data
        })
    },

    //保存
    onSave() {
        let {
            options,
            initData,
            useDeptId,
            useTime,
            applyReason,
            detailDataList,
            filesData
        } = this.data;
        //数据效验
        if (!initData.id || !options.procDefId || !options.category || !options.deploymentId) {
            app.toast("数据异常，请刷新页面重试!")
            return false;
        }
        if (useDeptId == "") {
            app.toast("请选择使用单位!")
            return false;
        }
        if (useTime == "") {
            app.toast("请选择使用时间!")
            return false;
        }
        if (applyReason == "") {
            app.toast("请填写申请原因!")
            return false;
        }
        if (detailDataList.length > 0) {
            for (let i = 0; i < detailDataList.length; i++) {
                if (!detailDataList[i].detailId || !detailDataList[i].detailName || detailDataList[i].activeId.length == 0) {
                    app.toast("请选择申请明细!")
                    return false;
                }
                if (!detailDataList[i].applyNumber) {
                    app.toast("请填写申请数量!")
                    return false;
                }
                if (!detailDataList[i].useUnit) {
                    app.toast("请选择单位名称!")
                    return false;
                }
            }
        } else {
            app.toast("请添加申请明细!")
        }
        if (filesData.length > 0) {
            for (let i = 0; i < filesData.length; i++) {
                let _fileType = filesData[0].split('.');
                _fileType = _fileType[_fileType.length - 1].toLowerCase();
                if (this.data.fileType.indexOf(_fileType) == -1) {
                    app.toast("申请附件不支持 [ " + _fileType + " ] 格式！请检查第" + (i + 1) + "个附件")
                    return false;
                }
            }
        }
        let that = this;
        wx.showModal({
            title: '提示',
            content: '是否确定提交流程申请？',
            success: function (sm) {
                if (sm.confirm) {
                    that.submit()
                } else if (sm.cancel) {
                    console.log('用户点击取消');
                }
            }
        })
    },

    /**
     * 表单确认提交
     */
    submit() {
        let {
            filesData,
        } = this.data;
        let fileUrls = [];
        if (filesData.length > 0) {
            filesData.forEach(async (item) => {
                //这里复杂的图片上传，改为同步上传，因为小程序只能上传一张图片
                let ajaxResult = await this.syncUploadImage(item);
                fileUrls.push(ajaxResult.data.fileName);
                //验证图片上传完毕
                if (fileUrls.length == filesData.length) {
                    this.sbm(fileUrls.toString());
                }
            })
        } else {
            this.sbm("");
        }

    },

    sbm(fileUrls) {
        let {
            options,
            initData,
            useDeptId,
            useTime,
            applyReason,
            detailDataList,
            dataList
        } = this.data;
        let applyDetailList = [];
        detailDataList.forEach(detail => {
            applyDetailList.push({
                superTypeKey: options.category,
                typeId: dataList[detail.mainActiveIndex].id,
                typeName: dataList[detail.mainActiveIndex].name,
                assetsId: detail.detailId,
                assetsName: detail.detailName,
                number: detail.applyNumber,
                assetsUnit: detail.useUnit,
                assetsVersion: detail.assetsVersion,
                useReason: detail.useReason
            });
        });
        let params = {
            procDefId: options.procDefId,
            proProjectApply: {
                deptId: useDeptId,
                projId: initData.id,
                projName: initData.text,
                applyType: options.category,
                applyStatus: 1,
                useTime,
                applyReason,
                applyFiles: fileUrls,
                proProjectApplyDetailList: applyDetailList
            }
        }
        startProcessInstance(params).then(res => {
            if (res.code == '200') {
                app.toast("提交流程申请成功！", 'success');
                //跳转页面
                wx.redirectTo({
                    url: '../../index/index',
                })
            }
        });
    },

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

    //申请说明输入
    applyReasonblur: function (options) {
        this.data.applyReason = options.detail.value;
    },

    //申请附件上传
    fileUpload(options) {
        let files = options.detail;
        this.setData({
            filesData: files
        });
    },

    //使用单位 
    onSelectDept(e) {
        this.setData({
            useDeptId: e.detail.id
        })
    },

    //使用时间
    onInputTime(e) {
        this.setData({
            useTime: e.detail
        })
    },

    //查询部门资产列表信息
    findMyDeptAssetsList() {
        findAllByCategory(this.data.options.category).then(res => {
            if (res.code == '200') {
                let list = [];
                res.data.forEach(item => {
                    let children = [];
                    item.childrenAssetsTypeList.forEach(child => {
                        children.push({
                            id: child.id,
                            text: child.name,
                            units: child.unit,
                            detailName: item.name + ' > ' + child.name
                        });
                    })
                    list.push({
                        id: item.id,
                        text: item.name,
                        children: children
                    });
                });
                this.setData({
                    dataList: list
                })
            }
        });
    },

    //输入申请数量
    onInputNumber(e) {
        var index = e.currentTarget.dataset.index
        let list = this.data.detailDataList;
        let value = e.detail.value;
        list[index].applyNumber = value;
        this.setData({
            detailDataList: list
        })
    },

    //选择资产单位
    onSelectUnit(e) {
        var index = e.currentTarget.dataset.index
        let list = this.data.detailDataList;
        list[index].useUnit = e.detail.text;
        list[index].useUnitIndex = e.detail.id;
        this.setData({
            detailDataList: list
        })
    },

    //输入规格型号
    onInputVersion(e) {
        var index = e.currentTarget.dataset.index
        let list = this.data.detailDataList;
        list[index].assetsVersion = e.detail.value;
        this.setData({
            detailDataList: list
        })
    },

    //输入使用说明
    onInputUseReason(e) {
        var index = e.currentTarget.dataset.index
        let list = this.data.detailDataList;
        list[index].useReason = e.detail.value;
        this.setData({
            detailDataList: list
        })
    },

    //关闭申请明细选择
    onShowPopup(e) {
        var index = e.currentTarget.dataset.index
        let list = this.data.detailDataList;
        list[index].showDetailsPopup = true;
        this.setData({
            detailDataList: list
        })
    },

    //关闭申请明细选择
    onClosePopup(e) {
        var index = e.currentTarget.dataset.index
        let list = this.data.detailDataList;
        list[index].showDetailsPopup = false;
        this.setData({
            detailDataList: list
        })
    },

    /**
     * 切换临建项目
     * @param {*} e 
     */
    onProjectSelect: function (e) {
        let projectId = e.detail.id;
        let projectName = e.detail.text;
        app.globalData.useProjectId = projectId;
        app.globalData.useProjectName = projectName;
        this.setData({
            initData: {
                id: app.globalData.useProjectId,
                text: app.globalData.useProjectName
            }
        })
    },

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

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})