<!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 label {
            display: flex;
            align-items: center;
        }
        .function_btn .tags label input {
            margin: 0 4px 0 12px;
        }
        .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;
        }
        .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 {
            max-width: 350px;
            max-height: 180px;
        }
        .jump, .ticket_name, .set_function_time {
            display: flex;
            flex-grow: 1;
            align-items: center;
        }
        .iptOrSelect {
            flex: 1;
        }
    </style>
</head>
<body>
    <div class="home_page">
        <div class="left_content">
            <div class="left_title">
                
            </div>
            <div class="function_btn">
                <div class="hot_title">
                    展示形式：
                </div>
                <div class="tags">
                    <label>
                        <input type="radio" checked value="1" id="optionsRadios1" name="optionsRadios"><span>一行</span></label>
                    <label>
                        <input type="radio" value="2" id="optionsRadios2" name="optionsRadios"><span>两行</span></label>
                </div>
            </div>
            <div class="function_btn">
                <div class="hot_title">
                    位置顺序：
                </div>
                <div class="tags">
                    <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 class="tags">
                </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 jumpType = 1;
        let hang = 1;
        let returnData = [];
        $(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=>{
                console.log(res, 'resp')
                let { data } = res;
                data.forEach(item => {
                    if (item.moudleName == "jinGangWei") {
                        $("#sorting").val(item.indexs)
                    }
                })
            })
            showDetail (1)
        })
        function showDetail (numType) {
            promiseMethods('/navigation/list', 'post').then(res => {
                let { data } = res;
                if (data&&data.length>0) {
                    if (numType == 1) {
                        if (data[0].displayType == 1) {
                            $('#optionsRadios1').attr('checked', true)
                            $('#optionsRadios2').removeAttr('checked')
                        } else {
                            $('#optionsRadios2').attr('checked', true)
                            $('#optionsRadios1').removeAttr('checked')
                        }
                    }
                    if (hang == data[0].displayType) {
                        for (var i = 0; i < data.length; i++) {
                            let str = '';
                            str += `<div class="banner_item" data-id="${data[i].mid}">
                                    <div class="img_show">
                                        <div class="title">
                                            图片展示：
                                        </div>
                                        <div class="ibox-content" style="border: none;">
                                            <img id="viewImg${i}" class="imgBox" src="${data[i].picUrl}" alt="">
                                            <div class="form-group">
                                                <div class="file-loading">
                                                    <input id="fileinput${i}" 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="jumpType${i}" onchange="changeJump(this)" value="${data[i].navigationType}" class="typeSelect type form-control" data-first-title="请选择">
                                                    <option value="1">分类</option>
                                                    <option value="2">专题页</option>
                                                    <option value="3">商品单品</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="ticket_name">
                                            <div class="title titleDiv${i}">
                                                选择分类：
                                            </div>
                                            <div class="typeSelect${i}" style="display:flex;flex:1">
                                                <div class="iptOrSelect">
                                                    <select id="jumpSelectOne${i}" onchange="selectFirst(this)" class="type1 form-control" data-first-title="请选择">
                                                        <option value="">请选择</option>
                                                    </select>
                                                </div>
                                                <div class="iptOrSelect">
                                                    <select id="jumpSelectTwo${i}" class="type2 form-control" data-first-title="请选择">
                                                        <option value="">请选择</option>
                                                    </select>
                                                </div>
                                            </div>`
                                            if (data[i].goblinGoods) {
                                                str+= `<div class="input-group iptOrSelect shwoSelect${i}" style="display:none;">
                                                        <input id="searchIpt${i}" type="text" class="form-control storeList" onFocus="focusMethod(this)" data-id="${data[i].goblinGoods.spuId}" value="${data[i].goblinGoods.name}" placeholder="">
                                                        <div class="input-group-btn">
                                                            <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                                            </ul>
                                                        </div>
                                                    </div>`
                                            } else {
                                                str+=`<div class="input-group iptOrSelect shwoSelect${i}" style="display:none;">
                                                    <input id="searchIpt${i}" type="text" class="form-control storeList" onFocus="focusMethod(this)" value="" placeholder="">
                                                    <div class="input-group-btn">
                                                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                                        </ul>
                                                    </div>
                                                </div>`
                                            }
                                            
                                            str+= `<div class="link${i}" style="display:none;">
                                                <input id="linkUrl${i}" type="text" class="layui-input form-control linkUrl" value="${data[i].activityUrl}" placeholder="请输入活动链接">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="set_function">
                                        <div class="set_function_time">
                                            <div class="title">
                                                标题：
                                            </div>
                                            <div class="select_tiem">
                                                <input type="text" class="layui-input form-control titleIpt" id="startTime${i}" value="${data[i].title}" autocomplete="off" placeholder="请输入标题">
                                            </div>
                                        </div>
                                    </div>
                                </div>`
                            $("#bannerList").append(str);
                            common(i)
                            // setTimeout(() => {
                            let type = data[i].navigationType;
                            showOrhide (type, i, data[i].categoryType)
                            
                            $("#jumpType"+i+" option[value="+type+"]").attr('selected','selected');
                            returnData = [];
                            // }, 500);
                        }
                    } else {
                        returnData = data.map((item, index) => {
                            item.delTag = 1;
                            return {...item}
                        })
                        console.log(returnData, 'returnData')
                        if (hang == 1) {
                            addItem (4);
                        } else {
                            addItem (8);
                        }
                    }
                } else {
                    console.log('?')
                    if (hang == 1) {
                        addItem (4);
                    } else {
                        addItem (8);
                    }
                }
            })
        }
        $("input[name=optionsRadios]").change(function(e){
            $("#bannerList").empty();
            if (e.target.value == 2) {
                hang = 2;
                // addItem (8);
                showDetail (2)
            } else {
                hang = 1;
                showDetail (2)
            }
        })
        function addItem (num) {
            let str = '';
            for (var i = 0; i < num; i++) {
                str = `<div class="banner_item" data-id="">
                        <div class="img_show">
                            <div class="title">
                                图片展示：
                            </div>
                            <div class="ibox-content" style="border: none;">
                                <img id="viewImg${i}" class="imgBox" src="" alt="">
                                <div class="form-group">
                                    <div class="file-loading">
                                        <input id="fileinput${i}" 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="jumpType${i}" onchange="changeJump(this)" class="typeSelect type form-control" data-first-title="请选择">
                                        <option value="">请选择</option>
                                        <option value="1">分类</option>
                                        <option value="2">专题页</option>
                                        <option value="3">商品单品</option>
                                    </select>
                                </div>
                            </div>
                            <div class="ticket_name">
                                <div class="title titleDiv${i}">
                                    选择分类：
                                </div>
                                <div class="typeSelect${i}" style="display:flex;flex:1">
                                    <div class="iptOrSelect">
                                        <select id="jumpSelectOne${i}" onchange="selectFirst(this)" class="type1 form-control" data-first-title="请选择">
                                            <option value="">请选择</option>
                                        </select>
                                    </div>
                                    <div class="iptOrSelect">
                                        <select id="jumpSelectTwo${i}" class="type2 form-control" data-first-title="请选择">
                                            <option value="">请选择</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="input-group iptOrSelect shwoSelect${i}" style="display:none;">
                                    <input id="searchIpt${i}" type="text" class="form-control storeList" onFocus="focusMethod(this)" placeholder="请输入商品名称">
                                    <div class="input-group-btn">
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                        </ul>
                                    </div>
                                </div>
                                <div class="link${i}" style="display:none;">
                                    <input id="linkUrl${i}" type="text" class="layui-input form-control linkUrl" placeholder="请输入活动链接">
                                </div>
                            </div>
                        </div>
                        <div class="set_function">
                            <div class="set_function_time">
                                <div class="title">
                                    标题：
                                </div>
                                <div class="select_tiem">
                                    <input type="text" class="layui-input form-control titleIpt" id="startTime${i}" autocomplete="off" placeholder="请输入标题">
                                </div>
                            </div>
                        </div>
                    </div>`
                $("#bannerList").append(str);
                
                common(i)
            }
            
        }
        function save () {
            let itmeLength = $(".banner_item");
            let arr = [];
            let obj = {};
            Array.prototype.forEach.call(itmeLength,function (item,index) {
                let type = [];
                if ($("#jumpType"+index+"").val() == 2) {
                    obj['activityUrl'] = item.querySelector(".linkUrl").value;
                    obj['spuId'] = '';
                } else if ($("#jumpType"+index+"").val() == 3) {
                    obj['activityUrl'] = '';
                    obj['spuId'] = item.querySelector(".storeList").getAttribute('data-id');
                } else {
                    type.push(item.querySelector(".type1").value)
                    type.push(item.querySelector(".type2").value)
                }
                obj['categoryType'] = type.toString(); // 
                obj['createTime'] = '';
                obj['delTag'] = '0';
                obj['displayType'] = hang;
                obj['indexs'] = index;
                obj['mid'] = item.getAttribute('data-id') || 0;
                obj['navigationId'] = '';
                obj['navigationType'] = $("#jumpType"+index+"").val();
                obj['spuName'] = '';
                obj['picUrl'] = item.querySelector(".imgBox").getAttribute('src');
                obj['title'] = item.querySelector(".titleIpt").value;
                obj['updateTime'] = '';
                arr.push({...obj})
            });//foreach js6章封装的方法 
            arr = arr.concat(returnData);
            console.log(arr,returnData, 'arr')
            promiseMethods('/navigation/createOrUpdate', 'post', JSON.stringify(arr), 'application/json').then(() => {
                let data = {
                    "mid": 2,
                    "moudleIndexId": "708754120962334729770775",
                    "moudleName": "jinGangWei",
                    "indexs": $("#sorting").val(),
                    "updateTime": "2022-01-06 13:53:42",
                    "createTime": "2022-01-06 13:53:45",
                    "delTag": 0,
                    "status": 0
                };
                return promiseMethods('/front-index/update', 'post', JSON.stringify(data), 'application/json')
            }).then((res)=> {
                layer.msg('保存成功！')
                // $.modal.closeTab();
                $.operate.successCallback(res);
            })
        }
        function common (num) {
            $("#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,
                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;
                $("#viewImg"+num+"").attr('src', showPicture)
            })
        }
        function changeJump (e) {
            let index = $(e).attr('id').replace(/[^\d]/g,''); // 选中的是第几组
            let jumpType = $(e).val(); // 选中的跳转类型
            showOrhide (jumpType, index)
        }
        function selectFirst(e) {
            let index = $(e).attr('id').replace(/[^\d]/g,''); // 选中的是第几组
            let jumpType = $(e).val(); // 选中的跳转类型
            categoryMethods(jumpType,index, 3)
        }
        function categoryMethods(parentsId, num, type, categoryType) {
            let data = {
                cateId: parentsId,
                grade: type - 1
            }
            $.ajax({
                type: 'post',
                url: '/goblin/category/filter',
                data,
                success: function(res) {
                    const { data } = res;
                    let str = '';
                    data.forEach(item => {
                        if (categoryType) {
                            let categoryTypeArr = categoryType.split(',');
                            if (item.cateId == categoryTypeArr[0] || item.cateId == categoryTypeArr[1]) {
                                str += `<option value="${item.cateId}" selected>${item.name}</option>`
                                categoryMethods(item.cateId, num, 3, categoryType)
                            } else {
                                str += `<option value="${item.cateId}">${item.name}</option>`
                            }
                        } else {
                            str += `<option value="${item.cateId}">${item.name}</option>`
                        }
                    })
                    if (!parentsId) {
                        $("#jumpSelectOne"+num+"").append(str);
                    } else {
                        $("#jumpSelectTwo"+num+"").append(str);
                    }
                }
            })
        }
        function showOrhide (jumpType, index, categoryType) {
            switch(jumpType.toString()) {
                case '1':
                    $('.shwoSelect'+index+'').hide();
                    $('.link'+index+'').hide();
                    $('.typeSelect'+index+'').show();
                    $(".titleDiv"+index+"").text('选择分类：');
                    categoryMethods('',index, 2, categoryType)
                    break;
                case '2':
                    $('.shwoSelect'+index+'').hide();
                    $('.link'+index+'').show();
                    $('.typeSelect'+index+'').hide();
                    $(".titleDiv"+index+"").text('活动链接：');
                    break;
                case '3':
                    $(".titleDiv"+index+"").text('商品名称：');
                    $('.shwoSelect'+index+'').show();
                    $('.link'+index+'').hide();
                    $('.typeSelect'+index+'').hide();
                    break;
                default:
                    // $(".titleDiv"+index+"").text('商品聚合：');
                    // $('.shwoSelect'+index+'').show();
                    // $('.link'+index+'').hide();
                    // $('.typeSelect'+index+'').hide();
            }
        }
        function focusMethod (e) {
            let index = $(e).attr('id').replace(/[^\d]/g,''); // 选中的是第几组
            let url = '';
            $(".storeList").bsSuggest({
                idField: 'spuId',                 // data.value 的第几个数据，作为input输入框的内容
	            keyField: 'name',                // data.value 的第几个数据，作为input输入框的内容
                allowNoKeyword: false, //是否允许无关键字时请求数据
                showBtn:false,
                multiWord: true, //以分隔符号分割的多关键字支持
                hideOnSelect: true,
                getDataMethod: "url", //获取数据的方式，总是从 URL 获取
                effectiveFields: ['name'],
                url: '/compilations/goodsList?name=',
                /*如果从 url 获取数据，并且需要跨域，则该参数必须设置*/
                processData: function (json) { // url 获取数据时，对数据的处理，作为 getData 的回调函数
                    //字符串转化为 js 对象
                    let data = {};
                    data.value = json.data
                    return data
                }
            }).on('onDataRequestSuccess', function (e, result) {
            }).on('onSetSelectValue', function (e, selectedData,selectedRawData ) { // 当前行的所有值都能拿到
            }).on('onUnsetSelectValue', function (e) {
            });;
        }
        function promiseMethods(url,type,data,contentType) {
            return new Promise((resolve,reject)=>{
                $.ajax({
                    url,
                    type,
                    data,
                    contentType,
                    success:function(res) {
                        resolve(res);
                    }
                })
            })
        }
    </script>
</body>
</html>