layui.extend({
    permisConfig: `{/}${ctx}/js/sys/permissions/permisConfig` // {/}的意思即代表采用自有路径，即不跟随 base 路径
})

layui.use(['form', 'layer', 'gtable'], function () {
    let layer = layui.layer,
        gtable = layui.gtable,
        form = layui.form;

    // 用于临时存储查询条件
    let dictTypeTable, dictTable, dictTypes, searchText = '';
    const template_management = `
        <div class="layui-row" style="width: 900px; height: 600px;">
            <div class="layui-col-md12">
                <table class="layui-hide" id="dictTable" lay-filter="dictTypeTable"></table>
            </div>
        </div>`;
    const template_edit = `
        <div class="layui-row">
            <div class="layui-col-md12">
                <form class="layui-form" id="dictTypeEditForm" lay-filter="dictTypeEditForm" style="padding: 15px 15px 0 0">
                    <div class="layui-form-item">
                        <label class="layui-form-label" style="width: 80px; text-align: right; padding-right: 5px;">字典名称：</label>
                        <div class="layui-input-block" style="margin-left: 100px">
                            <input class="layui-input" type="text" name="name" lay-verify="required" autocomplete="off">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label" style="width: 80px; text-align: right; padding-right: 5px;">字典描述：</label>
                        <div class="layui-input-block" style="margin-left: 100px">
                            <input class="layui-input" type="text" name="remark" lay-verify="required" autocomplete="off">
                        </div>
                    </div>
                    <input type="hidden" name="id">
                    <button type="submit" lay-submit id="dictFormSubmitBtn" style="width: 1px; height: 1px;position: absolute;left: -100px;top:-100px">submit</button>
                </form>
            </div>
        </div>`;


    initDictTypeTable();



    /**
     * 数据表格点击事件
     */
    function tableEventCallback(obj) {
        let {data, config} = obj;
        let dictType = config ? config.dictType : '';
        switch (obj.event) {
            case 'query':
                searchText = $('#searchKeyInput').val().trim();
                let queryOps = {page: {current: 1}, where: {name: searchText}}
                let done = Object.assign({}, obj.config).done;
                queryOps.done = (res) => {
                    $('#searchKeyInput').val(searchText);
                    done && done(res);
                }
                dictTypeTable.reload(queryOps);
                break;
            case 'add':
                if (config.id === 'dictTypeTable') {
                    openDictTypeEditLayer();
                } else {
                    openDictEditLayer(dictType);
                }
                break;
            case 'edit':
                if (data.typeId) {
                    openDictEditLayer(dictType, data.id);
                } else {
                    openDictTypeEditLayer(data);
                }
                break;
            case 'delete':
                if (data.typeId) {
                    deleteDictData(data.id);
                } else {
                    deleteDictTypeData(data.id);
                }
                break;
            case 'manage':
                openDictManageLayer(data.id);
        }
    }
    let editLayerWin;
    /**
     * 打开编辑窗口
     * @param dictType 字典项类型
     * @param id 字典项ID
     */
    function openDictEditLayer(dictType, id = '') {
        layer.open({
            id: 'dictEdit',
            type: 2,
            title: '数据字典编辑',
            area: ['550px', '430px'],
            content: ctx + `/sys/dict/edit?type=${dictType}&id=${id}`,
            btn: ['确定', '取消'],
            success: function (layero, index) {
                editLayerWin = window[layero.find('iframe')[0]['name']]
            },
            yes: function (index) {
                editLayerWin && editLayerWin.save().then(ok => {
                    if (ok) {
                        gtable.reload();
                        layer.close(index);
                    }
                });
            },
            end: function () {
            }
        });
    }

    /**
     * 删除字典类型数据
     * @param ids
     */
    function deleteDictTypeData(ids) {
        layer.confirm('是否确定删除该数据？', function () {
            Util.send('/sys/dict/type/delete', {ids}, 'delete').then(res => {
                if (res.flag) {
                    showOkMsg('删除成功');
                    dictTypeTable && dictTypeTable.reload();
                } else {
                    showErrorMsg('删除失败');
                }
            }).catch(() => showErrorMsg())
        });
    }

    /**
     * 打开字典维护窗口
     * @param id
     */
    function openDictManageLayer(id) {
        layer.open({
            type: 1,
            id: 'dictTypeManagement',
            title: '字典项维护',
            content: template_management,
            btn: ['确定'],
            success: () => initDictTable(id),
            yes: (index) => layer.close(index)
        });
    }

    /**
     * 初始化字典数据表
     * @param id
     */
    function initDictTable(id) {
        dictTable = gtable.init({
            id: 'dictTable',
            dictType: id,
            url: `${ctx}/sys/dict/list`,
            where: {typeId: id},
            method: 'post',
            toolbar: '#tableToolBar',
            height: '600px',
            page: false,
            cols: [[
                {field: 'dictName', title: '字典项名称', minWidth: 120},
                {field: 'typeName', title: '所属字典', minWidth: 100},
                {
                    field: 'dictState',
                    title: '字典项状态',
                    width: 100,
                    align: 'center',
                    templet: d => d.dictState ? '启用' : '禁用'
                },
                {field: 'dictValue', title: '字典值', minWidth: 160},
                {fixed: 'right', title: '操作', toolbar: '#rowToolBar', align: 'center', width: 120}
            ]]
        });
    }

    /**
     * 删除字典数据
     * @param ids
     */
    function deleteDictData(ids) {
        layer.confirm('是否确定删除该数据？', function () {
            Util.send('/sys/dict/delete', {ids}, 'delete').then(res => {
                if (res.flag) {
                    showOkMsg('删除成功');
                    dictTable && dictTable.reload();
                } else {
                    showErrorMsg('删除失败');
                }
            }).catch(() => showErrorMsg())
        });
    }

    /**
     * 初始化数据字典列表
     */
    function initDictTypeTable() {
        let options = {
            id: 'dictTypeTable',
            url: ctx + '/sys/dict/type/page',
            toolbar: '#tableToolBar',
            title: '数据字典列表',
            cols: [[
                {field: 'name', title: '字典名称'},
                {field: 'remark', title: '字典描述'},
                {field: 'createTime', title: '创建时间'},
                {fixed: 'right', title: '操作', toolbar: '#rowToolBar', align: 'center', width: 180}
            ]],
            onToolBarTable: tableEventCallback,
            onToolBarRow: tableEventCallback
        };
        dictTypeTable = gtable.init(options);
    }

    let editLayerIndex;

    /**
     * 打开字典类型编辑弹窗
     * @param data 字典类型数据
     */
    function openDictTypeEditLayer(data) {
        layer.open({
            type: 1,
            id: 'dictTypeEdit',
            title: data ? '编辑' : '新增',
            area: ['400px', '230px'],
            content: template_edit,
            btn: ['保存', '取消'],
            success: function (layerObj, index) {
                editLayerIndex = index;
                if (data) {
                    form.val('dictTypeEditForm', data);
                    //$('#dictTypeEditForm input[name="id"]').attr('readonly', true)
                }
                initDictTypeForm();
            },
            yes: function () {
                $('#dictFormSubmitBtn').click();
            }
        })
    }

    /**
     * 关闭编辑窗口
     */
    function closeEditLayer() {
        layer.close(editLayerIndex);
    }

    /**
     * 初始化字典类型Form表单
     */
    function initDictTypeForm() {
        form.on('submit(dictTypeEditForm)', function () {
            let data = form.val('dictTypeEditForm')
            saveDictTypeData(data)
            return false;
        });
    }

    /**
     * 保存数据
     * @param data
     */
    function saveDictTypeData(data) {
        Util.post('/sys/dict/type/save', data).then(res => {
            if (res.flag) {
                showOkMsg('保存成功');
                closeEditLayer();
                dictTypeTable && dictTypeTable.reload();
            } else {
                showErrorMsg('保存失败');
            }
        }).catch(() => showErrorMsg())
    }
});
