<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增活动')" />
    <th:block th:include="include :: select2-css" />
    <link rel="stylesheet" href="">
    <style>
        
        .required {
            font-style: normal;
            color: red;
        }
        .content_item {
            padding: 20px;
        }
        /* .content_item .content_title {
            display: flex;
        } */
        .content_item .content_title h3 span {
            display: inline-block;
            width: 4px;
            height: 18px;
            background: skyblue;
            margin-right: 6px;
            vertical-align: top;
        }
        .basis_data {
            display: flex;
            font-size: 14px;
            padding: 0 20px;
            margin-top: 20px;
            /* align-items: center; */
        }
        .basis_data span {
            width: 100px;
            text-align: right;
            
        }
        #startTime, #endTime {
            width: 272px;
            margin-right: 10px;
        }
        .storeList, #selectShow, .dropdown-menu, .input-group {
            width: 270px !important;
        }
        .activityStore_item {
            display: flex;
            margin-bottom: 12px;
        }
        #basis_data {
            align-items: flex-start;
        }
        .add_footer {
            width: 100%;
            height: 45px;
            line-height: 45px;
            padding-left: 60px;
        }
    </style>
</head>
<body>
<div>
    <div class="content_item">
        <div class="content_title">
            <h3><span></span>基础信息</h3>
        </div>
        <div class="basis_data">
            <span>
                <em class="required">*</em>
                选择演出：
            </span>
            <div class="input-group" style="width: 300px;">
                <input type="text" class="form-control select-show editDisabled" id="selectShow" placeholder="">
                <div class="input-group-btn">
                    <button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown">
                        <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-right" role="menu">
                    </ul>
                </div>
                <!-- /btn-group 11 -->
            </div>
        </div>
        <div class="basis_data">
            <span>
                <em class="required">*</em>
                有效期：
            </span>
            <input type="text" class="layui-input form-control editDisabled" id="startTime" autocomplete="off" placeholder="请选择活动开始时间">
            ~  
            <input type="text" class="layui-input form-control editDisabled"  id="endTime" style="margin-left: 10px;" autocomplete="off" placeholder="请选择活动结束时间">
        </div>
       <div class="first_footer editshow" style="padding-left: 60px;margin-top: 12px;">
           <button class="btn btn-primary" onclick="nextBtn()">确定</button>
       </div>
    </div>
    <div class="content_item" style="display: none;">
        <div class="content_title">
            <h3><span></span>设置</h3>
        </div>
        <div class="basis_data" id="basis_data">
            <span>
                <em class="required">*</em>
                选择店铺：
            </span>
            <div class="activityStore">
                <button class="btn btn-primary" onclick="addItem()" style="margin-bottom: 12px;">新增</button>
                <div class="activityStore_item" id="activityStore_item" data-newTag="1">
                    <div class="input-group" style="margin-right: 12px;">
                        <input type="text" class="form-control storeList item1" placeholder="搜索店铺名称">
                        <div class="input-group-btn">
                            <ul class="dropdown-menu dropdown-menu-right" role="menu">
                            </ul>
                        </div>
                    </div>
                    <input type="text" class="layui-input form-control timeSp" id="startTime" autocomplete="off" placeholder="配置活动时间">
                    
                </div>
               
            </div>
        </div>
    </div>
    <div class="add_footer" style="display: none;">
        <button class="btn btn-success" onclick="save()">保存</button>
        <!-- <button class="btn" onclick="addItem()">取消</button> -->
    </div>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: bootstrap-suggest-js" />
</body>
<script th:inline="javascript">
    let count = 1;
    var prefix2 = ctx + "local";
    let marketId = '';
    let editDatas = 0;
    let performanceImg = '';
    $(function() {
        let name = 'id';
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        layui.use('laydate', function(){
            var laydate = layui.laydate;
            //执行一个laydate实例
            laydate.render({
                elem: '#startTime', //指定元素
                type: 'datetime'
            });
            laydate.render({
                elem: '#endTime', //指定元素
                type: 'datetime'
            });
        });
        common ();
        if (r) {
            marketId =  unescape(r[2]);
            $(".editDisabled").attr('disabled', true);
            $(".editshow").hide()
            let data = {
                marketId
            }
            let searchActivity = promiseMethods('/goblin/marketing/zhengzai/details', 'post', data);
            let searchActivityStore = promiseMethods('/goblin/marketing/zhengzai/store/list', 'post', data);
            Promise.all([searchActivity,searchActivityStore]).then(res => {
                let basisData = res[0];
                let { data } = res[1];
                editDatas = data.length;
                $("#selectShow").val(basisData.data.name);
                $("#startTime").val(basisData.data.startTime);
                $("#endTime").val(basisData.data.endTime);
                $(".content_item").show();
                $(".add_footer").show();
                $("#activityStore_item").remove();
                data.forEach((item,index)=>{
                    addItem(item)
                })
            })
        }


    })
    function common () {
        $("#selectShow").bsSuggest({
            idField: 'performancesId',
	        keyField: 'title',
            allowNoKeyword: false, //是否允许无关键字时请求数据
            showBtn:false,
            multiWord: true, //以分隔符号分割的多关键字支持
            hideOnSelect: true,
            getDataMethod: "url", //获取数据的方式，总是从 URL 获取
            effectiveFields: ['title'],
            url: '/kylin/performances/recommend/performance/status?status=(3,6,7,9,10)&title=',
            /*如果从 url 获取数据，并且需要跨域，则该参数必须设置*/
            processData: function (json) { // url 获取数据时，对数据的处理，作为 getData 的回调函数
                //字符串转化为 js 对象
                return json;
            }
        }).on('onSetSelectValue', function (e, result, selectedRawData) {
            console.log(e, result, selectedRawData)
            performanceImg = selectedRawData.imgPoster;
        });
        $(".storeList").bsSuggest({
            idField: 'storeId',
	        keyField: 'storeName',
            allowNoKeyword: false, //是否允许无关键字时请求数据
            showBtn:false,
            multiWord: true, //以分隔符号分割的多关键字支持
            hideOnSelect: true,
            effectiveFields: ['storeName'],
            getDataMethod: "url", //获取数据的方式，总是从 URL 获取
            url: '/goblin/store/list?storeName=',
            processData: function (json) { // url 获取数据时，对数据的处理，作为 getData 的回调函数
                //字符串转化为 js 对象
                // return json.rows;
                let data = {};
                data.value = json.rows;
                return data
            }
        });
    }
    function addItem (item) {
        count++;
        let body = '';
        if (item) {
            body+=`<div class="activityStore_item" data-newTag="">
                <div class="input-group" style="margin-right: 12px;">
                    <input type="text" class="form-control storeList item${count} itemDisabled" data-id="${item.storeId}" value="${item.storeName}" placeholder="搜索店铺名称">
                    <div class="input-group-btn">
                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                        </ul>
                    </div>
                </div>
                <input type="text" class="layui-input form-control timeSp startTime${count} itemDisabled" id="startTime" value="${item.showTime}" autocomplete="off" placeholder="配置活动时间">
            </div>`
        } else {
            body+=`<div class="activityStore_item" data-newTag="1">
                <div class="input-group" style="margin-right: 12px;">
                    <input type="text" class="form-control storeList item${count}" placeholder="搜索店铺名称">
                    <div class="input-group-btn">
                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                        </ul>
                    </div>
                </div>
                <input type="text" class="layui-input form-control timeSp startTime${count}" id="startTime" autocomplete="off" placeholder="配置活动时间">
            </div>`
        }
        $(".activityStore").append(body)
        common ()
        $(".itemDisabled").attr('disabled', true);
        layui.use('laydate', function(){
            var laydate = layui.laydate;
            //执行一个laydate实例
            laydate.render({
                elem: `.startTime${count}`, //指定元素
                type: 'datetime'
            });
        });
    }
    function nextBtn (params) {
        if (!$("#selectShow").attr('data-id')) {
            return layer.msg('请选择演出进行创建！')
        }
        if (!$("#endTime").val() || !$("#startTime").val()) {
            return layer.msg('请输入必填项！')
        }
        let data = {
            endTime: $("#endTime").val(),
            startTime: $("#startTime").val(),
            name: $("#selectShow").val(),
            performanceId: $("#selectShow").attr('data-id'),
            performanceImg
        } // endTime
        if (marketId) {
            data.marketId = marketId;
            promiseMethods('/goblin/marketing/zhengzai/change','post',data).then(res => {
                if (res.code == 0) {
                    layer.msg('修改活动成功，请配置活动对应店铺！')
                }
            })
            
        } else {
            promiseMethods('/goblin/marketing/zhengzai','post',data).then(res => {
                if (res.code == 0) {
                    marketId = res.data;
                    layer.msg('添加活动成功，请配置活动对应店铺！')
                    $(".content_item").show();
                    $(".add_footer").show();
                }
            })
        }
        
    }
    function save () {
        let obj = {};
        let data = []; // 新增集合
        let data2 = []; // 修改集合
        let domData = $(".activityStore_item");
        let flag = false;
        Array.prototype.forEach.call(domData,function(item,index){
            obj['marketId'] = marketId;
            obj['showTime'] = item.querySelector('.timeSp').value;
            obj['storeId'] = item.querySelector('.storeList').getAttribute('data-id');
            if (!item.querySelector('.timeSp').value || !item.querySelector('.storeList').getAttribute('data-id')) {
                flag = true;
            }
            obj['delTag'] = 0;
            if (item.getAttribute('data-newTag')) {
                obj['newTag'] = 1;
            } else {
                obj['newTag'] = 0;
            }
            data.push({...obj});
            // if (index < editDatas) {
                
            // } else {
            //     data2.push({...obj});
            // }
            
        })
        if (flag) {
            layer.msg('请将选项填写完整！')
            flag = false
            return
        }
        promiseMethods('/goblin/marketing/zhengzai/store','post', JSON.stringify(data), 'application/json').then(res => {
            if (res.code == 0) {
                $.operate.successCallback(res);
            } else {
                layer.msg(res.message)
            }
            
        })
    }
    function promiseMethods(url,type,data,contentType) {
        return new Promise((resolve,reject)=>{
            $.ajax({
                url,
                type,
                data,
                contentType,
                success:function(res) {
                    resolve(res);
                }
            })
        })
    }
</script>
</html>
