/**
 * <p>
 *  修改：在数据管控系统中目录审核页面改为按目录结构显示
 *  xiongcl 20210412
 * </p>
 *
 * @author Administrator
 * @since 2021/6/1
 */
// 目录树数据缓存
const dirCache = new Map();

function startRender() {
    layui.use(['ReviewComponent','form'], function () {
        const ReviewComponent = layui.ReviewComponent;
        // 目录树
        let dirTree, metaListTable, tempNode;
        let reviewForm = layui.form;
        /**
         * 加载数据资源列表
         */
        const loadMetadataList = function (directory) {
            const {basicData} = directory;
            if (!basicData) return;
            let dirId = basicData.id, uploadPermis = true, viewPermis = true, removePermis = true,
                permis = {uploadPermis, viewPermis, removePermis};
            if (!WritePermisDirIds.includes(basicData.id) || dirId == DIR_ROOT_ID) {
                permis.uploadPermis = false;
                permis.removePermis = false;
            }
            if (!ReadPermisDirIds.includes(basicData.id)) {
                permis.viewPermis = false;
                dirId = DIR_ROOT_ID
            }
            let reviewStatus = 'PASS';
            metaListTable = listPage.init({
                table: {
                    permis: permis,
                    id: 'dirMetadataTable',
                    //reviewStatusC: directory.basicData.reviewStatus,
                    toolbar: '#tableToolBar',
                    searchFieldNames: 'resourceName',
                    where: {reviewStatus: reviewStatus},
                    url: `${ctx}/business/metadata/list/directory?directoryId=${dirId}&allChild=true`,
                    height: 'full-110',
                    method: 'get',
                    text: {none: permis.viewPermis ? '没有数据' : '没有权限'},
                    parseData: function (res) { //res 即为原始返回的数据
                        let data = res.data || {};
                        data.records = data.records.map(item => {
                            item.permis = permis
                            return item;
                        });
                        return {
                            "flag": res.flag, //解析接口状态
                            "msg": res.msg, //解析提示文本
                            "records": data.records || res.records || data, //解析数据长度
                            "total": data.total || data.length //解析数据列表
                        };
                    },
                    cols: [[
                        {type: 'checkbox', fixed: 'left'},
                        {field: 'id', title: 'ID', hide: true},
                        {field: 'resourceName', title: '数据名称', width: 300},
                        {field: 'directoryPath', title: '所属目录'},
                        {field: 'resourceComment', 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: 160, align: 'center'},
                        {
                            fixed: 'right',
                            title: '操作',
                            toolbar: `#rowToolBar`,
                            width: 100,
                            align: 'center'
                        }
                    ]],
                    done: function (res) {
                        console.log(reviewStatus)
                        reviewForm.val('tableToolForm', {reviewStatus: reviewStatus})
                        reviewForm.render('radio', 'tableToolForm');
                    }
                },
            });

            // 查看按钮监听
            metaListTable.addTableRowEvent('details', function (obj) {
                if (obj.resourceType === 'file') {
                    openMaxLayerWithURL(`${ctx}/sys/file/view?fileId=${obj.id}`)
                } else {
                    openMaxLayerWithURL(`${ctx}/business/metadata/details/${obj.id}`)
                }
            })
            //驳回
            metaListTable.addTableRowEvent('batchReview', function (obj) {
                var table = layui.table, checkStatus = table.checkStatus('dirMetadataTable'),
                    datas = checkStatus.data || [];
                console.log(datas);
                if(datas.length<=0){
                    showErrorMsg("请至少选择一条数据！");
                    return false;
                }
                layer.confirm('是否确定驳回该数据？', {}, function (index) {
                    layer.close(index);
                    reviewData();
                })
                function reviewData() {
                    const ids = datas.map(data => data.directoryId);
                    let param = {
                        ids: ids.join(','),
                        status: ReviewStatus.REJECTED,
                        opinion: '',
                        sendNotice: true,
                    };
                    $.post(`${ctx}/business/review/directory/file/change`, param, function (res) {
                        if (res.flag) {
                            showOkMsg('驳回成功');
                            refreshPermis().then(() => {
                                metaListTable.reloadTable();
                            })
                        } else {
                            layer.msg('驳回失败' + res.msg);
                        }
                    });
                }
            })

            reviewForm.on('radio(statusRadio)', function (data) {
                reviewStatus = data.value;
                let options = {
                    table: {
                        where: {reviewStatus}
                    }
                }
                metaListTable.reloadTable(options)
            })

        }

        // 加载并渲染目录树
        let currentNode, currentParentNode;
        let treeChildrenUrl = `${ctx}/business/directory/tree?busType=` + bus_type
        let treeOps = {
            id: 'directoryTree',
            url: treeChildrenUrl,
            cache: false,
            // type: 'all',
            initLevel: 1, // 默认展开一级
            scroll: '#tree-toobar-div',
            width: 'fit-content',
            toolbar: true,
            toolbarShow: [], //置空默认菜单项
            sendSuccess: function (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)
                }
            },
            done: function (nodes, elem) {
                // 模拟鼠标点击事件展开第一层目录
                elem.find('li:first>div:first>i:first').click();
                $('#directoryTree cite span').on('click', function (event) {
                    event.stopPropagation();
                    const target = event.target;
                    const id = $(target).data('id');
                    const status = $(target).data('status')
                    if (status == ReviewStatus.FAIL || status == ReviewStatus.REJECTED) {
                        showLoading()
                        $.get(`${ctx}/business/review/get/entity?entityId=${id}`, {}, function (res) {
                            closeLoading()
                            if (res.flag) {
                                const reviewData = res.data;
                                const content = `
                                    <div class="tips-box">
                                        <div style="height: 32px;line-height: 32px;color: #dbdbdb;">审核人：${reviewData.reviewUser}</div>
                                        <div style="min-width: 200px;max-width: 500px;min-height: 30px;max-height: 300px; color: gray">原因：${reviewData.reviewOpinion}</div>
                                    </div>`;
                                layer.tips(content, `#${id}`, {
                                    tips: [2],
                                    closeBtn: 1,
                                    shade: 0.3,
                                    shadeClose: true,
                                    time: 60000
                                });
                            } else {
                                showErrorMsg(res.msg);
                            }
                        })
                    }
                })
            },
            onClick: function (node) {
                tempNode = node;
                currentNode = getCurrentNode();
                currentParentNode = getCurrentParentNode();
                const {basicData} = node.param;
                setLocation(basicData.directoryPath)
                loadMetadataList(node.param)
            },
            toolbarFun: {
                // 显示右键菜单之前的回调，用于设置显示哪些菜单
                loadToolbarBefore: function (buttons, param, $div) {
                    const {basicData} = param;
                    // 根据数据审核状态判断是否显示相关功能按钮
                    if (basicData && basicData.id !== DIR_ROOT_ID && basicData.id !== DIR_THEME_ROOT_ID) {
                        switch (basicData.reviewStatus) {
                            case ReviewStatus.SUBMITTED:
                                setDisabledButtons([]);
                            case ReviewStatus.PASS:
                                setDisabledButtons([]);
                                break;
                            case ReviewStatus.UN_SUBMIT:
                            case ReviewStatus.FAIL:
                                setDisabledButtons(['toolbar_dir_rejected']);
                                break
                            case ReviewStatus.REJECTED:
                                setDisabledButtons(['toolbar_dir_rejected']);
                        }
                    }

                    /**
                     * 设置需要禁用的按钮
                     * @param buttonIds 按钮ID数组
                     */
                    function setDisabledButtons(buttonIds = []) {
                        for (let btnName of buttonIds) {
                            let $btn = $(buttons[btnName]);
                            let $a = $btn.find('a').addClass('layui-disabled');
                            $btn.html($a[0]);
                            buttons[btnName] = $btn[0];
                        }
                    }

                    return buttons;
                }
            },
            toolbarExt: [
                {
                    toolbarId: "toolbar_dir_rejected",
                    icon: "layui-icon layui-icon-release",
                    title: "驳回", handler: function (node, elem) {
                        ReviewComponent.renderDirectoryList(true)
                        ReviewComponent.openReviewLayer(node.id, ReviewStatus.REJECTED, res => {
                            let temp = Object.assign({}, node)
                            temp.basicData.reviewStatus = ReviewStatus.REJECTED;
                            temp.title = temp.context;
                            temp.title = formatterTitle(temp);
                            dirTree.partialRefreshEdit(elem, temp)
                            dirTree.getChild(elem);
                            loadMetadataList(node)
                        });
                    }
                },
            ],
            formatter: {
                title: function (data) { // 文字过滤，返回null,"",undefined之后，都不会改变原有的内容返回。
                    return formatterTitle(data);
                }
            }
        }
        dirTree = globalTree.init(treeOps);


        /**
         * 获取当前节点
         * @returns {*|jQuery|HTMLElement}
         */
        function getCurrentNode() {
            return $('li.dtree-nav-item div.dtree-theme-item-this');
        }

        /**
         * 获取当前节点的父级节点
         * @returns {*|jQuery}
         */
        function getCurrentParentNode() {
            return getCurrentNode().parent().parent().prev();
        }

        function reZhanKai(node) {
            let iconNode = node.find('i:first');
            if (iconNode.data('spread') === 'open') {
                iconNode.click();
                iconNode.click();
            } else {
                iconNode.click();
            }
        }
    })
}
