<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>后台管理系统</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="shortcut icon" th:href="@{/images/logo.jpg}"/>
    <link rel="stylesheet" th:href="@{/js/layui/css/layui.css}">
    <link rel="stylesheet" th:href="@{/js/layui/css/admin.css}">

    <link rel="stylesheet" th:href="@{/js/upload_img/css/index.css}">
    <script type="text/javascript" th:src="@{/js/jquery-3.3.1.min.js}"></script>
    <script type="text/javascript" th:src="@{/js/xm-select.js}"></script>
    <script th:src="@{/js/layui/layui.js}" charset="utf-8"></script>
    <script type="text/javascript" th:src="@{/js/layui/layui.all.js}" charset="utf-8"></script>
    <link rel="stylesheet" th:href="@{/js/ueditor/themes/default/css/ueditor.css}" type="text/css"/>
    <script type="text/javascript" th:src="@{/js/ueditor/ueditor.config.js}"></script>
    <script type="text/javascript" th:src="@{/js/ueditor/ueditor.all.js}"></script>
    <script type="text/javascript" th:src="@{/js/ueditor/lang/zh-cn/zh-cn.js}"></script>
    <script src="https://s2.pstatp.com/cdn/expire-1-M/jquery/1.7.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/layui/2.5.6/layui.min.js"></script>
    <!--    <link href="https://cdn.jsdelivr.net/npm/xm-select/dist/xm-select.css" rel="stylesheet">-->
    <script type="text/javascript" th:src="@{/js/xm-select.js}" charset="utf-8"></script>

    <style>
        .layui-form-label {
            width: 120px;
        }

        #editor {
            height: 600px;
            width: 700px;
        }
    </style>

</head>
<body>
<div class="layui-form" style="padding: 20px 0 0 0;">
    <form id="formId" onsubmit="return false;">
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>活动标题</label>
            <div class="layui-input-inline">
                <input type="text" class="layui-input" name="groupBuyTitle" id="groupBuyTitle"
                       th:value="${obj.groupBuyTitle}">
            </div>
            <label class="layui-form-label"><span style="color: red">*</span>最低起送人数</label>
            <div class="layui-input-inline">
                <input type="number" step="1" class="layui-input" name="groupSize" id="groupSize"
                       th:value="${obj.groupSize}">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>团购活动有效期</label>
            <div class="layui-input-inline">
                <input type="text" class="layui-input" name="startDate" id="startDate" th:value="${obj.startDate}"
                       required="required"  lay-verify="datetime">
            </div>
            <label class="layui-form-label">至</label>
            <div class="layui-input-inline">
                <input type="text" class="layui-input" name="endDate" id="endDate" th:value="${obj.endDate}"
                       required="required"  lay-verify="datetime">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red">*</span>配送小区</label>
            <div class="layui-input-inline" id="areaIdList">
                <!--                <select name="areaIdList" id="areaIdList" xm-select="multiSelect" xm-select-skin="primary" lay-omit>-->
                <!--                    &lt;!&ndash; 选项列表 &ndash;&gt;-->
                <!--                </select>-->
            </div>
            <label class="layui-form-label">简介</label>
            <div class="layui-input-inline">
                <input type="text" class="layui-input" name="groupBlurb" id="groupBlurb"
                       th:value="${obj.groupBlurb}">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">
                <span style="color: red">*</span>团购图片
            </label>
            <div class="layui-input-inline" style="width: 700px">
                <div class="layui-upload">
                    <button type="button" class="layui-btn" id="uploadBtn"
                            lay-data="{acceptMime: 'image/jpg, image/png, image/gif, image/bmp, image/jpeg'}">上传图片
                    </button>
                    <div class="layui-upload-list">
                        <img class="layui-upload-img" id="previewImg">
                        <p id="uploadText"></p>
                        <span style="color: red">图片建议500*400px</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-card-body">
            <table class="layui-table" id="tableId" lay-data="{id: 'tableId', toolbar: '#toolbarUtil', even: true, height: 'full-400', page: false, limit: 9999, cols: [[
                {field: 'id', title: '编码'},
                {field: 'sshortpic', title: '头图'},
                {field: 'sname', title: '名称'},
                {field: 'catalogName', title: '分类'},
                {field: 'doldprice', title: '原价'},
                {field: 'dsaleprice', title: '售价'},
                {field: 'productPrice', title: '价格'},
                {field: '', width: 100, title: '操作', toolbar: '#table-handle', fixed: 'right'}
            ]]}" lay-filter="tableId"></table>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"><span style="color: red"></span>团购详情</label>
            <div class="layui-input-inline" id="groupDetail" style="width:70%">

                <script id="editor" name="groupDetail" th:utext="${obj.groupDetail}" type="text/plain"
                        style="width:100%;height:500px;"></script>

            </div>
        </div>

        <button class="layui-btn" style="display: none;" id="saveBtn" onclick="save()">保存</button>
    </form>
</div>
<script type="text/html" id="toolbarUtil">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn" lay-event="add">添加商品</button>
    </div>
</script>
<script type="text/html" id="table-handle">
    <i class="layui-icon  layui-icon-delete" lay-event="del" title="删除"></i>
</script>
<script type="text/html" id="priceTpl">
    <input type="text" name="productPrice" value="{{d.productPrice}}" lay-event="editPrice">
</script>
<script type="text/html" id="sshortpic">
    {{#if (d.sshortpic !=null && d.sshortpic !='') { }}
    <img src="{{d.sshortpic }}">
    {{# }else if(d.sshortpic ==null || d.sshortpic ==''){ }}
    <span>无</span>
    {{# } }}
</script>
<script type="text/javascript" th:src="@{/js/upload_img/js/updateimg.js}"></script>

<script>
    var id = '[[${id}]]';
    var areaList = '[[${areaList}]]';

    var ue = UE.getEditor('editor');
    UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
    UE.Editor.prototype.getActionUrl = function (action) {
        if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage') {
            return "https://qpxdnyy.com/product/uploads";
            // return "https://127.0.0.1/goods/uploads";
        } else if (action == 'listimage') {
            return this._bkGetActionUrl.call(this, action);
        } else {
            return this._bkGetActionUrl.call(this, action);
        }
    }
    // 设置默认选中项
    var selectedValues;

    layui.use(['laydate'], function() {
        var laydate = layui.laydate;
        laydate.render({
            elem: '#endDate',
            type: 'datetime' // 设置日期时间类型，带时分秒
        });
        laydate.render({
            elem: '#startDate',
            type: 'datetime' // 设置日期时间类型，带时分秒
        });
    });
    layui.use(['form', 'jquery', 'xmSelect'], function () {
        var form = layui.form;
        var $ = layui.jquery;
        var xmSelect = layui.xmSelect;

        var item = {
            curpage: 1,
            pagesize: 99999
        };
        $.ajax({
            url: '/groupArea/findPageList',  // 替换成你的接口地址
            type: 'post',
            dataType: 'json',
            data: JSON.stringify(item),
            processData: false,
            contentType: "application/json",
            success: function (res) {
                // 渲染下拉选项
                let arr = new Array(), brr = new Array();
                if (res.data.items && res.data.items.length) {
                    res.data.items.forEach(item => {
                        arr.push({
                            name: item.areaName,
                            value: item.id
                        })
                    })
                    if ('[[${obj.areaIdList}]]') {
                        brr = JSON.parse('[[${obj.areaIdList}]]');
                    }
                }
                selectedValues = xmSelect.render({
                    el: '#areaIdList',  // 下拉框容器的 id
                    data: arr,  // 接口返回的数据，格式为 [{name: '选项1', value: 'value1'}, {name: '选项2', value: 'value2'}, ...]
                    layVerify: 'required',  // 表单验证规则，可根据需要自定义
                    initValue: brr,  // 设置初始值，格式为 ['value1', 'value2', ...]
                });
                // 渲染完成后，调用 layui 的 form.render() 方法更新渲染
                form.render();
            },
            error: function (err) {
                console.error('接口请求失败：', err);
            }
        });
    });

    var groupBuyPic;
    layui.use('upload', function () {
        var upload = layui.upload;

        //执行实例
        upload.render({
            elem: '#uploadBtn', //绑定元素
            url: 'uploads', //上传接口
            accept: 'images', //允许上传的文件类型，这里只允许上传图片
            exts: 'jpg|png|gif|bmp|jpeg', //允许上传的图片后缀名
            size: 1024 * 10, //限制文件大小，单位 KB
            acceptMime: 'image/jpg, image/png, image/gif, image/bmp, image/jpeg',
            field: 'upfile',
            before: function (obj) { //上传前回调
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#previewImg').attr('src', result); //预览图片
                });
            },
            done: function (res) { //上传完毕回调
                if (res.state === "SUCCESS") { //上传成功
                    $('#uploadText').text('上传成功');
                    groupBuyPic = res.url;
                } else { //上传失败
                    $('#uploadText').text('上传失败');
                }
            },
            error: function () { //请求异常回调
                $('#uploadText').text('网络异常');
            }
        });
    });

    var selectedData = [];

    var field;
    layui.use(['table'], function () {
        var table = layui.table;

        $(function () {
            if (id) {
                showPic('[[${obj.groupBuyPic}]]');
                showTable('[[${obj.productList}]]');
                renderTable();
            }
        });

        window.addEventListener('message', function (event) {
            selectedData.push(...event.data);
            const idSet = new Set(selectedData.map(item => item.id));
            selectedData = Array.from(idSet).map(id => selectedData.find(item => item.id === id));
            for (var i = 0; i < selectedData.length; i++) {
                selectedData[i].productPrice = selectedData[i].productPrice || selectedData[i].dsaleprice;
            }
            renderTable();
        }, false);

        function renderTable() {
            table.render({
                elem: '#tableId',
                data: selectedData,
                toolbar: '#toolbarUtil', //开启头部工具栏，并为其绑定左侧模板
                even: true,    //隔行换色
                page: false,
                limit: 9999,
                cols: [
                    [
                        {field: 'id', title: '编码'},
                        {field: 'sshortpic', title: '头图', toolbar: '#sshortpic'},
                        {field: 'sname', title: '名称'},
                        {field: 'catalogName', title: '分类'},
                        {field: 'doldprice', title: '原价'},
                        {field: 'dsaleprice', title: '售价'},
                        {
                            field: 'productPrice', title: '价格', templet: function (d) {
                                return '<input type="text" class="layui-input" value="' + d.productPrice + '" onchange="updateProductPrice(' + d.id + ', this.value)">';
                            }
                        },
                        {field: '', width: 100, title: '操作', toolbar: '#table-handle', fixed: 'right'}
                    ]
                ]
            });
        }

        //头工具栏事件
        table.on('toolbar(tableId)', function (obj) {
            switch (obj.event) {
                case 'add':
                    var w = ($(window).width() * 0.9);
                    var h = ($(window).height() * 0.9);
                    layer.open({
                        type: 2
                        , title: '添加商品'
                        , content: '/groupBuy/productList'
                        , area: [w + 'px', h + 'px']
                        , fix: false //不固定
                        , maxmin: true
                        , shadeClose: true
                        , shade: 0.4
                        // , btn: ['保存', '关闭']
                        , yes: function (index, layero) {
                            var body = layer.getChildFrame('body', index); //得到iframe页面层的BODY
                            var iframeBtn = body.find('#saveBtn');//得到iframe页面层的提交按钮
                            iframeBtn.click();//模拟iframe页面层的提交按钮点击
                        }
                    });
                    break;
            }
        });

        //监听行工具事件
        table.on('tool(tableId)', function (obj) {
            var data = obj.data;
            if (obj.event === 'del') {
                var oldData = table.cache["tableId"];
                oldData.splice(obj.tr.data('index'), 1);
                selectedData = oldData;
                layer.msg("删除成功", {time: 10}, function () {
                    table.reload('tableId', {data: oldData});
                });
            }
        });
    });

    // 更新商品价格
    function updateProductPrice(id, value) {
        // 根据id更新selectedData中对应商品的价格
        for (var i = 0; i < selectedData.length; i++) {
            if (selectedData[i].id === id) {
                selectedData[i].productPrice = value;
                break;
            }
        }
    }

    function save() {
        if ($("#formId input[name='groupBuyTitle']").val() == '') {
            layer.msg("活动标题不能为空!");
            return false;
        }

        if ($("#formId input[name='groupSize']").val() == '') {
            layer.msg("最低起送人数不能为空!");
            return false;
        }

        if ($("#formId input[name='startDate']").val() == '') {
            layer.msg("开始时间不能为空!");
            return false;
        }

        if ($("#formId input[name='endDate']").val() == '') {
            layer.msg("结束时间不能为空!");
            return false;
        }
        var startTime = $("#formId input[name='startDate']").val();
        var endTime = $("#formId input[name='endDate']").val();

        if (selectedValues.getValue("value").length <= 0) {
            layer.msg("配送小区不能为空!");
            return false;
        }

        if (!selectedData.length > 0) {
            layer.msg("商品不能为空!");
            return false;
        }

        var content = UE.getEditor('editor').getContent();
        if (content == '') {
            layer.msg("详情不能为空!", {icon: 5});
            return false;
        }
        var form = document.querySelector("#formId");
        var formdata = new FormData(form);
        var areaIdList = selectedValues.getValue("value");
        var products = [];
        // 遍历原数组
        for (var i = 0; i < selectedData.length; i++) {
            // 将原数组中的每个元素转化为目标数组中的对象
            var product = {
                productId: selectedData[i].id,
                productPic: selectedData[i].sshortpic,
                productName: selectedData[i].sname,
                productSduction: selectedData[i].sduction,
                productPrice: selectedData[i].productPrice,
                sunit: selectedData[i].sunit
            };
            // 将转化后的对象添加到目标数组中
            products.push(product);
        }
        // 打印目标数组
        formdata.append("groupDetail", content);
        var goodsImgArr = [dataArr.length];
        for (var i = 0; i < dataArr.length; i++) {
            goodsImgArr[i] = dataArr[i].base64;
        }
        // formdata.append("goodsImgArr", goodsImgArr);
        formdata.append("id", id);

        var groupBuy = JSON.stringify(
            Array.from(formdata.entries()).reduce((data, [key, value]) => {
                data[key] = value;
                return data;
            }, {})
        );
        groupBuy = JSON.parse(groupBuy)
        groupBuy.areaIdList = areaIdList;
        groupBuy.products = products;
        groupBuy.goodsImgArr = goodsImgArr;
        groupBuy.groupBuyPic = groupBuyPic;
        // groupBuy.groupBuyPic = "https://yuezhi-1314984551.cos.ap-shanghai.myqcloud.com/register/0f2f3ca914fa4e36ad644f61a3a3a243.jpeg";
        groupBuy.startTime = startTime;
        groupBuy.endTime = endTime;
        $.ajax({
            url: "addOrUpdate",
            data: JSON.stringify(groupBuy),
            type: "POST",
            dataType: "json",
            processData: false,
            contentType: "application/json",
            success: function (result) {
                if (result.code == 100) {
                    closeLayer();
                    parent.layui.table.reload('tableId');
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });

    }


    function showImg(goodsImgs) {

        var arr = goodsImgs.split(",");
        var imgMsg = {
            name: randomString(5), //获取文件名
            base64: arr[i], //reader.readAsDataURL方法执行完后，base64数据储存在reader.result里
        }
        dataArr.push(imgMsg);
        currentReViewImgIndex = i;
        var showui = document.getElementById("showui");

        result = '<div class="showdiv"><img class="left" src="/js/upload_img/img/Arrow_left.svg" /><img class="center" src="/js/upload_img/img/delete.svg" /><img class="right" src="/js/upload_img/img/Arrow_right.svg" /></div><img id="img' + currentReViewImgIndex + randomString(1) + randomString(2) + randomString(5) + '" class="showimg" src="' + arr[0] + '" />';
        var li = document.createElement('li');
        li.innerHTML = result;
        showui.replaceChild(li);
    }

    function showPic(groupPic) {
        groupBuyPic = groupPic;
        $('#previewImg').attr('src', groupPic);
    }

    function showTable(products) {
        const newStr = products.replace(/&quot;/g, '"');
        selectedData = JSON.parse(newStr)
        for (var i = 0; i < selectedData.length; i++) {
            selectedData[i].productPrice = selectedData[i].productPrice || '';
        }
    }

    layui.use('form', function () {
        var form = layui.form;
        form.render();
    });


    function closeLayer() {
        //关闭当前frame
        parent.layer.close(parent.layer.getFrameIndex(window.name));
    }


    function chioceImage(i) {
        $('#file' + i).trigger("click");
    }


</script>
</body>

</html>
