<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('顶部banner')" />
    <th:block th:include="include :: bootstrap-fileinput-css" />
    <style>
        .home_page {
            display: flex;
            justify-content: center;
            padding: 20px;
        }
        .right_content {
            font-size: 16px;
            font-weight: 600;
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 50%;
        }
        .left_content {
            flex: 1;
        }
        .left_title, .right_title {
            margin-bottom: 12px;
        }
        .function_btn {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }
        .function_btn .hot_title {
            font-size: 16px;
            font-weight: 600;
        }
        .function_btn .tags {
            display: flex;
            align-items: center;
        }
        .function_btn .tags .tag {
            padding: 6px 12px 4px;
            border: 1px solid #ccc;
            border-radius: 5px;
            position: relative;
            margin-right: 12px;
        }
        .function_btn .tags .tag span {
            display: inline-block;
            position: absolute;
            top: -8px;
            right: -8px;
            width: 18px;
            height: 18px;
            line-height: 16px;
            border: 1px solid #aaa;
            border-radius: 50%;
            background: #fff;
            text-align: center;
            cursor: pointer;
        }
        .banner_list {
            display: flex;
            flex-direction: column;
        }
        .banner_item {
            border: 1px dashed #ccc;
            border-radius: 10px;
            padding: 12px;
            margin-bottom: 20px;
            position: relative;
        }
        .banner_item .del {
            position: absolute;
            right: -8px;
            top: -8px;
            width: 20px;
            height: 20px;
            line-height: 18px;
            border: 1px solid #ccc;
            border-radius: 50%;
            text-align: center;
            cursor: pointer;
        }
        .img_show, .set_method, .set_function {
            display: flex;
        }
        .title {
            font-size: 16px;
            font-weight: 600;
            width: 80px;
            text-align: right;
        }
        .kv-upload-progress {
            display: none !important;
        }
        .ibox-content .imgBox {
            width: 350px;
            max-height: 180px;
        }
        .jump, .ticket_name, .set_function_time {
            display: flex;
            flex-grow: 1;
            align-items: center;
        }
        .iptOrSelect {
            flex: 1;
        }
        #activeTags {
            display: none;
        }
    </style>
</head>
<body>
    <div class="home_page">
        <div class="left_content">
            <div class="left_title">
                <img id="testImg" src="" style="display: none;" alt="">
            </div>
            <div class="function_btn">
                <div class="hot_title">
                    展示形式：
                </div>
                <div class="tags" style="font-weight: 600;font-size: 16px;">
                    轮播
                </div>
            </div>
            <div class="function_btn" id="showMiddleBanner" style="display: none;">
                <div class="hot_title">
                    位置顺序：
                </div>
                <div class="tags" style="font-weight: 600;font-size: 16px;">
                    <input type="text" class="layui-input form-control titleIpt" id="sorting" value="" autocomplete="off" placeholder="请输入模块顺序">
                </div>
            </div>
            <div class="function_btn">
                <div class="hot_title">
                    选择照片：
                </div>
                <div id="tags" class="tags">
                    <button type="button" class="btn btn-warning" style="margin-right: 12px;" onclick="addItem(0)">添加banner</button>
                    <span id="tall">(最多允许添加10张图，宽度为764像素，高度为1018像素)</span>
                </div>
                <div id="activeTags" class="tags">
                    <span id="tall">(请上传宽度为382像素的图片！)</span>
                </div>
            </div>
            <div id="bannerList" class="banner_list">
                
            </div>
            
            <div class="footer_btn">
                <button type="button" class="btn btn-success" onclick="save()">保存</button>
            </div>
        </div>
        <!-- <div class="right_content">
            <div class="right_title">
                
            </div>
            <div class="function_area">
                <iframe id="iframe" src="http://172.16.3.82:8080/#/goods/home?place=admin" width="375" height="1190" frameborder="0"></iframe>
            </div>
        </div> -->
    </div>
    <th:block th:include="include :: footer"/>
    <th:block th:include="include :: bootstrap-fileinput-js" />
    <th:block th:include="include :: bootstrap-suggest-js" />
    <script th:inline="javascript">
        var prefix2 = ctx + "local";
        var platformUrl = [[${platformUrl}]];
        let num = 0;
        let type = 0;
        $(function(){
            let url = window.location.hostname;
            if (url.includes('test')) {
                $("#iframe").attr('src', 'https://ttestm.zhengzai.tv/#/goods/home?place=admin');
            } else if (!url.includes('test') && url.includes('admin')) {
                $("#iframe").attr('src', 'https://m.zhengzai.tv/#/goods/home?place=admin');
            } else {

            }
            promiseMethods('/front-index/list','post').then(res=>{
                let { data } = res;
                data.forEach(item => {
                    if (item.moudleName == "huDongBanner") {
                        $("#sorting").val(item.indexs)
                    }
                })
            })
            let name = 'id';
            var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            type = unescape(r[2]);
            if (type == 2) {
                $("#tall").html('');
                $("#tags").hide();
                $("#activeTags").show();
            } else {
                type = 1
                $("#tags").show();
                $("#activeTags").hide();
            }
            let data = {
                type
            }
            promiseMethods('/frontBanner/list', 'post', data).then(res => {
                let { data } = res;
                if (data.length <= 0) {
                    addItem();
                }
                for (var i = 0; i < data.length; i++) {
                    num++
                    let str = `<div class="banner_item" id="banner_item${i+1}" data-createTime="${data[i].createTime}" data-startTime="${data[i].startTime}" data-upData="${data[i].updateTime}" data-endTime="${data[i].endTime}" data-id="${data[i].bannerId}" data-mid="${data[i].mid}">
                        <span class="del" onclick="delItem('${i+1}', '${data[i].mid}')">x</span>
                        <div class="img_show">
                            <div class="title">
                                图片展示：
                            </div>
                            <div class="ibox-content" style="border: none;">
                                <img id="viewImg${i+1}" class="imgBox" src="${data[i].picUrl}" alt="">
                                <div class="form-group">
                                    <div class="file-loading">
                                        <input id="fileinput${i+1}" type="file" name="file" data-browse-on-zone-click="true" data-theme="fas">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="set_method" style="margin-bottom: 20px;">
                            <div class="jump">
                                <div class="title">
                                    跳转方式：
                                </div>
                                <div class="iptOrSelect" style="margin-right: 12px;">
                                    <select id="jumpSelect${i+1}" onchange="changeJump(this)" class="type form-control" data-first-title="请选择">
                                        <option value="1">票务</option>
                                        <option value="2">H5</option>
                                        <option value="3">商品</option>
                                    </select>
                                </div>
                            </div>
                            <div class="ticket_name">
                                <div class="title">
                                    <span class="change${i+1}">票务名称</span>：
                                </div>
                                <div class="input-group iptOrSelect shwoSelect${i+1}"">
                                    <input id="ticketName${i+1}" type="text" data-id="${data[i].ticketId}" value="${data[i].ticketName}" class="form-control storeList suggestIpt${i+1} quzhi" onFocus="focusMethod(this)" placeholder="请输入查询信息">
                                    <div class="input-group-btn">
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                        </ul>
                                    </div>
                                </div>
                                <div class="input-group iptOrSelect shwoSelectTwo${i+1}"" style="dispaly:none;">
                                    <input id="ticketNames${i+1}" type="text" data-id="${data[i].ticketId}" value="${data[i].ticketName}" class="form-control storeList2 suggestIpt${i+1} quzhi" onFocus="focusMethod(this)" placeholder="请输入查询信息">
                                    <div class="input-group-btn">
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                        </ul>
                                    </div>
                                </div>
                                <div class="iptOrSelect shwoH5${i+1}" style="display:none;">
                                    <input id="ticketName${i+1}" data-id="${data[i].ticketId}" value="${data[i].ticketName}" type="text" class="layui-input form-control h5Url quzhi" placeholder="请输入活动链接">
                                </div>
                            </div>
                        </div>
                        <div class="set_function">
                            <div class="set_function_time">
                                <div class="title">
                                    时间设置：
                                </div>
                                <div class="select_tiem" style="display:flex;">
                                    <input type="text" class="layui-input form-control timeStart" id="startTime${i+1}" value="${data[i].startTime || ''}" autocomplete="off" placeholder="配置活动时间">
                                    <input type="text" class="layui-input form-control timeEnd" id="endTime${i+1}" value="${data[i].endTime || ''}" autocomplete="off" placeholder="配置活动时间">
                                </div>
                            </div>
                            <div class="set_function_time pxBox" style="width: 40%;">
                                <div class="title">
                                    排序：
                                </div>
                                <div class="select_tiem">
                                    <input id="px${i+1}" type="text" class="layui-input form-control px" value="${data[i].indexs}" placeholder="请输入顺序数字">
                                </div>
                            </div>
                        </div>
                    </div>`;
                    $("#bannerList").append(str);
                    let type = data[i].jumpType;
                    $("#jumpSelect"+(i+1)+" option[value="+type+"]").attr('selected','selected');
                    typeJump(type, i+1)
                    common(num)
                }
                if (type == 2) {
                    $('.del').hide();
                    $('.pxBox').hide();
                }
            })
            // 
        })
        function addItem (index) {
            if (num == 10) {
                return layer.msg('最多可添加10张图片')
            }
            num++
            let str = `<div class="banner_item" id="banner_item${num}" data-createTime="" data-startTime="" data-upData="" data-endTime="" data-id="" data-mid="">
                        <span class="del" onclick="delItem('${num}', '')">x</span>
                        <div class="img_show">
                            <div class="title">
                                图片展示：
                            </div>
                            <div class="ibox-content" style="border: none;">
                                <img id="viewImg${num}" class="imgBox" src="" alt="">
                                <div class="form-group">
                                    <div class="file-loading">
                                        <input id="fileinput${num}" type="file" name="file" data-browse-on-zone-click="true" data-theme="fas">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="set_method" style="margin-bottom: 20px;">
                            <div class="jump">
                                <div class="title">
                                    跳转方式：
                                </div>
                                <div class="iptOrSelect" style="margin-right: 12px;">
                                    <select id="jumpSelect${num}" onchange="changeJump(this)" class="type form-control" data-first-title="请选择">
                                        <option value="1">票务</option>
                                        <option value="2">H5</option>
                                        <option value="3">商品</option>
                                    </select>
                                </div>
                            </div>
                            <div class="ticket_name">
                                <div class="title">
                                    <span class="change${num}">票务名称</span>：
                                </div>
                                <div class="input-group iptOrSelect shwoSelect${num}"">
                                    <input id="ticketName${num}" data-id="" value="" type="text" class="form-control storeList quzhi" onFocus="focusMethod(this)" placeholder="请输入查询信息">
                                    <div class="input-group-btn">
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                        </ul>
                                    </div>
                                </div>
                                <div class="input-group iptOrSelect shwoSelectTwo${num}"" style="display:none">
                                    <input id="ticketNames${num}" data-id="" value="" type="text" class="form-control storeList2 quzhi" onFocus="focusMethod(this)" placeholder="请输入查询信息">
                                    <div class="input-group-btn">
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                        </ul>
                                    </div>
                                </div>
                                <div class="iptOrSelect shwoH5${num}" style="display:none;">
                                    <input id="ticketName${num}" data-id="" value="" type="text" class="layui-input form-control h5Url quzhi" placeholder="请输入活动链接">
                                </div>
                            </div>
                        </div>
                        <div class="set_function">
                            <div class="set_function_time">
                                <div class="title">
                                    时间设置：
                                </div>
                                <div class="select_tiem" style="display:flex;">
                                    <input type="text" class="layui-input form-control timeStart" id="startTime${num}" autocomplete="off" placeholder="配置活动时间">
                                    <input type="text" class="layui-input form-control timeEnd" id="endTime${num}" autocomplete="off" placeholder="配置活动时间">
                                </div>
                            </div>
                            <div class="set_function_time pxBox" style="width: 40%;">
                                <div class="title">
                                    排序：
                                </div>
                                <div class="select_tiem">
                                    <input id="px${num}" type="text" class="layui-input form-control px" placeholder="请输入顺序数字">
                                </div>
                            </div>
                        </div>
                    </div>`;
            $("#bannerList").append(str);
            common(num)
            bsSuggestCommon(num)
            if (type == 2) {
                $('.del').hide();
                $('.pxBox').hide();
            }
        }
        function save () {
            let obj = {};
            let itmeLength = $(".banner_item");
            
            let data = []
            Array.prototype.forEach.call(itmeLength,function (item,index,arr) {
                obj.activityUrl = item.querySelector('.h5Url').value;
                obj.bannerId = item.getAttribute('data-id');
                obj.bannerType = type;
                obj.createTime = item.getAttribute('data-createTime');
                obj.delTag = '0';
                obj.endTime = item.getAttribute('data-endTime');
                obj.indexs = item.querySelector('.px').value;
                obj.jumpType = item.querySelector('#jumpSelect'+(index+1)+'').value;
                obj.mid = item.getAttribute('data-mid') || 0; // 
                obj.picUrl = item.querySelector('.imgBox').getAttribute('src');
                obj.startTime = item.querySelector('.timeStart').value;
                obj.endTime = item.querySelector('.timeEnd').value;
                // obj.updateTime = item.getAttribute('data-upData');
                if (item.querySelector('#jumpSelect'+(index+1)+'').value == 2) {
                    obj.ticketId = item.querySelector('.h5Url').getAttribute('data-id');
                    obj.ticketName = item.querySelector('.h5Url').value;
                } else if (item.querySelector('#jumpSelect'+(index+1)+'').value == 3) {
                    obj.ticketId = item.querySelector('.storeList2').getAttribute('data-id');
                    obj.ticketName = item.querySelector('.storeList2').value;
                } else {
                    obj.ticketId = item.querySelector('.storeList').getAttribute('data-id');
                    obj.ticketName = item.querySelector('.storeList').value;
                }
                data.push({...obj})
            });//foreach js6章封装的方法
            promiseMethods('/frontBanner/updateOrCreate', 'post', JSON.stringify(data), 'application/json').then(res => {
                // if (type == 2) {
                    let data = {
                        "mid": 1,
                        "moudleIndexId": "708753099180072962244503",
                        "moudleName": "huDongBanner",
                        "indexs": $("#sorting").val(),
                        "updateTime": "2022-01-06 13:52:22",
                        "createTime": "2022-01-06 13:52:19",
                        "delTag": 0,
                        "status": 0
                    };
                    return promiseMethods('/front-index/update', 'post', JSON.stringify(data), 'application/json')
                // }
            }).then(res => {
                layer.msg("保存成功！")
                $.operate.successCallback(res);
            })
            
        }
        function focusMethod(e) {
            
        }
        function delItem (num, mid) {
            if (mid) {
                let data = {
                    mid
                }
                promiseMethods('/frontBanner/delete','post',JSON.stringify(data),'application/json').then(res => {
                    if (res.code == 0) {
                        layer.msg('删除成功！');
                    } else {
                        layer.msg('删除失败！');
                        refreshItem()
                    }
                })
            }
            $('#banner_item'+num+'').remove();
        }
        function changeJump(e) {
            let index = $(e).attr('id').replace(/[^\d]/g,''); // 选中的是第几组
            let jumpType = $(e).val(); // 选中的跳转类型
            typeJump(jumpType, index)
        }
        function bsSuggestCommon(index) {
            // let index = $(e).attr('id').replace(/[^\d]/g,''); // 选中的是第几组
            let url = '';
            let type = document.querySelector('#jumpSelect'+(index)+'').value;
            let idField = '';
            let keyField = '';
            let effectiveFields = [];
            let dom = ''
            if (type == 1) {
                url = '/kylin/performances/recommend/performance/status?pageNum=1&pageSize=50&status=(3,6,7,8,9,10)&title=';
                idField = 'performancesId';
                keyField = 'title';
                effectiveFields[0] = 'title';
                dom = 'storeList'
            } else if (type == 3) {
                url = '/compilations/goodsList?name=';
                idField = 'spuId';
                keyField = 'name';
                effectiveFields[0] = 'name';
                dom = 'storeList2'
            }
            $('.'+dom+'').bsSuggest('init', {
                idField,                 // data.value 的第几个数据，作为input输入框的内容
	            keyField,                // data.value 的第几个数据，作为input输入框的内容
                allowNoKeyword: false, //是否允许无关键字时请求数据
                showBtn:false,
                multiWord: true, //以分隔符号分割的多关键字支持
                hideOnSelect: true,
                getDataMethod: "url", //获取数据的方式，总是从 URL 获取
                url,
                effectiveFields,
                /*如果从 url 获取数据，并且需要跨域，则该参数必须设置*/
                processData: function (json) { // url 获取数据时，对数据的处理，作为 getData 的回调函数
                    //字符串转化为 js 对象
                    if (type == 1) {
                        return json;
                    } else if (type == 3) {
                        let data = {};
                        data.value = json.data
                        return data
                    }
                }
            })
        }
        function typeJump (jumpType, index) {
            switch(jumpType.toString()) {
                case '1':
                    $('.shwoH5'+index+'').hide();
                    $('.shwoSelect'+index+'').show();
                    $('.shwoSelectTwo'+index+'').hide();
                    $(".change"+index+"").text('票务名称');
                    bsSuggestCommon(index)
                    break;
                case '2':
                    $(".change"+index+"").text('活动链接');
                    $('.shwoH5'+index+'').show();
                    $('.shwoSelect'+index+'').hide();
                    $('.shwoSelectTwo'+index+'').hide();
                    break;
                case '3':
                    $('.shwoH5'+index+'').hide();
                    $('.shwoSelect'+index+'').hide();
                    $('.shwoSelectTwo'+index+'').show();
                    $(".change"+index+"").text('商品名称');
                    bsSuggestCommon(index)
                    break;
                default:
                    $('.shwoH5'+index+'').hide();
                    $('.shwoSelect'+index+'').show();
                    $(".change"+index+"").text('商品集合');
            }
        }
        function common (num) {
            layui.use('laydate', function(){
                var laydate = layui.laydate;
                //执行一个laydate实例
                laydate.render({
                    elem: `#startTime${num}`, //指定元素
                    type: 'datetime'
                });
                laydate.render({
                    elem: `#endTime${num}`, //指定元素
                    type: 'datetime'
                });
            });
            $("#fileinput"+num+"").fileinput({
                'theme': 'explorer-fas',
                'uploadUrl':  "https://devplatform.zhengzai.tv/platform/basicServices/alOss/upload",
                "uploadExtraData": {
                    "pathName" : "banner",
                    "buckType" : 1
                },
                autoReplace: true,
                showCaption: false,
                showPreview: false,
                showRemove: false,
                showUpload: false,
                showCancel: false,
                showClose: false,
                autoReplace: true,
                minImageWidth: '764',
                maxImageWidth: '764',
                minImageHeight: '1018',
                maxImageHeight: '1018',
                previewSettings: {
                    image: {
                        width: '764px',
                        height: '1018px'
                    }
                },
                dropZoneTitle: "请上传文件",
                maxFileCount: 1
            }).on("filebatchselected", function (event, files) {         //默认上传
                $(this).fileinput("upload");
            })
            .on("fileuploaded", function (event, data) {       //上传回调事件
                let showPicture = 'https://img.zhengzai.tv/' + data.response.data.ossPath;
                $("#testImg").attr('src', showPicture);
                setTimeout(()=>{
                    if (type == 1) {
                        console.log($("#testImg").height(),$("#testImg").width())
                        if ($("#testImg").height() != 1018) return layer.msg('图片规格不符合要求');
                        if ($("#testImg").width() != 764) return layer.msg('图片规格不符合要求');
                    } else {
                        if ($("#testImg").width() != 382) return layer.msg('图片规格不符合要求');
                    }
                    $("#viewImg"+num+"").attr('src', showPicture)
                }, 500)
            })
        }
        function promiseMethods(url,type,data,contentType) {
            return new Promise((resolve,reject)=>{
                $.ajax({
                    url,
                    type,
                    data,
                    contentType,
                    success:function(res) {
                        resolve(res);
                    }
                })
            })
        }
    </script>
</body>
</html>