<!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>
            </tr>
            </thead>
            <tbody id="linkedGoodsBody">
            <tr id="emptyRow">
                <td colspan="7" 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 = [];

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

    // 初始化 Select2（AJAX 搜索）
    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 : [];
                    return { results: list.map(function (item) {
                        return { id: item.skuId, text: (item.title || item.spuName || item.skuName), _raw: item };
                    })};
                }
            }
        });

        // 选中即添加
        $('#goodsSelect').on('select2:select', function (e) {
            var raw = e.params.data._raw;
            if (raw) { addLinked(raw); }
            // 清空选择框
            $(this).val(null).trigger('change');
        });
    }

    // 加载已关联商品
    function loadLinkedGoods() {
        $.get(prefix + '/list', { performancesId: performancesId }, function (resp) {
            if (resp.code === 0 && resp.data) {
                // 设置全局开关状态
                var globalAuto = resp.data.autoOffline === 1;
                $('#globalAutoOffline').prop('checked', globalAuto);
                
                var list = resp.data.goodsList || [];
                linkedGoods = list.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 != null ? item.settlementPrice : ''),
                        persisted: true
                    };
                });
                renderLinkedGoods();
            }
        });
    }

    function renderLinkedGoods() {
        var tbody = document.getElementById('linkedGoodsBody');
        if (linkedGoods.length === 0) {
            tbody.innerHTML = '<tr id="emptyRow"><td colspan="7" 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 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><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.title || item.spuName || item.skuName,
            skuName: item.title || item.skuName || item.spuName,
            coverPic: item.skuPic || item.coverPic || '',
            price: item.price,
            stock: (item.skuStock != null ? item.skuStock : item.stock),
            settlementPrice: null, autoOffline: 0, persisted: false
        });
        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) {
        // 全局开关，无需在 linkedGoods 中逐个维护 autoOffline
        // 只需在保存时通过 checkbox.checked 获取
    }

    function removeLinked(idx) {
        var item = linkedGoods[idx];
        if (!item) {
            return;
        }

        // 未入库（本次新增、未保存）直接从页面移除
        if (!item.persisted) {
            linkedGoods.splice(idx, 1);
            renderLinkedGoods();
            layer.msg('已从待保存列表移除');
            return;
        }

        $.modal.confirm('确认要取消关联该商品吗？', function () {
            $.post(prefix + '/unbind', { performancesId: performancesId, skuId: item.skuId }, function (resp) {
                if (resp.code === 0) {
                    linkedGoods.splice(idx, 1);
                    renderLinkedGoods();
                    layer.msg('已取消关联');
                } else {
                    layer.msg(resp.msg || resp.message || '操作失败', { icon: 2 });
                }
            });
        });
    }

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