<!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; }
        .tip { color: #e8501a; font-size: 12px; margin-left: 8px; }
        .section-title { font-weight: bold; margin: 16px 0 8px; }
        .auto-offline-bar { margin-bottom: 10px; font-size: 13px; }
        .settlement-input { width: 100px; }
        .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 class="tip">如未关联商品，则APP和小程序前端推荐模块隐藏</span>
    </div>

    <!-- Select2 选择框 -->
    <div class="add-row">
        <select id="goodsSelect" style="width:400px;">
            <option value="">请输入商品名称搜索...</option>
        </select>
        <span style="color:#999;font-size:12px;">选中商品后自动添加到列表</span>
    </div>

    <!-- 已关联商品 -->
    <div class="section-title">
        已关联商品
        <span class="tip">⚠ 设置换购价格，则商品参与演出票换购活动，不设置则按售价售卖，换购价须小于商品售价</span>
    </div>
    <div class="auto-offline-bar">
        <label>
            <input type="checkbox" id="globalAutoOffline" onchange="toggleGlobalAutoOffline(this)"/>
            演出结束商品自动下架
        </label>
    </div>
    <div class="table-responsive">
        <table class="table table-bordered" id="linkedGoodsTable">
            <thead>
            <tr>
                <th>商品ID</th>
                <th>商品头图</th>
                <th>商品名称</th>
                <th>商品售价（元）</th>
                <th>换购价（元）</th>
                <th>商品库存</th>
                <th>自动下架</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="linkedGoodsBody">
            <tr id="emptyRow">
                <td colspan="8" style="text-align:center;color:#999;">暂无关联商品</td>
            </tr>
            </tbody>
        </table>
    </div>

    <button type="button" class="btn btn-primary" onclick="saveConfig()">保存配置</button>
</div>

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

    // 内存中维护已关联商品列表
    var linkedGoods = [];

    // ——— mock 数据（接口无数据时用于测试）———
    var MOCK_GOODS = [
        { skuId: 'SKU_MOCK_001', spuId: 'SPU_MOCK_001', spuName: '收钱吧周边T恤', skuName: '收钱吧周边T恤 M码', price: 9900, stock: 100, coverPic: '' },
        { skuId: 'SKU_MOCK_002', spuId: 'SPU_MOCK_002', spuName: '演出纪念手册',   skuName: '演出纪念手册 精装版',price: 4900, stock: 200, coverPic: '' },
        { skuId: 'SKU_MOCK_003', spuId: 'SPU_MOCK_003', spuName: '限定徽章套装',   skuName: '限定徽章套装 五件套', price: 3900, stock: 50,  coverPic: '' },
        { skuId: 'SKU_MOCK_004', spuId: 'SPU_MOCK_004', spuName: '摇滚帽子',       skuName: '摇滚帽子 黑色',      price: 5900, stock: 80,  coverPic: '' },
    ];

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

    // 初始化 Select2（AJAX 搜索 + mock fallback）
    function initSelect2() {
        $('#goodsSelect').select2({
            allowClear: true,
            placeholder: '请输入商品名称搜索...',
            minimumInputLength: 0,
            language: { inputTooShort: function () { return '请输入关键词'; } },
            ajax: {
                url: prefix + '/search',
                dataType: 'json',
                delay: 300,
                data: function (params) { return { keyword: params.term || '' }; },
                processResults: function (resp) {
                    var list = (resp && resp.data) ? resp.data : [];
                    // 接口无数据时回退到 mock
                    if (list.length === 0) { list = filterMock($('#goodsSelect').data('select2').options.get('ajax').data({ term: '' }).keyword); }
                    return { results: list.map(function (item) {
                        return { id: item.skuId, text: (item.spuName || item.skuName), _raw: item };
                    })};
                },
                error: function () {
                    // 接口异常时使用 mock
                    return { results: MOCK_GOODS.map(function (item) {
                        return { id: item.skuId, text: item.spuName, _raw: item };
                    })};
                }
            }
        });

        // 选中即添加
        $('#goodsSelect').on('select2:select', function (e) {
            var raw = e.params.data._raw;
            if (!raw) {
                // 兼容：从 mock 中找
                raw = MOCK_GOODS.find(function(m){ return m.skuId === e.params.data.id; });
            }
            if (raw) { addLinked(raw); }
            // 清空选择框
            $(this).val(null).trigger('change');
        });

        // 若 ajax 报错或首次打开无关键词，预填 mock
        $('#goodsSelect').on('select2:open', function () {
            // 触发一次搜索以显示 mock 数据
            setTimeout(function () {
                var searchInput = document.querySelector('.select2-search__field');
                if (searchInput) { $(searchInput).trigger('input'); }
            }, 100);
        });
    }

    function filterMock(keyword) {
        if (!keyword) return MOCK_GOODS;
        return MOCK_GOODS.filter(function (m) { return m.spuName.indexOf(keyword) >= 0; });
    }

    // 加载已关联商品
    function loadLinkedGoods() {
        $.get(prefix + '/list', { performancesId: performancesId }, function (resp) {
            if (resp.code === 0 && resp.data && resp.data.length > 0) {
                linkedGoods = resp.data.map(function (item) {
                    return {
                        skuId: item.skuId, spuId: item.spuId,
                        spuName: item.spuName || item.skuName, skuName: item.skuName,
                        coverPic: item.coverPic || '', price: item.price, stock: item.stock,
                        settlementPrice: item.settlementPrice || '', autoOffline: item.autoOffline || 0
                    };
                });
                renderLinkedGoods();
            }
        });
    }

    function renderLinkedGoods() {
        var tbody = document.getElementById('linkedGoodsBody');
        if (linkedGoods.length === 0) {
            tbody.innerHTML = '<tr id="emptyRow"><td colspan="8" style="text-align:center;color:#999;">暂无关联商品</td></tr>';
            return;
        }
        var html = '';
        linkedGoods.forEach(function (item, idx) {
            var priceYuan = item.price ? (item.price / 100).toFixed(2) : '-';
            var settlementVal = item.settlementPrice || '';
            var autoChecked = item.autoOffline == 1 ? 'checked' : '';
            var imgHtml = item.coverPic
                ? '<img src="' + item.coverPic + '" class="img-thumb"/>'
                : '<span style="color:#ccc;font-size:12px;">无图</span>';
            html += '<tr data-idx="' + idx + '">';
            html += '<td><small>' + item.skuId + '</small></td>';
            html += '<td>' + imgHtml + '</td>';
            html += '<td>' + (item.spuName || item.skuName || '-') + '</td>';
            html += '<td>' + priceYuan + '</td>';
            html += '<td><input type="number" class="form-control settlement-input" value="' + settlementVal
                + '" placeholder="不填按售价" onchange="updateSettlement(' + idx + ', this.value)" min="0" step="0.01"/></td>';
            html += '<td>' + (item.stock != null ? item.stock : '-') + '</td>';
            html += '<td><input type="checkbox" ' + autoChecked + ' onchange="updateAutoOffline(' + idx + ', this)"/></td>';
            html += '<td><button type="button" class="btn btn-xs btn-danger" onclick="removeLinked(' + idx + ')">取消关联</button></td>';
            html += '</tr>';
        });
        tbody.innerHTML = html;
    }

    function addLinked(item) {
        for (var i = 0; i < linkedGoods.length; i++) {
            if (linkedGoods[i].skuId === item.skuId) {
                layer.msg('该商品已在关联列表中');
                return;
            }
        }
        linkedGoods.push({
            skuId: item.skuId, spuId: item.spuId || '',
            spuName: item.spuName, skuName: item.skuName,
            coverPic: item.coverPic || '', price: item.price, stock: item.stock,
            settlementPrice: null, autoOffline: 0
        });
        renderLinkedGoods();
        layer.msg('已添加，可配置换购价后保存');
    }

    function updateSettlement(idx, val) {
        linkedGoods[idx].settlementPrice = val ? parseFloat(val) : null;
    }

    function updateAutoOffline(idx, checkbox) {
        linkedGoods[idx].autoOffline = checkbox.checked ? 1 : 0;
    }

    function toggleGlobalAutoOffline(checkbox) {
        var val = checkbox.checked ? 1 : 0;
        linkedGoods.forEach(function (item) { item.autoOffline = val; });
        renderLinkedGoods();
    }

    function removeLinked(idx) {
        var skuId = linkedGoods[idx].skuId;
        // mock 数据直接从内存移除，无需请求接口
        if (skuId.startsWith('SKU_MOCK_')) {
            linkedGoods.splice(idx, 1);
            renderLinkedGoods();
            return;
        }
        if (!confirm('确定取消关联该商品？')) return;
        $.post(prefix + '/unbind', { performancesId: performancesId, skuId: skuId }, function (resp) {
            if (resp.code === 0) {
                linkedGoods.splice(idx, 1);
                renderLinkedGoods();
            } else {
                alert(resp.msg || resp.message || '操作失败');
            }
        });
    }

    function saveConfig() {
        var items = linkedGoods.map(function (item) {
            return {
                skuId: item.skuId, sort: 0,
                settlementPrice: item.settlementPrice || null,
                autoOffline: item.autoOffline || 0
            };
        });
        $.ajax({
            url: prefix + '/bind?performancesId=' + encodeURIComponent(performancesId),
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(items),
            success: function (resp) {
                if (resp.code === 0) {
                    layer.msg('保存成功');
                } else {
                    layer.msg(resp.msg || resp.message || '保存失败', { icon: 2 });
                }
            },
            error: function () {
                layer.msg('请求失败，请重试', { icon: 2 });
            }
        });
    }
</script>
</body>
</html>
