/**
 * <p>
 *  资源审核页面通用js
 * </p>
 *
 * @author GuoXin
 * @since 2021/6/3
 */
// 预定义属性
const reviewOps = {};

/**
 * 审核操作窗口html模板
 * @type {string}
 */
const reviewLayerHtml = `
    <div class="layui-form" lay-filter="reviewForm" style="padding: 15px 15px 0 15px">
        <input type="hidden" name="status" value="REJECTED">
        <!--<div class="layui-form-item">
            <label class="layui-form-label">审核</label>
            <div class="layui-input-block">
                <input type="radio" name="status" value="PASS" title="通过" lay-verify="required" lay-filter="reviewStatusRadio">
                <input type="radio" name="status" value="FAIL" title="不通过" lay-verify="required" lay-filter="reviewStatusRadio">
                &lt;!&ndash;<input type="radio" name="status" value="REJECTED" title="驳回" lay-verify="required" lay-filter="reviewStatusRadio">&ndash;&gt;
            </div>
        </div>-->
        <div class="layui-form-item" style="margin-bottom: 0">
            <!--<label class="layui-form-label">驳回原因</label>-->
            <div class="layui-block">
                <textarea class="layui-textarea" name="opinion" cols="4" lay-verify="required" placeholder="请输入驳回原因..." style="width: 450px"/>
            </div>
        </div>
        <button id="btn-submit" lay-submit lay-filter="reviewForm"
                style="position: absolute; left:-1000px; top: -1px"/>
    </div>
`;
/**
 * 定义数据表格字段列
 * @type {{DIRECTORY: [{hide: boolean, field: string, title: string}, {field: string, title: string}, {field: string, title: string}, {field: string, title: string}, {field: string, title: string}, null][], METADATA: [{hide: boolean, field: string, title: string}, {field: string, title: string}, {field: string, title: string}, {field: string, title: string}, {field: string, title: string}, null, null][]}}
 */
const cols = {
    METADATA: [[
        {field: 'id', title: 'ID', hide: true},
        {field: 'metadataName', title: '数据名称'},
        {field: 'metadataComment', title: '中文注释'},
        {field: 'themeTask', title: '主题任务'},
        {field: 'modifyUserName', title: '提交人'},
        {field: 'modifyTime', title: '提交时间'},
        {fixed: 'right', title: '操作', toolbar: '#rowToolBar', width: 120, align: 'center'}
    ]],
    DIRECTORY: [[
        {field: 'id', title: 'ID', hide: true},
        {field: 'directoryName', title: '目录名称'},
        {field: 'directoryPath', title: '目录路径'},
        {field: 'modifyUserName', title: '提交人'},
        {field: 'modifyTime', title: '提交时间'},
        {fixed: 'right', title: '操作', toolbar: '#rowToolBar', width: 120, align: 'center'}
    ]]
}
let reviewForm;

class Review {
    options = {
        entityType: '', // 数据实体类型
    };

    constructor(options) {
        this.options = $.extend(true, this.options, options);
    }

    /**
     * 初始化组件
     */
    init(onlyLayer) {
        const _this = this;
        let opt = $.extend({}, _this.options);

        layui.use(['layer', 'listPage', 'form'], function () {
            let layer = layui.layer; // 弹出层组件
            let ListPage = layui.listPage; // 数据表格组件
            reviewForm = layui.form;
            const type = opt.entityType.toLowerCase();

            let reviewStatus = 'SUBMITTED';

            if (!onlyLayer) {
                // 数据表格
                const listPage = ListPage.init({
                    table: {
                        id: 'reviewTable',
                        url: `${ctx}/business/review/list/${type}`,
                        method: 'get',
                        height: 'full-84',
                        searchFieldNames: opt.entityType == ReviewEntityType.METADATA ? 'metadataName' : 'directoryName',
                        where: {reviewStatus: reviewStatus},
                        cols: cols[opt.entityType],
                        done: function (res) {
                            reviewForm.val('tableToolForm', {reviewStatus: reviewStatus})
                            reviewForm.render('radio', 'tableToolForm');
                        }
                    }
                })

                // 绑定审核按钮点击事件
                listPage.addTableRowEvent('review', function (data) {
                    _this.reviewOperate(data.id, () => listPage.reloadTable());
                })

                listPage.addTableRowEvent('details', function (data) {
                    let url;
                    if (data.metadataName) { // 数据资源类型数据
                        url = `${ctx}/business/metadata/details/${data.id}`;
                    } else { // 目录类型数据
                        url = `${ctx}/business/directory/details/${data.id}`;
                    }
                    openMaxLayerWithURL(url);
                });

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

    /**
     * 审核操作
     * @param id 需要审核的数据
     * @param callback 回调
     * @param status 审核状态
     */
    reviewOperate(id, callback, status) {
        const _this = this;
        layer.open({
            type: 1,
            title: '驳回',
            area: ['auto'],
            btn: ['确定', '取消'],
            content: reviewLayerHtml,
            success: function (_layer, index) {
                reviewForm.render();
                /*reviewForm.on('radio(reviewStatusRadio)', function ({value}) {
                    let opinion = value == 'PASS' ? '同意' : '';
                    reviewForm.val('reviewForm', {opinion});
                })*/
                let url = _this.options.reviewUrl
                reviewForm.on('submit(reviewForm)', function ({elem, field}) {
                    let param = $.extend({}, field);
                    param.id = id;
                    param.sendNotice = true;
                    $.post(url, param, function (res) {
                        layer.close(index);
                        if (res.flag) {
                            layer.msg('操作成功');
                            callback && callback(res);
                        } else {
                            layer.msg('操作失败,' + res.msg);
                        }
                    });
                    return false;
                });

                if (status) {
                    setTimeout(() => {
                        $(`input[type="radio"][name="status"][value="${status}"]`).next().click();
                    }, 100)
                }
            },
            yes: function () {
                let formData = reviewForm.val('reviewForm');
                if (formData.status) {
                    $('#btn-submit').click();
                } else {
                    layer.msg('请选择审核操作选项！');
                    return false;
                }
            }
        });

    }
}

layui.define([], function (exports) {

    const component = {
        reviewComponent: undefined,
        renderMetadataList: function (flag) {
            const review = new Review(flag);
            review.options.entityType = ReviewEntityType.METADATA;
            review.options.reviewUrl = `${ctx}/business/review/metadata/change`;
            review.init()
            this.reviewComponent = review;
        },
        renderDirectoryList: function (flag) {
            const review = new Review();
            review.options.entityType = ReviewEntityType.DIRECTORY;
            review.options.reviewUrl = `${ctx}/business/review/directory/change`;
            review.init(flag)
            this.reviewComponent = review;
        },
        openReviewLayer: function (id, status, callback) {
            this.reviewComponent.reviewOperate(id, () => {
                callback && callback()
                //window.location.reload();
            }, status);
        }

    };

    exports('ReviewComponent', component);
});