<?php defined('EM_ROOT') || exit('access denied!'); ?>


<div style="padding: 20px 0px;">
    <div class="layui-tabs" style="margin-bottom: 12px;" lay-options="{trigger: false}">
        <ul class="layui-tabs-header">
            <li><a href="./shop.php">基础设置</a></li>
            <li><a href="./shop.php?action=gg">公告设置</a></li>
            <li class="layui-this"><a href="./shop.php?action=btx">下单必填项</a></li>
        </ul>
    </div>
    <div class="layui-panel">
        <div style="padding: 20px;">
            <form action="shop.php?action=btx_save" method="post" name="setting_form" id="setting_form" class="layui-form">
                <div class="layui-form-item">
                    <label class="layui-form-label">设置下单必填项</label>
                    <div class="layui-input-inline">
                        <input type="text" class="layui-input" id="keyInput" placeholder="请输入名称">
                    </div>
                    <div class="layui-input-inline">
                        <input type="text" class="layui-input" id="valueInput" placeholder="请输入提示内容">
                    </div>
                    <div class="layui-input-inline">
                        <select id="typeInput">
                            <option value="string" selected>字符串</option>
                            <option value="tel">手机号</option>
                            <option value="email">邮箱</option>
                            <option value="num">数字</option>
                        </select>
                    </div>
                    <div class="layui-text-em">
                        <span id="addBtn" class="layui-btn layui-bg-blue">添加</span>
                        <span id="clearBtn" class="layui-btn layui-btn-primary layui-border">清空</span>
                    </div>
                </div>


                <div class="layui-form-item">
                    <label class="layui-form-label">已添加的下单必填项</label>
                    <div id="keyValueList">
                        <!-- 键值对将在这里动态添加 -->
                        <div class="text-muted py-4" id="emptyListPlaceholder">
                            暂无下单必填项，请添加
                        </div>
                    </div>
                </div>


                <div class="layui-form-item" style="display: none;">
                    <label class="font-weight-bold mb-2"><i class="fa fa-code mr-2 text-success"></i>JSON 输出</label>
                    <div class="relative">
                        <textarea name="order_required" id="jsonOutput" class="form-control" readonly></textarea>
                    </div>
                </div>


                <input name="token" id="token" value="<?= LoginAuth::genToken() ?>" type="hidden"/>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button type="submit" class="layui-btn" lay-submit lay-filter="demo1">保存设置</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>


<script>
    $(function () {
        $("#menu-system").attr('class', 'admin-menu-item has-list in');
        $("#menu-system .fa-angle-right").attr('class', 'admin-arrow fa fa-angle-right active');
        $("#menu-system > .submenu").css('display', 'block');
        $('#menu-shop > a').attr('class', 'menu-link active')

        // 提交表单
        $("#setting_form").submit(function (event) {
            event.preventDefault();
            submitForm("#setting_form");
        });
    });
</script>

<script>
    // 初始化数据为数组，每个元素包含三个字段
    let items = <?= empty($order_required) ? '[]' : $order_required ?>;

    console.log(items);

    // 添加项目
    $('#addBtn').click(function() {
        const name = $('#keyInput').val().trim();
        const placeholder = $('#valueInput').val().trim();
        var type = $('#typeInput').val();
        type = type == null ? 'string' : type;

        if (!name) {
            layer.msg('请输入名称');
            return;
        }

        // 添加新项目
        items.push({
            name: name,
            placeholder: placeholder,
            type: type
        });

        updateList();
        updateJsonOutput();

        // 清空输入框
        $('#keyInput').val('');
        $('#valueInput').val('');
        $('#typeInput').val('');
        $('#keyInput').focus();

        layer.msg('下单必填项已添加');
    });

    // 清空所有项目
    $('#clearBtn').click(function() {
        if (items.length === 0) {
            layer.msg('列表已为空');
            return;
        }

        if (confirm('确定要清空所有下单必填项吗？')) {
            items = [];
            updateList();
            updateJsonOutput();
            layer.msg('已清空所有下单必填项')
        }
    });

    // 回车键添加项目
    $('#typeInput').keypress(function(e) {
        if (e.which === 13) {
            e.preventDefault();
            $('#addBtn').click();
        }
    });

    // 更新列表
    function updateList() {
        const listContainer = $('#keyValueList');
        listContainer.empty();

        if (items.length === 0) {
            listContainer.append('<div class="text-muted py-4" id="emptyListPlaceholder">暂无下单必填项，请添加</div>');
            return;
        }

        items.forEach((item, index) => {
            const listItem = $(`
                <blockquote class="layui-elem-quote">
                    ${escapeHtml(item.name)} <span class="delete-btn text-danger" data-index="${index}">
                            <i class="fa fa-times-circle"></i>
                        </span><br>
                    ${escapeHtml(item.placeholder || '无')}<br>
                    ${escapeHtml(item.type || '未指定')}
                </blockquote>
            `);

            // 添加删除事件
            listItem.find('.delete-btn').click(function() {
                const indexToDelete = $(this).data('index');
                items.splice(indexToDelete, 1);
                updateList();
                updateJsonOutput();
                layer.msg(`已删除下单必填项: ${escapeHtml(item.name)}`)
            });

            listContainer.append(listItem);
        });
    }

    // 更新JSON输出
    function updateJsonOutput() {
        const jsonOutput = $('#jsonOutput');
        const jsonString = JSON.stringify(items, null, 2);
        jsonOutput.val(jsonString);

        // 自动调整文本区域高度
        jsonOutput.height(0);
        jsonOutput.height(jsonOutput.prop('scrollHeight'));
    }

    // 显示提示消息
    function showToast(message, type) {
        // 移除已有的toast
        $('.custom-toast').remove();

        let bgColor, icon;
        switch(type) {
            case 'success':
                bgColor = 'bg-success';
                icon = 'fa-check-circle';
                break;
            case 'warning':
                bgColor = 'bg-warning';
                icon = 'fa-exclamation-triangle';
                break;
            case 'error':
                bgColor = 'bg-error';
                icon = 'fa-times-circle';
                break;
            default:
                bgColor = 'bg-info';
                icon = 'fa-info-circle';
        }

        const toast = $(`
            <div class="custom-toast ${bgColor}">
                <i class="fa ${icon} mr-2"></i>
                <span>${message}</span>
            </div>
        `);

        $('body').append(toast);

        // 淡入
        setTimeout(() => {
            toast.addClass('show');
        }, 10);

        // 3秒后淡出
        setTimeout(() => {
            toast.removeClass('show');
            setTimeout(() => {
                toast.remove();
            }, 300);
        }, 3000);
    }

    // 转义HTML特殊字符
    function escapeHtml(text) {
        if (!text) return '';
        return text
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    // 页面加载时更新列表和JSON输出
    updateList();
    updateJsonOutput();
</script>
