/**
 * <p>
 *  directory
 * </p>
 *
 * @author Administrator
 * @since 2021/6/1
 */
// 目录树数据缓存
const dirCache = new Map();
layui.use(['layer', 'listPage', 'globalTree', 'gtable', 'form', 'element', 'dropdown', 'laydate', 'dict'], function () {
    const listPage = layui.listPage,
        form = layui.form,
        element = layui.element,
        laydate = layui.laydate,
        globalTree = layui.globalTree;

    let metaListTable, dirFileTable, tagSelector, tags = [], unchecked_tags = [], conditions = [];

    // 初始化
    initDirectoryTree();


    // 加载并渲染目录树
    function initDirectoryTree() {
        let dirTree = globalTree.init({
            id: 'directoryTree',
            url: `${ctx}/business/directory/tree?busType=${bus_type}`,
            request: {reviewStatus: ReviewStatus.SUBMITTED, allChild: false},
            cache: false,
            // type: 'all',
            initLevel: 1, // 默认展开一级
            scroll: '#tree-toobar-div',
            width: 'fit-content',
            done: treeInitDone,
            onClick: nodeClickEventListener,
            sendSuccess: fetchRequestSendSuccess,
        });

        /**
         * 树组件请求数据接口成功后的回调函数
         * @param res
         */
        function fetchRequestSendSuccess(res) {
            if (res.flag) {
                res.data.forEach(item => {
                    dirCache.set(item.id, item);
                })

                setTimeout(() => {
                    $('.dtree-nav-div.dtree-theme-item').each((index, elem) => {
                        let data = $(elem).data('basic');
                        if (data) {
                            if (typeof data === 'string') {
                                data = JSON.parse(data);
                            }
                            let title = data.metadataComment || data.directoryName || data.fileName + data.fileSuffix;
                            $(elem).attr('title', title)
                        }
                    });
                }, 200)
            }
        }

        /**
         * 树组件初始化完成回调函数
         * @param nodes
         * @param elem
         */
        function treeInitDone(nodes, elem) {
            // 模拟鼠标点击事件展开第一层目录
            elem.find('li:first>div:first>i:first').click();
            elem.find('li:first>div:first').click();
            // 搜索事件监听
            treeSearchEventListener()
        }

        /**
         * 节点点击事件监听
         * @param node
         */
        function nodeClickEventListener(node) {
            let {basicData} = node.param;
            basicData = basicData || {id: DIR_ROOT_ID};
            //设置当前位置
            setCurrentPosition(basicData);
            if ($('#metaQuery').hasClass("layui-this")) {
                // 初始化数据资源表格
                initMetadataTable(basicData.id)
            }
            if ($('#fileQuery').hasClass("layui-this")) {
                //初始化文件搜索表格
                initFileSearchTable(basicData.id);
            }
        }

        element.on('tab(metadataListCardBody)', function (data) {
            if (!dirFileTable) {
                initFileSearchTable(DIR_ROOT_ID);
            }
        });

        /**
         * 设置当前位置
         * @param basicData
         */
        function setCurrentPosition(basicData) {
            let directoryPath =  basicData.directoryPath.replaceAll('/', ' / ');
            $('.current-position label').text(directoryPath);
        }

        /**
         * 树组件搜索事件监听
         */
        function treeSearchEventListener() {
            $('#directoryTreeSearchBox').on('keyup', function () {
                setTimeout(() => {
                    dirTree.fuzzySearch(this.value);
                }, 500)
            })
        }
    }

    /**
     * 加载数据资源列表
     */
    function initMetadataTable(id) {
        metaListTable = listPage.init({
            table: {
                id: 'dirMetadataTable',
                toolbar: '#tableToolBar',
                searchFieldNames: 'metadataName',
                url: `${ctx}/search/metadata/all/page/${id}`,
                height: 'full-110',
                method: 'post',
                defaultToolbar: [{
                    title: '导出' //标题
                    , layEvent: 'export' //事件名，用于 toolbar 事件中使用
                    , icon: 'layui-icon-export' //图标类名
                }],
                request: {pageName: 'page', limitName: 'size'},
                limit: 30,
                cols: [[
                    {field: 'id', title: 'ID', hide: true},
                    {field: 'resourceName', title: '数据名称', width: 300},
                    {field: 'resourceComment', title: '中文注释/描述'},
                    {field: 'directoryPath', title: '资源路径'},
                    {field: 'themeTask', title: '主题任务', hide: true},
                    {
                        field: 'dataSource',
                        title: '数据来源',
                        width: 160,
                        templet: (data) => DICT.getText("data_source", data.dataSource) || data.dataSource || ''
                    },
                    {field: 'taskTime', title: '任务时间', width: 180, align: 'center'},
                    {field: 'modifyTime', title: '注册时间', width: 160, align: 'center', hide: true},
                    {fixed: 'right', title: '操作', toolbar: '#rowToolBar', width: 100, align: 'center'}
                ]],
                done: function (res, _table) {
                    initConditionBlock();
                    if (_table.where) {
                        metaListTable.where = _table.where;
                        if (_table.where.conditions && _table.where.conditions.length > 0) {
                            let formVal = form.val('search-form');
                            formVal = Object.assign(formVal, whereConditionToFormValue(_table.where));
                            form.val('search-form', formVal);
                            // $('div[lay-event="export"]').show();
                        }
                        renderConditionTabByForm(true);
                    }
                }
            },
        });
        metaListTable.addTableRowEvent('export', function (obj) {
            if (id === DIR_ROOT_ID) {
                showErrorMsg('不允许导出根目录数据');
                return false;
            }
            layer.confirm('该导出操作比较耗时，导出时请勿刷新页面', {title: '提示信息'}, function () {
                let params = metaListTable.where;
                let exportLayer = showExportMsgLayer('正在查询需要导出的数据');
                Util.post(`/search/export/query/${id}`, params, false).then(res => {
                    layer.close(exportLayer);
                    if (res.flag) {
                        let exportId = res.data.exportId;
                        exportLayer = showExportMsgLayer('正在打包需要导出的数据');
                        Util.get(`/search/export/package/${exportId}`, {}, false).then(res => {
                            layer.close(exportLayer);
                            if (res.flag) {
                                parent.window.open(`${ctx}/search/export/download/${exportId}`, '_blank')
                            } else {
                                showExportMsgLayer('数据打包失败，' + res.msg);
                            }
                        })
                    } else {
                        showExportMsgLayer('数据查询失败，' + res.msg);
                    }
                })
            });
        })
        // 查看按钮监听
        metaListTable.addTableRowEvent('details', function (obj) {
            if (obj.resourceType === 'file') {
                openMaxLayerWithURL(`${ctx}/sys/file/view?fileId=${obj.id}`)
            } else {
                openMaxLayerWithURL(`${ctx}/search/meta/${obj.id}`)
            }
        })
    }

    function initFileSearchTable(id) {
        dirFileTable = listPage.init({
            table: {
                id: 'dirFileTable',
                toolbar: '#fileTableToolBar',
                searchInput: 'fileSearchKeyInput',
                searchFieldNames: 'search',
                url: `${ctx}/search/full/file?metaId=${id}`,
                height: 'full-110',
                request: {pageName: 'page', limitName: 'size'},
                limit: 30,
                method: 'get',
                cols: [[
                    {field: 'id', title: 'ID', hide: true},
                    {field: 'fileName', title: '文件名称', minWidth: 300, fixed: 'left'},
                    {
                        title: '文件来源',
                        minWidth: 160,
                        templet: data => DICT.getText('data_source', data.source) || data.source || ''
                    },
                    {field: 'taskCode', title: '任务代号', minWidth: 160},
                    {
                        title: '任务性质',
                        minWidth: 160,
                        templet: data => DICT.getText('task_nature', data.taskNature) || data.taskNature || ''
                    },
                    {field: 'troopCode', title: '部队代号', minWidth: 160},
                    {field: 'missileNumber', title: '导弹编号', minWidth: 160},
                    {field: 'equipmentModel', title: '装备型号', minWidth: 160},
                    {
                        title: '目标/靶标类型',
                        minWidth: 160,
                        templet: data => DICT.getText('target_type', data.targetNumber) || data.targetNumber || ''
                    },
                    {field: 'entryStaff', title: '录入人员', minWidth: 160},
                    {field: 'inputDate', title: '收文时间', width: 160, align: 'center'},
                    {field: 'remark', title: '文件描述', width: 300},
                    {field: 'text', title: '文件内容', width: 300},
                    {fixed: 'right', title: '操作', toolbar: '#fileRowToolBar', width: 100, align: 'center'}
                ]],
            },
        });

        // 查看按钮监听
        dirFileTable.addTableRowEvent('details-file', function (obj) {
            openMaxLayerWithURL(`${ctx}/sys/file/view?fileId=${obj.id}`)
        })
    }

    /**
     * 搜索条件模块初始化
     */
    function initConditionBlock() {
        // 监听更多条件按钮点击事件
        $('#condition-btn').click(function () {
            const display = $('#condition-div').css('display');
            if (display == 'none') {
                $('#mengban').show().on('click', function () {
                    $(this).hide();
                    $('#condition-btn').click();
                });
            }
            $('#condition-div').slideToggle(100, 'linear', conditionSlideToggle)
        });

        if (!tagSelector) {
            tagSelector = new MarkerSelector('#mark-selector-input');
        }
        tagSelector.bindBtnEvent()
        tagSelector.onOkBtn(data => {
            tags = data
            setMarkTagInputValue();
        });

        // 监听标签点击事件
        element.on('tab(condition-tab)', function (data) {
            // 点击后移除选中样式
            $('#condition-tab ul li').removeClass('layui-this')
        });

        $('#condition-cancel-btn').on('click', function () {
            $('#condition-div').slideToggle(100, 'linear')
            $('#mengban').hide();
        });

        // 监听条件标签删除事件
        element.on('tabDelete(condition-tab)', function (data) {
            let key = $(this).parent().data('key');
            let formVal = form.val('search-form');
            formVal[key] = '';
            form.val('search-form', formVal);
            let where = metaListTable.where;
            if (where.conditions) {
                metaListTable.where.conditions = where.conditions.filter(item => item.fieldName != key);
            }
            renderConditionTabByForm()
        });

        // 监听重置按钮
        $('#condition-clear-btn').on('click', function () {
            $('#searchKeyInput').val('');
            tags = [];
            unchecked_tags = [];
            conditions = [];
            beginSearch();
        });

        layui.dict.render();

        /**
         * 渲染时间选择组件
         */
        laydate.render({
            elem: '#input-date-begin'
            , type: 'date'
            , range: '至'
        });

        $('#searchKeyInput').on('change', function () {
            let where = metaListTable.where || {};
            let conditions = where.conditions || [];
            let value = $(this).val();
            conditions = conditions.filter(item => item.fieldName !== 'metadataName')
            if (value && value.trim()) {
                conditions.push({fieldName: 'metadataName', fieldValue: value.trim(), logicJudgement: 'like'})
            }
            where.conditions = conditions;
            metaListTable.where = where;
        })
    }

    function setMarkTagInputValue() {
        let temp = [];
        for (let tag of tags) {
            let arr = tag.split('-');
            let text = tag.replace(arr[0] + '-' + arr[1] + '-', '');
            temp.push(text);
        }
        $('#mark-selector-input').val(temp.join(', '));
    }

    /**
     * 条件下拉框显示隐藏的回调
     */
    function conditionSlideToggle() {
        const display = $('#condition-div').css('display');
        // 隐藏时，根据搜索表单的值渲染条件标签，并根据条件检索
        if (display === 'none') {
            renderConditionTabByForm();
        } else {
            setMarkTagInputValue();
        }
    }

    /**
     * 根据条件表单数据渲染条件标签
     */
    function renderConditionTabByForm(isCallback) {
        let formVal = form.val('search-form') || {};
        let htm = '';
        conditions = [];
        for (let key in formVal) {
            if (key == 'searchKeyInput') continue;
            let fieldName = key, fieldValue = formVal[key], logicJudgement;
            // 如果fieldName是条件下拉框，则跳过
            if (fieldName.startsWith('logic-') || fieldName === 'directoryId' || fieldName === 'metadataId') continue;

            let hasText = fieldValue.trim();
            if (hasText) {
                logicJudgement = formVal[`logic-${fieldName}`];
                let title = $(`label.layui-form-label[label-name='${fieldName}']`).text();
                let condition = '';
                switch (logicJudgement) {
                    case 'eq':
                        condition = '等于';
                        break;
                    case 'nq':
                        condition = '不等于';
                        break;
                    case 'gt':
                        condition = '大于';
                        break;
                    case 'lt':
                        condition = '小于';
                        break;
                    case 'like':
                        condition = '包含';
                }

                if (fieldName == 'secretLevel') {
                    hasText = $(`select[name="secretLevel"] option[value="${fieldValue}"]`).text();
                } else if (fieldName == 'dataFrom') {
                    hasText = $(`select[name="dataFrom"] option[value="${fieldValue}"]`).text();
                } else if (fieldName == 'dataType') {
                    hasText = $(`select[name="dataType"] option[value="${fieldValue}"]`).text();
                }
                conditions.push({fieldName, fieldValue, logicJudgement})
                htm += `<li data-key="${fieldName}" style="color:#009688"><label style="color:#333">${title}</label><label style="color:gray;margin-left:5px">${condition}</label>: ${hasText}</li>`
            }
        }

        let temp = [];
        for (let tag of tags) {
            let tag_arr = tag.split('-');
            let tag_type = tag_arr[1], tag_text = tag_arr[2], temp_tags = temp[tag_type];
            if (!temp_tags) {
                temp_tags = []
            }
            temp_tags.push({id: tag_arr[0], text: tag_text});
            temp[tag_type] = temp_tags;
        }

        for (let type in temp) {
            let tag_type = type, tag_items = temp[type], tag_htm = '';
            for (let item of tag_items) {
                let val = item.id + '-' + item.text, checked = 'checked';
                if (unchecked_tags.includes(val)) {
                    checked = '';
                }
                tag_htm += `<input type="checkbox" title="${item.text}" value="${val}" ${checked} lay-skin="primary">`;
            }

            htm += `<li data-key="markTag">${tag_type}：${tag_htm}</li>`;
        }
        $('#condition-tab ul').html(htm);
        element.render('tab');
        $('#condition-tab ul li[data-key="markTag"] i').remove();
        form.render('checkbox');

        $('li[data-key="markTag"] .layui-form-checkbox').on('click', function () {
            let val = $(this).prev().val(), index = unchecked_tags.indexOf(val);
            if (!$(this).hasClass('layui-form-checked')) {
                unchecked_tags.push(val);
            } else if (index > -1) {
                unchecked_tags.splice(index, 1)
            }
            beginSearch();
        })

        // 开始检索
        if (!isCallback) {
            beginSearch();
        }
    }


    function beginSearch() {
        setMarkTagsValue()
        metaListTable.where.conditions = conditions;
        metaListTable.reloadTable({table: metaListTable})
    }

    function setMarkTagsValue() {
        let values = [];
        $(`li[data-key="markTag"] .layui-form-checked`).each(function (index, elem) {
            values.push($(elem).prev().val())
        });
        if (values.length > 0) {
            conditions.push({fieldName: 'markTag', fieldValue: values.join(','), logicJudgement: 'eq'});
        }
    }

    function whereConditionToFormValue(where) {
        let params = {};
        if (where.conditions) {
            where.conditions.forEach(item => {
                params[item.fieldName] = item.fieldValue;
                if (item.logicJudgement) {
                    params[`logic-${item.fieldName}`] = item.logicJudgement;
                }
            })
        }
        return params;
    }

    function showExportMsgLayer(msg) {
        return layer.msg(msg, {
            icon: 16,
            shade: 0.01,
            time: 1000 * 60 * 30,
            closeBtn: 1
        });
    }
})