<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('关联商品')"/>
    <link rel="stylesheet" th:href="@{/ajax/libs/select2/select2.min.css}"/>
    <style>
        body { background: #fff; }
        .page-wrap { padding: 16px; }
        .section-title { font-weight: bold; margin: 16px 0 8px; }
        .img-thumb { width: 40px; height: 40px; object-fit: cover; border-radius: 4px; }
        .select2-container { min-width: 380px; }
        .add-row { margin-bottom: 16px; display: flex; align-items: center; gap: 10px; }
    </style>
</head>
<body class="white-bg">
<div class="page-wrap">
    <div class="section-title">
        艺人：<span th:text="${artistName}">--</span>
        <span style="font-size:12px;color:#999;margin-left:8px;" th:text="'ID: ' + ${artistId}"></span>
    </div>

    <div class="add-row">
        <select id="goodsSelect" style="width:400px;">
            <option value="">默认最近20条，输入名称搜索全部匹配</option>
        </select>
        <span style="color:#999;font-size:12px;">选中商品后自动添加到列表</span>
    </div>

    <div class="section-title">已关联商品</div>
    <div class="table-responsive">
        <table class="table table-bordered">
            <thead>
            <tr>
                <th>商品SPU ID</th>
                <th>头图</th>
                <th>商品名称</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="linkedProductsBody">
            <tr id="linkedProductsEmptyRow">
                <td colspan="5" style="text-align:center;color:#999;">暂无关联商品</td>
            </tr>
            </tbody>
        </table>
    </div>
</div>

<th:block th:include="include :: footer"/>
<script th:src="@{/ajax/libs/select2/select2.min.js}"></script>
<script th:inline="javascript">
    var artistId = /*[[${artistId}]]*/ '';
    var prefix = ctx + 'kylin/artist';
    var linkedProducts = [];

    $(function () {
        initSelect2();
        loadLinkedProducts();
    });

    function initSelect2() {
        $('#goodsSelect').select2({
            allowClear: true,
            placeholder: '默认最近20条，输入名称搜索全部匹配',
            minimumInputLength: 0,
            ajax: {
                url: prefix + '/searchGoods',
                dataType: 'json',
                delay: 300,
                data: function (params) {
                    return {
                        keyword: params.term || '',
                        artistId: artistId,
                        excludeSpuIds: linkedProducts.map(function (item) { return item.spuId; }).join(',')
                    };
                },
                processResults: function (resp) {
                    var list = (resp && resp.data) ? resp.data : [];
                    return { results: list.map(function (item) {
                        var text = item.name || item.spuId;
                        if (item.spuNo) {
                            text += ' (' + item.spuNo + ')';
                        }
                        return { id: item.spuId, text: text, disabled: item.selectable === false, _raw: item };
                    })};
                }
            }
        }).on('select2:select', function (e) {
            var raw = e.params.data._raw;
            if (raw && raw.selectable === false) {
                $.modal.alertWarning('该商品不可关联');
                $(this).val(null).trigger('change');
                return;
            }
            if (raw) {
                addLinkedProduct(raw);
            }
            $(this).val(null).trigger('change');
        });
    }

    function loadLinkedProducts() {
        $.get(prefix + '/products/list', { artistId: artistId }, function (resp) {
            if (resp.code === 0 && resp.data) {
                linkedProducts = resp.data.map(function (item) {
                    return {
                        spuId: item.spuId,
                        name: item.productName,
                        coverPic: item.imageUrl,
                        shelfStatusLabel: item.status === 1 ? '已上架' : '未上架'
                    };
                });
                renderLinkedProducts();
            }
        });
    }

    function renderLinkedProducts() {
        var $body = $('#linkedProductsBody');
        $body.empty();
        if (!linkedProducts.length) {
            $body.append('<tr><td colspan="5" style="text-align:center;color:#999;">暂无关联商品</td></tr>');
            return;
        }
        linkedProducts.forEach(function (item, index) {
            $body.append('<tr>' +
                '<td>' + (item.spuId || '--') + '</td>' +
                '<td>' + (item.coverPic ? '<img class="img-thumb" src="' + item.coverPic + '">' : '--') + '</td>' +
                '<td>' + (item.name || '--') + '</td>' +
                '<td>' + (item.shelfStatusLabel || '--') + '</td>' +
                '<td><button type="button" class="btn btn-danger btn-xs" onclick="removeLinkedProduct(' + index + ')">移除</button></td>' +
                '</tr>');
        });
    }

    function addLinkedProduct(raw) {
        if (!raw || !raw.spuId) {
            return;
        }
        if (linkedProducts.some(function (item) { return item.spuId === raw.spuId; })) {
            $.modal.alertWarning('该商品已在列表中');
            return;
        }
        linkedProducts.push({
            spuId: raw.spuId,
            name: raw.name,
            coverPic: raw.coverPic,
            shelfStatusLabel: raw.shelfStatusLabel
        });
        renderLinkedProducts();
    }

    function removeLinkedProduct(index) {
        linkedProducts.splice(index, 1);
        renderLinkedProducts();
    }

    function submitHandler(index, layero) {
        var spuIds = linkedProducts.map(function (item) { return item.spuId; });
        $.ajax({
            url: prefix + '/products/save',
            type: 'post',
            contentType: 'application/json',
            data: JSON.stringify({ artistId: artistId, spuIds: spuIds }),
            success: function (resp) {
                if (resp.code === 0) {
                    if (parent && parent.$ && parent.$.modal) {
                        parent.$.modal.msgSuccess('保存成功');
                        if (parent.$.table) {
                            parent.$.table.refresh();
                        }
                    } else {
                        $.modal.msgSuccess('保存成功');
                    }
                    if (typeof index !== 'undefined') {
                        parent.layer.close(index);
                    } else {
                        $.modal.close();
                    }
                } else {
                    $.modal.alertError(resp.msg || '保存失败');
                }
            }
        });
    }
</script>
</body>
</html>
