<?php defined('EM_ROOT') || exit('access denied!'); ?>
<link rel="stylesheet" type="text/css" href="./views/css/views/goods.css?t=<?= Option::EM_VERSION_TIMESTAMP ?>">
<style>
    .post-type{
        display: <?= $goods['type'] == 'post' ? 'block' : 'none' ?>
    }
</style>
<div class="padding: 20px 0px;">

    <div class="layui-tabs" style="margin-top: 20px; margin-bottom: 12px;" lay-options="{}">
        <ul class="layui-tabs-header">
            <li lay-id="aaa" class="layui-this">基础信息</li>
            <li lay-id="bbb">规格信息</li>
            <li lay-id="ccc">商品详情</li>
            <li lay-id="ddd">附加选项</li>
            <li lay-id="eee">营销设置</li>
            <li lay-id="fff">其他设置</li>
        </ul>
        <form class="layui-form" id="form" method="post" action="goods_save.php">
            <input type="hidden" name="goods_id" value="<?= $goods['id'] ?>" />
            <input name="token" id="token" value="<?= LoginAuth::genToken() ?>" type="hidden"/>
            <div class="layui-tabs-body">
                <div class="layui-tabs-item layui-show">
                    <div class="layui-form-item">
                        <label class="layui-form-label">商品类型</label>
                        <?php if($action == 'edit'): ?>
                            <input type="hidden" name="type" value="<?= $goods['type'] ?>" />
                        <?php endif; ?>
                        <div class="layui-input-block">
                            <input <?= $action == 'edit' ? 'disabled' : '' ?> type="radio" name="type" value="duli" <?= $goods['type'] == 'duli' || $action == 'release' ? 'checked' : '' ?> title="一次性卡密">
                            <input <?= $action == 'edit' ? 'disabled' : '' ?> type="radio" name="type" value="guding" <?= $goods['type'] == 'guding' ? 'checked' : '' ?> title="固定通用卡密">
                            <input <?= $action == 'edit' ? 'disabled' : '' ?> type="radio" name="type" value="xuni" <?= $goods['type'] == 'xuni' ? 'checked' : '' ?> title="虚拟服务类型">
                            <input <?= $action == 'edit' ? 'disabled' : '' ?> type="radio" name="type" value="post" <?= $goods['type'] == 'post' ? 'checked' : '' ?> title="自定义接口URL/POST">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">商品分类</label>
                        <div class="layui-input-block">
                            <select name="sort_id">
                                <option value="">选择分类</option>
                                <?php
                                    foreach ($sorts as $key => $value):
                                        if ($value['pid'] != 0) {
                                            continue;
                                        }
                                        $flg = $value['sid'] == $goods['sort_id'] ? 'selected' : '';
                                ?>
                                    <option value="<?= $value['sid'] ?>" <?= $flg ?>><?= $value['sortname'] ?></option>
                                    <?php
                                        $children = $value['children'];
                                        foreach ($children as $key):
                                            $value = $sorts[$key];
                                            $flg = $value['sid'] == $goods['sort_id'] ? 'selected' : '';
                                    ?>
                                        <option value="<?= $value['sid'] ?>" <?= $flg ?>>&nbsp; &nbsp; &nbsp; <?= $value['sortname'] ?></option>
                                    <?php
                                        endforeach;
                                        endforeach;
                                    ?>
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">商品名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="title" class="layui-input" value="<?= $goods['title'] ?>">
                        </div>
                    </div>

                    <div class="layui-form-item post-type">
                        <label class="layui-form-label">URL</label>
                        <div class="layui-input-block">
                            <input name="post_url" id="" type="text" class="layui-input" placeholder="请输入访问的URL" value="<?= $goods['post_url'] ?>">
                        </div>

                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">封面图</label>
                        <div class="layui-input-block">
                            <div class="layui-input-group" style="width: 100%; display: flex;">
                                <input type="text" value="<?= $goods['cover'] ?>" placeholder="封面图" class="layui-input" name="cover" id="sortimg">
                                <div id="ID-upload-demo-btn" class="layui-input-split layui-input-suffix layui-btn" style="display: table-cell; line-height: 192%;">
                                    上传图片
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
                <div class="layui-tabs-item">
                    <div class="fairy-form form mt-4">
                        <!--商品规格选项-->
                        <div id="fairy-is-attribute"></div>
                        <!--商品类型选择-->
                        <div id="fairy-product-type"></div>
                        <!--商品属性表-->
                        <div id="fairy-attribute-table"></div>
                        <!--商品规格表-->
                        <div id="fairy-spec-table"></div>
                        <!--商品库存表-->
                        <div id="fairy-sku-table"></div>
                    </div>
                </div>
                <div class="layui-tabs-item">
                    <div class="layui-form-item">
                        <label class="layui-form-label">简介内容</label>
                        <div class="layui-input-block">
                            <textarea class="layui-textarea" name="des"><?= $goods['des'] ?></textarea>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">商品详情</label>
                        <div class="layui-input-block">
                            <textarea class="basic-example" name="content"><?= $goods['content'] ?></textarea>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">订单详情页额外显示内容</label>
                        <div class="layui-input-block">
                            <textarea class="basic-example" name="pay_content"><?= $goods['pay_content'] ?></textarea>
                        </div>
                    </div>
                </div>
                <div class="layui-tabs-item">
                    <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-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="attach_user" id="jsonOutput" class="form-control" readonly></textarea>
                        </div>
                    </div>
                </div>
                <div class="layui-tabs-item">
                    <div class="layui-form-item">
                        <label class="layui-form-label">配置批量购买，单价优惠</label>
                        <div id="keyValueContainer">
                            <?php if(empty($discount)): ?>
                            <div class="kv-item">
                                <div class="layui-input-inline">
                                    <input step="1" name="discount[number][]" type="number" class="key-input kv-input layui-input" placeholder="购买数量" />
                                </div>
                                <div class="layui-input-inline">
                                    <input step="0.01" name="discount[amount][]" type="number" class="value-input kv-input layui-input" placeholder="每一件优惠金额" />
                                </div>
                                <button type="button" class="kv-btn delete-btn layui-btn layui-bg-red" title="删除"><i class="fa fa-trash-o"></i></button><button type="button" class="kv-btn add-btn layui-btn layui-bg-blue btn-sm btn-add" title="添加"><i class="fa fa-plus"></i></button>

                            </div>

                            <?php else: ?>
                                <?php foreach($discount as $val): ?>
                                <div class="kv-item">
                                    <div class="layui-input-inline">
                                        <input value="<?= $val['quantity'] ?>" step="1" name="discount[number][]" type="number" class="key-input kv-input layui-input" placeholder="购买数量" />
                                    </div>
                                    <div class="layui-input-inline">
                                        <input value="<?= $val['amount'] / 100 ?>" step="0.01" name="discount[amount][]" type="number" class="value-input kv-input layui-input" placeholder="每一件优惠金额" />
                                    </div>
                                    <button type="button" class="kv-btn delete-btn btn danger btn-sm layui-btn layui-bg-red" title="删除"><i class="fa fa-trash-o"></i></button><button type="button" class="kv-btn add-btn btn primary btn-sm btn-add layui-btn layui-bg-blue" title="添加"><i class="fa fa-plus"></i></button>
                                </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">销量</label>
                        <div class="layui-input-block">
                            <input type="number" name="sales" class="layui-input" value="<?= $goods['sales'] ?>">
                        </div>
                    </div>
                </div>
                <div class="layui-tabs-item">
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <input type="checkbox" value="1" name="is_on_shelf" title="上架" <?= $goods['is_on_shelf'] == 1 ? 'checked' : '' ?>>
                        </div>
                        <div class="layui-input-block">
                            <input type="checkbox" value="1" name="index_top" title="首页置顶" <?= $goods['index_top'] == 1 ? 'checked' : '' ?>>
                        </div>
                        <div class="layui-input-block">
                            <input type="checkbox" value="1" name="sort_top" title="分类置顶" <?= $goods['sort_top'] == 1 ? 'checked' : '' ?>>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">排序</label>
                        <div class="layui-input-block">
                            <input type="number" name="sort_num" class="layui-input" value="<?= $goods['sort_num'] ?>">
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-input-block" style="margin: 0 auto;">
                <button type="submit" class="layui-btn" lay-submit lay-filter="submit">保存</button>
                <button type="button" class="layui-btn layui-btn-primary">取消</button>
            </div>
        </form>
    </div>


</div>


<script src="./views/js/dropzone.min.js?t=<?= Option::EM_VERSION_TIMESTAMP ?>"></script>
<script src="./views/js/media-lib.js?t=<?= Option::EM_VERSION_TIMESTAMP ?>"></script>


<script src="./views/components/lay-module/sortable.js?t=<?= Option::EM_VERSION_TIMESTAMP ?>"></script>
<script src="./views/components/lay-module/skuTable.js?t=<?= Option::EM_VERSION_TIMESTAMP ?>"></script>

<script src="./tinymce/js/tinymce/tinymce.min.js?t=<?= Option::EM_VERSION_TIMESTAMP ?>"></script>

<script src="./views/js/views/goods.js?t=<?= Option::EM_VERSION_TIMESTAMP ?>"></script>


<script>
    layui.use(['form', 'laydate', 'util'], function(){
        var $ = layui.$;
        var form = layui.form;
        var upload = layui.upload;
        var element = layui.element;
        form.on('submit(submit)', function(data){
            var field = data.field; // 获取表单全部字段值
            var url = $('#form').attr('action');
            $.ajax({
                type: "POST",
                url: url,
                data: field,
                dataType: "json",
                success: function (e) {
                    location.href = "goods.php"
                },
                error: function (xhr) {
                    layer.msg(JSON.parse(xhr.responseText).msg);
                }
            });
            return false; // 阻止默认 form 跳转
        });


        var uploadInst = upload.render({
            elem: '#ID-upload-demo-btn',
            field: 'image',
            url: './article.php?action=upload_cover', // 实际使用时改成您自己的上传接口即可。
            before: function(obj){
                // 预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $('#ID-upload-demo-img').attr('src', result); // 图片链接（base64）
                });

                element.progress('filter-demo', '0%'); // 进度条复位
                loadIndex = layer.load(2);
            },
            done: function(res){
                // 若上传失败
                if(res.code > 0){
                    return layer.msg('上传失败');
                }
                // 上传成功的一些操作
                if(res.code == 0){
                    $('#sortimg').val(res.data)
                }
                $('#ID-upload-demo-text').html(''); // 置空上传失败的状态
            },
            error: function(){
                // 演示失败状态，并实现重传
                var demoText = $('#ID-upload-demo-text');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst.upload();
                });
            },
            // 进度条
            progress: function(n, elem, e){
                element.progress('filter-demo', n + '%'); // 可配合 layui 进度条元素使用
                if(n == 100){
                    layer.close(loadIndex)
                }
            }
        });



    })
</script>


<script>

    const memberLevels = <?= json_encode($members) ?>;

    var form = $('#addgoods');

    var thed = [
        {title: '游客访问(元)', icon: 'icon-edit'},
        {title: '登录用户(元)', icon: 'icon-edit'},
        {title: '市场价(元)', icon: 'icon-edit'},
        {title: '成本价(元)', icon: 'icon-edit'},
    ];
    // 循环会员等级数组，生成对应的对象并添加到thed中
    memberLevels.forEach((level, index) => {
        thed.splice(2 + index, 0, {
            title: `${level.name}(元)`,
            icon: 'icon-edit'
        });
    });

    var tbody = [
        {type: 'input', field: 'guest_price', value: ''},
        {type: 'input', field: 'user_price', value: ''},
        {type: 'input', field: 'market_price', value: ''},
        {type: 'input', field: 'cost_price', value: '0'},
    ];

    // 循环会员等级数组，生成对应的对象并添加到thed中

    memberLevels.forEach((level, index) => {

        tbody.splice(2 + index, 0, {
            type: 'input',
            field: `member_${level.id}`,
            value: ''
        });
    });

    console.log(tbody)
    <?php if($action == 'edit'): ?>
        var tbody2 = [ // 单规格
            {type: 'input', field: 'skus[guest_price]', value: "<?= $goods['skus'][0]['guest_price'] /100 ?>"},
            {type: 'input', field: 'skus[user_price]', value: "<?= $goods['skus'][0]['user_price'] /100 ?>"},
            {type: 'input', field: 'skus[market_price]', value: "<?= $goods['skus'][0]['market_price'] /100 ?>"},
            {type: 'input', field: 'skus[cost_price]', value: "<?= $goods['skus'][0]['cost_price'] /100 ?>"},
        ];

        var member_price = JSON.parse('<?= $goods['skus_json'] ?>')[0].member_prices;

        memberLevels.forEach((level, index) => {

            // 查找当前会员等级对应的价格数据
            const priceData = member_price.find(price => price.member_level == level.id);


            tbody2.splice(2 + index, 0, {
                type: 'input',
                field: `skus[member][${level.id}]`,
                value: priceData ? priceData.price.toString() / 100: '' // 有价格则显示，否则为空
            });
        });
    <?php endif; ?>

    <?php if($action == 'release'): ?>
        var tbody2 = [ // 单规格
            {type: 'input', field: 'skus[guest_price]', value: ""},
            {type: 'input', field: 'skus[user_price]', value: ""},
            {type: 'input', field: 'skus[market_price]', value: ""},
            {type: 'input', field: 'skus[cost_price]', value: ""},
        ];
        memberLevels.forEach((level, index) => {
            tbody2.splice(2 + index, 0, {
                type: 'input',
                field: `skus[member][${level.id}]`,
                value: ''
            });
        });
    <?php endif; ?>

    var options = {
        isAttributeElemId: 'fairy-is-attribute',
        productTypeElemId: 'fairy-product-type',
        attributeTableElemId: 'fairy-attribute-table',
        specTableElemId: 'fairy-spec-table',
        skuTableElemId: 'fairy-sku-table',
        //商品规格模式 0单规格 1多规格
        mode: "<?= $goods['is_sku'] == 'y' ? 1 : 0 ?>",
        //是否开启sku表行合并
        rowspan: true,
        //图片上传接口
        uploadUrl: './json/upload.json',
        //获取商品类型接口
        productTypeUrl: '?action=goods_type_data',
        //获取商品类型下的规格和属性接口
        attrSpecUrl: '?action=attr_spec_data',
        //创建规格接口
        specCreateUrl: '?action=create_spec',
        //删除规格接口
        specDeleteUrl: './json/specD    elete.json',
        //创建规格值接口
        specValueCreateUrl: '?action=create_spec_value',
        //删除规格值接口
        specValueDeleteUrl: './json/specValueDelete.json',
        //单规格SKU表配置
        singleSkuTableConfig: {
            thead: thed,
            tbody: tbody2
        },
        //多规格SKU表配置
        multipleSkuTableConfig: {
            thead: thed,
            tbody: tbody
        },
        // ========================================== 回显时相关配置参数 ========================================== //
        //商品id
        goods_id: "<?php echo $goods['id'] ?>",
        //商品类型id
        productTypeId: "<?= isset($goods['attr_id']) ? $goods['attr_id'] : '' ?>",
        //sku数据接口
        skuDataUrl: '?action=sku_data',
    }

    var skuTableObj = new SkuTable(options);

    form.on('submit', function (data) {

        console.log(data)

        //获取表单数据
        console.log(data.field);

        // return false;

        if (skuTableObj.getMode() == 0) {
            //单规格
            // layer.alert(JSON.stringify(data.field), {title: '提交的数据'});
        } else {
            //多规格
            var state = Object.keys(data.field).some(function (item, index, array) {
                return item.startsWith('skus');
            });
            // state ? layer.alert(JSON.stringify(data.field), {title: '提交的数据'}) : layer.msg('sku表数据不能为空', {icon: 5, anim: 6});
        }

        return true;
    });

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

<!--附加选项-->
<script>
    let keyValuePairs = <?= $goods['attach_user'] ? $goods['attach_user'] : '{}' ?>;

    console.log(keyValuePairs)

    // 添加键值对
    $('#addBtn').click(function() {
        const key = $('#keyInput').val().trim();
        const value = $('#valueInput').val().trim();

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

        // 更新或添加键值对
        keyValuePairs[key] = value;
        updateKeyValueList();
        updateJsonOutput();

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

        layer.msg('附加选项已添加');
    });

    // 清空所有键值对
    $('#clearBtn').click(function() {
        if (Object.keys(keyValuePairs).length === 0) {
            layer.msg('列表已为空');
            return;
        }

        if (confirm('确定要清空所有附加选项吗？')) {
            keyValuePairs = {};
            updateKeyValueList();
            updateJsonOutput();
            layer.msg('已清空所有附件选项')
        }
    });



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

    // 更新键值对列表
    function updateKeyValueList() {
        const listContainer = $('#keyValueList');
        listContainer.empty();

        if (Object.keys(keyValuePairs).length === 0) {
            listContainer.append('<div class="text-muted text-center py-4" id="emptyListPlaceholder">暂无附加选项，请添加</div>');
            return;
        }

        Object.entries(keyValuePairs).forEach(([key, value]) => {
            const item = $(`
                <blockquote class="layui-elem-quote">
                    ${escapeHtml(key)} <span class="delete-btn text-danger" data-key="${escapeHtml(key)}">
                            <i class="fa fa-times-circle"></i>
                        </span><br>
                    ${escapeHtml(value)}
                </blockquote>
                    `);

            // 添加删除事件
            item.find('.delete-btn').click(function() {
                const keyToDelete = $(this).data('key');
                delete keyValuePairs[keyToDelete];
                updateKeyValueList();
                updateJsonOutput();
                layer.msg(`已删除附加选项: ${keyToDelete}`)
            });

            listContainer.append(item);
        });
    }

    // 更新JSON输出
    function updateJsonOutput() {
        const jsonOutput = $('#jsonOutput');
        const jsonString = JSON.stringify(keyValuePairs, 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);
    }

    // 页面加载时更新列表和JSON输出
    updateKeyValueList();
    updateJsonOutput();

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