<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('艺人专题管理')" />
    <style>
        /* 状态与推荐 标签样式 (匹配图2) */
        .badge-status {
            display: inline-block;
            padding: 3px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
            line-height: 1.4;
        }
        .badge-status-success {
            background-color: #e6f7eb;
            color: #52c41a;
        }
        .badge-status-warning {
            background-color: #fef8e7;
            color: #d99b00;
        }
        .badge-status-gray {
            background-color: #f5f5f5;
            color: #8c8c8c;
        }
        
        .badge-rec {
            display: inline-block;
            padding: 3px 10px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
            line-height: 1.4;
        }
        .badge-rec-active {
            background-color: #e6f7ff;
            color: #1890ff;
        }
        .badge-rec-none {
            background-color: #f5f5f5;
            color: #8c8c8c;
        }

        /* 操作按钮样式 (匹配图2) */
        .action-cell {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 4px;
        }
        .action-row-top {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }
        .btn-act {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 2px 8px;
            font-size: 12px;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none !important;
            transition: all 0.2s;
        }
        .btn-act i {
            margin-right: 3px;
        }
        .btn-act-detail {
            background-color: #e6f7ff;
            color: #1890ff;
            border: 1px solid #91d5ff;
        }
        .btn-act-detail:hover {
            background-color: #bae7ff;
            color: #096dd9;
        }
        .btn-act-offsale {
            background-color: #fff7e6;
            color: #fa8c16;
            border: 1px solid #ffd591;
        }
        .btn-act-offsale:hover {
            background-color: #ffe7ba;
            color: #d46b08;
        }
        .btn-act-rec {
            background-color: #ffffff;
            color: #595959;
            border: 1px solid #d9d9d9;
            padding: 2px 10px;
        }
        .btn-act-rec:hover {
            border-color: #40a9ff;
            color: #40a9ff;
        }

        /* 推荐设置下拉菜单 */
        .rec-menu {
            position: absolute; z-index: 9999; display: none;
            min-width: 110px; padding: 5px 0;
            background: #fff; border: 1px solid #e4e7ed; border-radius: 4px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, .12);
        }
        .rec-menu a {
            display: block; padding: 6px 16px; font-size: 12px;
            color: #606266; white-space: nowrap; cursor: pointer;
            text-decoration: none !important;
        }
        .rec-menu a:hover { background: #f5f7fa; color: #1890ff; }
        .rec-menu a.active { color: #1890ff; font-weight: bold; }
        /* 推荐位替换确认弹框 */
        .replace-confirm { padding: 24px 28px 18px; }
        .replace-confirm p { margin: 0 0 24px; font-size: 13px; color: #333; line-height: 1.9; }
        .replace-btns { text-align: right; }
        .replace-btns a { display: inline-block; margin-left: 10px; padding: 8px 20px; border-radius: 4px; font-size: 13px; cursor: pointer; }
        .replace-btns .btn-cancel { background: #e8e8e8; color: #333; }
        .replace-btns .btn-cancel:hover { background: #dcdcdc; }
        .replace-btns .btn-ok { background: #1890ff; color: #fff; }
        .replace-btns .btn-ok:hover { background: #40a9ff; }
    </style>
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <form id="role-form">
                <div class="select-list">
                    <ul>
                        <li>专题名称：<input type="text" name="topicName" placeholder="请输入专题名称"/></li>
                        <li>关联艺人：<input type="text" name="artistName" placeholder="请输入艺人名称"/></li>
                        <li>专题状态：<select name="status">
                            <option value="">全部</option>
                            <option value="0">待上架</option>
                            <option value="1">已上架</option>
                            <option value="2">已下架</option>
                        </select></li>
                        <li>所属商家：<input type="text" name="storeName" placeholder="请输入商家名称"/></li>
                        <li>
                            <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i> 搜索</a>
                            <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i class="fa fa-refresh"></i> 重置</a>
                        </li>
                    </ul>
                </div>
            </form>
        </div>
        <div class="col-sm-12 select-table table-striped">
            <table id="bootstrap-table"></table>
        </div>
    </div>
</div>
<th:block th:include="include :: footer" />
<script th:inline="javascript">
    var prefix = ctx + "goblin/artist/topic";
    var recommendFlg = [[${@permission.hasPermi('goblin:artist:topic:recommend')}]];
    var statusFlg = [[${@permission.hasPermi('goblin:artist:topic:status')}]];
    var infoFlg = [[${@permission.hasPermi('goblin:artist:topic:info')}]];
    var tagFlg = [[${@permission.hasPermi('goblin:artist:topic:tag')}]];

    function statusHtml(v) {
        if (v == 1) {
            return '<span class="badge-status badge-status-success">已上架</span>';
        } else if (v == 0) {
            return '<span class="badge-status badge-status-warning">待上架</span>';
        } else {
            return '<span class="badge-status badge-status-gray">已下架</span>';
        }
    }
    function recommendHtml(v) {
        return v ? '<span class="badge-rec badge-rec-active">推荐' + v + '号位</span>'
                 : '<span class="badge-rec badge-rec-none">无推荐</span>';
    }
    function tagHtml(v) {
        return v ? '<span class="badge-rec badge-rec-active">' + v + '</span>'
                 : '<span class="badge-rec badge-rec-none">无</span>';
    }
    function saleTimeHtml(row) {
        if (!row.onSaleStart && !row.onSaleEnd) return '-';
        return (row.onSaleStart || '--') + ' 至 ' + (row.onSaleEnd || '--');
    }

    $(function() {
        $.table.init({
            url: prefix + "/list",
            sortName: "sort",
            sortOrder: "asc",
            columns: [
                { field: 'topicId', title: '专题ID' },
                { field: 'topicName', title: '专题名称' },
                { field: 'artistName', title: '关联艺人', formatter: function(v, row) { return v || row.artistId || '-'; }},
                { field: 'goodsCount', title: '商品数' },
                { field: 'storeName', title: '所属商家', formatter: function(v, row) { return v || row.storeId || '-'; }},
                { field: 'createdAt', title: '创建时间' },
                { field: 'onSaleStart', title: '上架时间', formatter: function(v, row) { return saleTimeHtml(row); }},
                { field: 'status', title: '专题状态', align: 'center', formatter: function(v) { return statusHtml(v); }},
                { field: 'recommendPosition', title: '推荐状态', align: 'center', formatter: function(v) { return recommendHtml(v); }},
                { field: 'tag', title: '标签', align: 'center', formatter: function(v) { return tagHtml(v); }},
                { title: '操作', align: 'center', formatter: function(v, row) {
                    var html = '<div class="action-cell">';
                    html += '<div class="action-row-top">';
                    html += '<a class="btn-act btn-act-detail ' + infoFlg + '" onclick="openDetail(\'' + row.topicId + '\')"><i class="fa fa-eye"></i> 详情</a>';
                    if (row.status == 1) {
                        html += '<a class="btn-act btn-act-offsale ' + statusFlg + '" onclick="changeStatus(\'' + row.topicId + '\',2)"><i class="fa fa-arrow-down"></i> 下架</a>';
                    }
                    html += '</div>';
                    html += '<a class="btn-act btn-act-rec ' + recommendFlg + '" onclick="openRecMenu(event, \'' + row.topicId + '\',' + (row.recommendPosition || 0) + ')">推荐设置 <i class="fa fa-caret-down"></i></a>';
                    var safeTag = (row.tag || '').replace(/\\/g, '\\\\').replace(/'/g, "\\'");
                    html += '<a class="btn-act btn-act-rec ' + tagFlg + '" onclick="openSetTag(\'' + row.topicId + '\',\'' + safeTag + '\')">设置标签</a>';
                    html += '</div>';
                    return html;
                }}
            ]
        });
    });

    // ---------- 详情弹框 ----------
    function openDetail(topicId) {
        layer.open({
            type: 2,
            title: '艺人专题详情',
            area: ['680px', '600px'],
            shade: 0.3,
            content: prefix + "/detail/" + topicId
        });
    }

    // ---------- 下架 ----------
    function changeStatus(topicId, status) {
        $.modal.confirm("确认要将该专题下架吗？", function() {
            $.modal.loading("正在下架，请稍候...");
            $.ajax({
                type: 'post', url: prefix + "/status",
                data: { topicId: topicId, status: status },
                success: function(res) {
                    $.modal.closeLoading();
                    if (res.code == 0) {
                        $.modal.msgSuccess("下架成功");
                        $.table.refresh();
                    } else {
                        $.modal.alertError(res.msg);
                    }
                },
                error: function() { $.modal.closeLoading(); }
            });
        });
    }

    // ---------- 推荐设置下拉菜单 ----------
    var recPositions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    var $recMenu = null;

    function openRecMenu(event, topicId, curPos) {
        event.stopPropagation();
        closeRecMenu();

        var html = '<div class="rec-menu">';
        recPositions.forEach(function(pos) {
            html += '<a data-val="' + pos + '"' + (pos == curPos ? ' class="active"' : '') + '>推荐' + pos + '号位</a>';
        });
        html += '<a data-val="0"' + (curPos == 0 ? ' class="active"' : '') + '>无推荐</a></div>';

        $recMenu = $(html).appendTo('body');
        var $btn = $(event.currentTarget);
        $recMenu.css({
            top: $btn.offset().top + $btn.outerHeight() + 4,
            left: $btn.offset().left
        }).show();

        $recMenu.on('click', 'a', function() {
            setRecommend(topicId, $(this).data('val'));
        });
        $(document).on('click.recMenu', closeRecMenu);
    }

    function closeRecMenu() {
        if ($recMenu) { $recMenu.remove(); $recMenu = null; }
        $(document).off('click.recMenu');
    }

    function setRecommend(topicId, position) {
        closeRecMenu();
        if (position == 0) {
            doSetRecommend(topicId, position);
            return;
        }
        // 先查推荐位是否被其他专题占用，占用则弹替换确认框
        $.get(prefix + "/recommendOwner", { position: position }, function(res) {
            var owner = res.data;
            if (owner && owner.topicId != topicId) {
                openReplaceConfirm(topicId, position, owner.topicName);
            } else {
                doSetRecommend(topicId, position);
            }
        });
    }

    function openReplaceConfirm(topicId, position, ownerName) {
        var html = '<div class="replace-confirm">'
            + '<p>推荐' + position + '号位已被「' + ownerName + '」占用，是否替换为当前专题使用该推荐位？如果替换，原推荐位专题将更新为无推荐位，按排序规则展示。</p>'
            + '<div class="replace-btns"><a class="btn-cancel">取消</a><a class="btn-ok">确认替换</a></div></div>';
        var idx = layer.open({
            type: 1,
            title: '推荐位替换确认',
            shade: 0.3,
            area: ['440px'],
            content: html,
            success: function(layero) {
                layero.find('.btn-cancel').on('click', function() { layer.close(idx); });
                layero.find('.btn-ok').on('click', function() {
                    layer.close(idx);
                    doSetRecommend(topicId, position);
                });
            }
        });
    }

    function doSetRecommend(topicId, position) {
        $.modal.loading(position == 0 ? "正在取消推荐..." : "正在设置推荐" + position + "号位...");
        $.ajax({
            type: 'post', url: prefix + "/recommend",
            data: { topicId: topicId, position: position },
            success: function(res) {
                $.modal.closeLoading();
                if (res.code == 0) {
                    $.modal.msgSuccess(position == 0 ? "已取消推荐" : "推荐" + position + "号位设置成功");
                    $.table.refresh();
                } else {
                    $.modal.alertError(res.msg);
                }
            },
            error: function() { $.modal.closeLoading(); }
        });
    }

    // ---------- 设置标签 ----------
    function openSetTag(topicId, curTag) {
        layer.prompt({
            title: '设置专题标签（如 HOT / 上新，可清空）',
            formType: 0,
            value: curTag || '',
            maxlength: 32
        }, function(value, index) {
            layer.close(index);
            doSetTag(topicId, value == null ? '' : value);
        });
    }

    function doSetTag(topicId, tag) {
        $.modal.loading("正在保存标签...");
        $.ajax({
            type: 'post', url: prefix + "/tag",
            data: { topicId: topicId, tag: tag },
            success: function(res) {
                $.modal.closeLoading();
                if (res.code == 0) {
                    $.modal.msgSuccess("标签已更新");
                    $.table.refresh();
                } else {
                    $.modal.alertError(res.msg);
                }
            },
            error: function() { $.modal.closeLoading(); }
        });
    }
</script>
</body>
</html>
