/**
 * <p>
 *  datasource.js
 * </p>
 *
 * @author Administrator
 * @since 2021/5/24
 */
layui.use(['layer', 'listPage', 'form', 'dict'], function () {
    const layer = layui.layer;
    const form = layui.form;

    let height = $(document).height();
    height = height < 650 ? height : height * 0.8;
    let where = {metadataName: '', reviewStatus: '', useStatus: ''};

    const fieldMap = new Map()
    METADATA_FORM_CONFIG.forEach(conf=>fieldMap.set(conf.fieldName, conf));
    console.info(fieldMap);
    const listPage = layui.listPage.init({
        deleteUrl: `${ctx}/business/metadata/delete`,
        table: {
            id: 'metadataTable',
            searchFieldNames: 'metadataName',
            url: `${ctx}/business/metadata/simple/page`,
            limit: 30,
            cols: [[
                {field: 'id', title: 'ID', hide: true},
                {field: 'checkbox', type: 'checkbox', title: '选择', width: 60},
                {
                    field: 'metadataName',
                    title: '数据名称',
                    hide: !fieldMap.get('metadataName').isShow,
                    templet: data => `<lable style="font-weight: ${data.hasMark ? 'bold' : 'italic'};">${data.metadataName}</lable>`

                },
                {field: 'metadataComment', title: '中文注释',hide: fieldMap.get('metadataName').isShow},
                {
                    field: 'secretLevel',
                    title: '密级',
                    hide: !fieldMap.get('secretLevel').isShow,
                    templet: data => layui.dict.getDictDesc('secret_level', data.secretLevel)
                },
                {field: 'themeTask', title: '主题任务', hide: !fieldMap.get('themeTask').isShow},
                {
                    field: 'dataFrom',
                    title: '数据来源',
                    hide: !fieldMap.get('dataFrom').isShow,
                    width: 100,
                    templet: data => layui.dict.getDictDesc('data_source', data.dataFrom)
                },
                {field: 'collectionTime', title: '任务时间', width: 180, align: 'center',hide: !fieldMap.get('collectionTime').isShow},
                {
                    field: 'used', title: '关联状态', width: 120, align: 'center', templet: (data) => {
                        if (data.used) {
                            return `<span style="color: #009688">已关联</span>`;
                        }
                        return `未关联`;
                    }
                },
                {
                    field: 'reviewStatus', title: '审核状态', width: 120, align: 'center', templet: (data) => {
                        let colorClass = 'layui-bg-blue';
                        let title = '';
                        switch (data.reviewStatus) {
                            case ReviewStatus.SUBMITTED:
                            /*colorClass = 'layui-bg-orange';
                            break;*/
                            case ReviewStatus.PASS:
                                colorClass = 'layui-bg-green';
                                break;
                            case ReviewStatus.FAIL:
                            case ReviewStatus.REJECTED:
                                colorClass = 'layui-bg-badge';
                                title = '点击查看原因';
                        }
                        return `<span class="review-tips layui-badge ${colorClass}" data-status="${data.reviewStatus}" title="${title}" data-id="${data.id}" id="tips-${data.id}">${ReviewStatusMsg[data.reviewStatus]}</span>`
                    }
                },
                {fixed: 'right', title: '操作', toolbar: '#rowToolBar', width: 200, align: 'right'}
            ]],
            done: data => {
                data.records.forEach(function (item, index) {
                    if (item.used) {
                        let tr = $(".layui-table tr[data-index=" + index + "]");
                        tr.find("input[type='checkbox']").prop('disabled', true);
                        tr.find("input[type='checkbox']").next().addClass('layui-btn-disabled');
                    }

                });
                form.val('metadataSearchForm', {
                    reviewStatusSelect: where.reviewStatus,
                    useStateSelect: where.useStatus
                });
                form.on('select(reviewStatusSelect)', function ({elem, othis, value}) {
                    where.reviewStatus = value;
                    listPage.reloadTable({table: {where}})
                });
                form.on('select(useStateSelect)', function ({elem, othis, value}) {
                    where.useStatus = value;
                    listPage.reloadTable({table: {where}})
                });

                // 审核不通过提示
                $('.review-tips').on('click', function (_this) {
                    const id = $(_this.target).data('id');
                    const status = $(_this.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 class="tips-title" style="height: 32px;line-height: 32px;color: #dbdbdb;">审核人：${reviewData.reviewUser}</div>
                                        <div class="tips-content" style="min-width: 200px;max-width: 500px;min-height: 30px;max-height: 300px; color: gray">原因：${reviewData.reviewOpinion}</div>
                                    </div>`;
                                layer.tips(content, `#tips-${id}`, {
                                    tips: [4],
                                    closeBtn: 1,
                                    shade: 0.3,
                                    shadeClose: true,
                                    time: 60000
                                });
                            } else {
                                showErrorMsg(res.msg)
                            }
                        })
                    }
                });
            }
        },
        editPage: {
            content: `${ctx}/business/metadata/edit`,
            area: ['890px', height + 'px']
        }
    });

    listPage.addTableRowEvent('exampleData', function (data) {
        layer.open({
            title: '示例数据',
            type: 2,
            area: ['900px', '600px'],
            content: `${ctx}/business/metadata/example?metadataId=${data.id}`
        })
    });
    listPage.addTableRowEvent('submitReview', function (data) {
        let param = {
            id: data.id,
            status: ReviewStatus.SUBMITTED,
            opinion: '',
            sendNotice: false,
        };
        Util.post('/business/review/metadata/change', param).then(res => {
            if (res.flag) {
                layer.msg('提交成功');
                listPage.reloadTable();
            } else {
                layer.msg('提交失败,' + res.msg);
            }
        }).catch(err => {
            console.info(err);
            layer.msg('提交失败,' + err.msg);
        })
    });
    listPage.addTableRowEvent('del', (data) => {
        let checkRows = listPage.getCheckStatus();
        let datas = checkRows.data;
        if (datas.length == 0) {
            showErrorMsg("请至少选择一条数据");
            return;
        }
        layer.confirm('是否确定删除这些数据', {title: '删除'}, function () {
            let ids = checkRows.data.map(d => d.id).join(',');
            Util.post(`/business/metadata/delete`, {ids}).then(res => {
                if (res.flag) {
                    showOkMsg("删除成功");
                    listPage.reloadTable();
                } else {
                    showErrorMsg("删除失败，请联系管理员");
                }
            }).catch(err => {
                showErrorMsg("系统异常，请联系管理员")
                console.error(err);
            })
        })
    })

});
