layui.use(['layer', 'form', 'gtable', 'globalTree'], function () {
    const layer = layui.layer;
    let treeObj, _node = null, _div = null, _dataLabel = {}, tableObj, searchText = '', tableWhere = {parentId: 0};
    initTree();
    initTable();
    listenAddRootSubTypeButton();

    /**
     * 初始化分类树组件
     */
    function initTree() {
        treeObj = layui.globalTree.init({
            id: 'labelTree',
            url: `${ctx}/data-label/manager/api/tree/children`,
            all: false,
            initLevel: 3,
            scroll: '#tree-toobar-div',
            toolbar: true,
            toolbarShow: [],
            done: function (nodes, elem) {
            },
            onClick: function (node) {
                treeNodeClickCallback(node);
            },
            toolbarFun: {
                loadToolbarBefore: function (buttons, param, $div) {
                    treeToolbarShowBeforeCallback(buttons, param, $div);
                    return buttons;
                }
            },
            toolbarExt: [
                {
                    toolbarId: "addSubType",
                    icon: "dtree-icon-wenjianjiazhankai",
                    title: "添加子类",
                    handler: function (node, $div) {
                        let data = parseNodeData(node);
                        editLabel({isLabel: false, parentId: data.id}, (data) => {
                            treeObj.partialRefreshAdd($div);
                            tableObj.reload();
                        });
                    }
                },
                {
                    toolbarId: "addLabel",
                    icon: "dtree-icon-sort",
                    title: "添加标签",
                    handler: function (node, $div) {
                        let data = parseNodeData(node);
                        editLabel({isLabel: true, parentId: data.id}, () => {
                            treeObj.partialRefreshAdd($div);
                            tableObj.reload();
                        });
                    }
                },
                {
                    toolbarId: "editLabel",
                    icon: "dtree-icon-bianji",
                    title: "修改",
                    handler: function (node, $div) {
                        editLabel(parseNodeData(node), (result) => {
                            treeObj.partialRefreshEdit($div, result);
                            $('#currentPosition').text(result.titlePathWithSelf);
                            tableObj.reload();
                        });
                    }
                },
                {
                    toolbarId: "deleteLabel",
                    icon: "dtree-icon-delete1",
                    title: "删除",
                    handler: function (node, $div) {
                        deleteLabel(parseNodeData(node).id).then(() => {
                            treeObj.partialRefreshDel($div);
                            tableObj.reload();
                        });
                    }
                },
                {
                    toolbarId: "addToForm",
                    icon: "dtree-icon-sort",
                    title: "配置到表单",
                    handler: function (node, $div) {
                        inputFormFiledTitle(parseNodeData(node));
                    }
                }
            ]
        });
    }

    /**
     * 初始化数据表格
     */
    function initTable() {
        tableObj = layui.gtable.init({
            id: 'labelTable',
            url: `${ctx}/data-label/manager/page`,
            height: 'full-105',
            autoSort: false,
            where: tableWhere,
            limit: 20,
            toolbar: '#tableToolBar',
            cols: [[
                {type: 'checkbox'},
                {field: 'title', title: '名称', templet: labelTitleFormatter},
                {field: 'description', title: '备注'},
                {field: 'createUserName', title: '创建人', width: 120, align: 'center'},
                {field: 'createTime', title: '创建时间', width: 160, align: 'center'},
                {fixed: 'right', title: '操作', toolbar: '#rowToolBar', width: 90, align: 'center'}
            ]],
            done: function () {
                $('#searchKeyInput').val(searchText);
            },
            onToolBarTable: tableToolEventListener,
            onToolBarRow: tableToolEventListener
        });
    }

    /**
     * 数据表格工具按钮的统一事件监听
     * @param event
     * @param data
     * @returns {boolean}
     */
    function tableToolEventListener({event, data}) {
        switch (event) {
            case 'query':
                searchText = $('#searchKeyInput').val();
                tableWhere.title = searchText;
                tableWhere.description = searchText;
                tableObj.reload();
                break;
            case 'addSubType':
                editLabel({isLabel: false, parentId: _dataLabel.id ? _dataLabel.id : 0}, (data) => {
                    if (_div) {
                        treeObj.partialRefreshAdd(_div);
                    } else {
                        treeObj.reload();
                    }
                    tableObj.reload();
                });
                break;
            case 'addLabel':
                if (!_dataLabel.id) {
                    showErrorMsg('请选择一个分类');
                    return false;
                }
                editLabel({isLabel: true, parentId: _dataLabel.id}, () => {
                    tableObj.reload();
                });
                break;
            case 'edit':
                editLabel(data, (result) => {
                    if (!data.isLabel) {
                        let div = getTreeNodeDivByLabelId(data.id)
                        treeObj.partialRefreshEdit(div, result);
                    }
                    tableObj.reload();
                });
                break;
            case 'delete':
                let ids = '', idArr = [];
                if (data) {
                    ids = data.id;
                } else {
                    for (let _data of tableObj.getCheckStatus().data) {
                        idArr.push(_data.id);
                    }
                    ids = idArr.join(',');
                }
                if (!ids) {
                    showWarningMsg('请至少选择一条数据');
                    return false;
                }
                deleteLabel(ids).then(() => {
                    if (!data) {
                        for (let id of idArr) {
                            let div = getTreeNodeDivByLabelId(id);
                            treeObj.partialRefreshDel(div);
                        }
                    }
                    tableObj.reload();
                });
                break;
            case 'setting':
                openFormLabelConfigLayer();
                break;
            default:
        }
    }

    /**
     * 根据类型渲染表格数据的图标
     * @param data
     * @returns {string}
     */
    function labelTitleFormatter(data) {
        if (data.isLabel) {
            return `<i class="layui-icon layui-icon-note" style="margin: 4px"></i>${data.title}`;
        } else {
            return `<i class="dtreefont  dtree-icon-wenjianjiazhankai" style="margin: 4px"></i>${data.title}`;
        }
    }

    /**
     * 树组件node节点单击事件的回调
     */
    function treeNodeClickCallback(node) {
        _node = node;
        _dataLabel = parseNodeData(node);
        _div = getTreeNodeDivByLabelId(_dataLabel.id);
        $('#currentPosition').text(_dataLabel.titlePathWithSelf);
        tableWhere.parentId = _dataLabel.id;
        tableObj.reload();
    }

    /**
     * 树组件右键菜单渲染之前的回调
     */
    function treeToolbarShowBeforeCallback() {

    }

    /**
     * 监听添加大类按钮
     */
    function listenAddRootSubTypeButton() {
        $('#addRootSubType').on('click', function () {
            editLabel({isLabel: false, parentId: 0}, function () {
                pageReset()
            })
        })
    }

    /**
     * 从tree node节点解析标签数据
     * @param node
     * @returns {{}}
     */
    function parseNodeData(node) {
        return node.basicData ? node.basicData : node.param ? node.param.basicData : {};
    }

    /**
     * 根据数据的id获取分类树节点的DIV
     * @param labelId
     * @returns {jQuery|HTMLElement|*}
     */
    function getTreeNodeDivByLabelId(labelId) {
        return $(`div.dtree-nav-div[data-id="${labelId}"][dtree-id="labelTree"]`);
    }

    /**
     * 页面重置
     */
    function pageReset() {
        _node = {};
        _div = {};
        _dataLabel = {};
        searchText = '';
        tableWhere = {parentId: 0};
        $('#currentPosition').text('/');
        initTree();
        initTable();
    }

    /**
     * 编辑标签，data.id为空则为新增
     * @param data
     * @param callback
     */
    function editLabel(data, callback) {
        let isEdit = !!data.id;
        let titleName = data.isLabel ? '置标标签' : '置标分类'
        layer.open({
            type: 1,
            title: (isEdit ? '修改' : '添加') + titleName,
            btn: ['保存', '取消'],
            content: `<div class="layui-form" id="labelEditForm" lay-filter="labelEditForm" style="width: 500px; border-bottom: 1px solid #f2f2f2;">
                        <div class="layui-form-item" style="margin-bottom: 0">
                            <div class="layui-inline" style="width: calc(100% - 30px); margin:15px 15px 0 15px">
                                <input type="hidden" name="id" value="${data.id || ''}">
                                <input type="hidden" name="parentId" value="${data.parentId}" />
                                <input type="hidden" name="isLabel" value="${data.isLabel}" />
                                <input type="hidden" name="idPath" value="${data.idPath || ''}">
                                <input type="hidden" name="titlePath" value="${data.titlePath || ''}">
                                <input type="hidden" name="level" value="${data.level || ''}">
                                <label style="color: #555;">名称：</label>
                                <input class="layui-input" type="text" name="title" value="${data.title || ''}" maxlength="50" placeholder="请输入${titleName}名称" lay-verify="required">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline" style="width: calc(100% - 30px); margin:15px 15px 0 15px">
                                <label style="color: #555;">顺序：</label>
                                <input class="layui-input" name="sort" value="${data.sort || '0'}" lay-verify="number" autocomplete="false" maxlength="230" placeholder="请输入加载顺序" />
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline" style="width: calc(100% - 30px); margin:15px 15px 0 15px">
                                <label style="color: #555;">备注：</label>
                                <textarea class="layui-textarea" name="description" maxlength="230" placeholder="请输入描述信息">${data.description || ''}</textarea>
                            </div>
                        </div>
                        <a lay-submit lay-filter="labelEditForm" id="labelEditFormSubmit" style=""></a>
                    </div>`,
            success: function (layerObj, index) {
                layui.form.render();
                layui.form.on('submit(labelEditForm)', function ({elem, field}) {
                    saveLabel(field).then(data => {
                        if (data) {
                            layer.close(index)
                            callback && callback(data);
                        }
                    });
                    return false;
                });
                // 监听回车事件
                let inputElem = $('#labelEditForm input[name="title"]');
                inputElem.on('focus', function () {
                    listenEnterKey(this).then(() => $('#labelEditFormSubmit').click())
                })
                inputElem.focus();

            },
            yes: function (index) {
                $('#labelEditFormSubmit').click();
            }
        })
    }

    /**
     * 将置标分类配置到表单
     * @param label
     */
    function inputFormFiledTitle(label) {
        let {id, title} = label
        layer.open({
            type: 1,
            title: '设置字段标题',
            btn: ['保存', '取消'],
            content: `<div class="layui-form" id="formLabelConfigForm" lay-filter="formLabelConfigForm" style="width: 500px; border-bottom: 1px solid #f2f2f2;">
                        <div class="layui-form-item" style="margin-bottom: 0">
                            <div class="layui-inline" style="width: calc(100% - 30px); margin:15px 15px 0 15px">
                                <input class="layui-input" type="text" name="fieldTitle" value="${title}" maxlength="20"
                                 placeholder="请输入字段标题" lay-verify="required">
                            </div>
                        </div>
                        <p style="margin: 5px 15px 15px; color: #ff5722;">* 请根据业务需要输入显示到表单中的字段标题</p>
                        <a lay-submit lay-filter="formLabelConfigForm" id="formLabelConfigFormSubmit"></a>
                    </div>`,
            success: function (layerObj, index) {
                layui.form.render();
                layui.form.on('submit(formLabelConfigForm)', function ({elem, field}) {
                    saveFormConfig({labelId: id, fieldTitle: field.fieldTitle}).then(r => {
                        layer.close(index);
                    });
                    return false;
                });
                // 监听回车事件
                let inputElem = $('#formLabelConfigForm input[name="fieldTitle"]');
                inputElem.on('focus', function () {
                    listenEnterKey(this).then(() => $('#formLabelConfigFormSubmit').click())
                })
                inputElem.focus();
                inputElem[0].setSelectionRange(0, inputElem.val().length)

            },
            yes: function (index) {
                $('#formLabelConfigFormSubmit').click();
            }
        })
    }

    let formLabelTable;

    function openFormLabelConfigLayer() {
        let left = window.innerWidth / 2 - 650;
        let top = window.innerHeight / 2 - 380;
        layer.open({
            type: 1,
            title: '表单配置',
            offset: [top + 'px', left + 'px'],
            //btn: ['保存', '取消'],
            content: `<div class="layui-row" style="width: 1300px">
                        <div class="layui-col-md12" style="width: 100%; padding: 0 10px">
                            <table class="layui-hide" id="formLabelConfigTable" lay-filter="formLabelConfigTable"></table>
                        </div>
                    </div>`,
            success: function (layerObj, index) {
                formLabelTable = layui.gtable.init({
                    id: 'formLabelConfigTable',
                    url: `${ctx}/data-label/manager/api/form-config/list`,
                    method: 'get',
                    height: 650,
                    autoSort: false,
                    page: false,
                    toolbar: false,
                    cols: [[
                        {field: 'fieldTitle', title: '字段标题', width: 160},
                        {
                            field: 'labelTitle', title: '标签分类', templet: data => {
                                data.title = data.labelTitle;
                                return labelTitleFormatter(data);
                            }
                        },
                        {field: 'labelTitlePath', title: '上级分类'},
                        {field: 'fieldSort', title: '字段顺序', width: 90},
                        {field: 'createUserName', title: '添加人员', width: 120, align: 'center'},
                        {field: 'createTime', title: '添加时间', width: 160, align: 'center'},
                        {fixed: 'right', title: '操作', toolbar: '#rowToolBar', width: 90, align: 'center'}
                    ]],
                    done: function () {

                    },
                    onToolBarRow: function ({event, data}) {
                        if (event === 'edit') {
                            openFormConfigEditLayer(data)
                        } else if (event === 'delete') {
                            deleteFormConfig(data.id);
                        }
                    },
                });
            },
        })
    }

    function openFormConfigEditLayer(data) {
        layer.open({
            type: 1,
            title: '修改配置',
            btn: ['保存', '取消'],
            content: `<div class="layui-form" id="labelEditForm" lay-filter="labelEditForm" style="width: 500px; border-bottom: 1px solid #f2f2f2;">
                        <div class="layui-form-item" style="margin-bottom: 0">
                            <div class="layui-inline" style="width: calc(100% - 30px); margin:15px 15px 0 15px">
                                <input type="hidden" name="id" value="${data.id || ''}">
                                <label style="color: #555;">字段标题：</label>
                                <input class="layui-input" type="text" name="fieldTitle" value="${data.fieldTitle || ''}" maxlength="50" placeholder="请输入字段标题" lay-verify="required">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline" style="width: calc(100% - 30px); margin:15px 15px 0 15px">
                                <label style="color: #555;">字段顺序：</label>
                                <input class="layui-input" type="text" name="fieldSort" value="${data.fieldSort || 0}" maxlength="2" placeholder="设置字段显示顺序" lay-verify="required|number">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline" style="width: calc(100% - 30px); margin:0 15px 0 15px">
                                <label style="color: #555;">标签分类：<span style="color:black">${data.labelTitle || ''}</span></label><br>
                                <label style="color: #555;">上级分类：<span style="color:black">${data.labelTitlePath || '/'}</span></label>
                            </div>
                        </div>
                        <a lay-submit lay-filter="labelEditForm" id="labelEditFormSubmit" style=""></a>
                    </div>`,
            success: function (layerObj, index) {
                layui.form.render();
                layui.form.on('submit(labelEditForm)', function ({elem, field}) {
                    saveFormConfig(field).then(() => {
                        layer.close(index);
                        formLabelTable.reload();
                    });
                    return false;
                });
                // 监听回车事件
                let inputElem = $('#labelEditForm input[name="title"]');
                inputElem.on('focus', function () {
                    listenEnterKey(this).then(() => $('#labelEditFormSubmit').click())
                })
                inputElem.focus();

            },
            yes: function (index) {
                $('#labelEditFormSubmit').click();
            }
        })
    }

    /**
     * 保存标签
     * @param field
     * @returns {Promise<void>}
     */
    function saveLabel(field) {
        return new Promise((resolve, reject) => {
            Util.post(`/data-label/manager/save`, field, true).then(res => {
                if (res.flag) {
                    showOkMsg('保存成功')
                    resolve && resolve(res.data);
                } else {
                    showErrorMsg(res.msg);
                    reject && reject()
                }
            }).catch(err => {
                showErrorMsg('服务器异常，请联系系统管理员');
                console.error(err);
                reject && reject()
            });
        })
    }

    /**
     * 删除标签
     * @param dataIds
     */
    function deleteLabel(dataIds) {
        return new Promise((resolve, reject) => {
            showConfirmMsg('是否确定删除该数据？').then(() => {
                Util.post(`/data-label/manager/api/delete`, {ids: dataIds}).then(res => {
                    if (res.flag) {
                        showOkMsg('删除成功');
                        resolve && resolve();
                    } else {
                        showErrorMsg(res.msg);
                        reject && reject();
                    }
                }).catch(err => {
                    showErrorMsg('服务器异常，请联系系统管理员');
                    console.error(err);
                    reject && reject();
                })
            })
        });
    }

    function saveFormConfig(data) {
        return new Promise((resolve, reject) => {
            Util.post(`/data-label/manager/api/form-config/save`, data).then(res => {
                if (res.flag) {
                    showOkMsg('保存成功');
                    resolve && resolve();
                } else {
                    showErrorMsg(res.msg);
                    reject && reject();
                }
            }).catch(err => {
                showErrorMsg('服务器异常，请联系系统管理员');
                console.error(err);
                reject && reject();
            })
        });
    }

    function deleteFormConfig(id) {
        showConfirmMsg('是否确定删除该配置？').then(() => {
            Util.send(`/data-label/manager/api/form-config/delete/${id}`, {}, 'delete').then(res => {
                if (res.flag) {
                    showOkMsg('删除成功');
                    formLabelTable.reload();
                } else {
                    showErrorMsg(res.msg);
                }
            }).catch(err => {
                showErrorMsg('服务器异常，请联系系统管理员');
                console.error(err);
            })
        })
    }
});
