<!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>
        body .layui-layer-btn {
            display: none !important;
        }
        #layui-layer1 {
            z-index: 1001 !important;
        }
        #layui-layer-shade1 {
            z-index: 1000 !important;
        }

        .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: 320px !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;
        }

        #addClassify2, #detailPro {
            width: 450px;
            padding-top: 20px;
        }
        .addAvatarItem .selectClassifyOne {
            display: flex;
        }
        .addAvatarItem .selectClassifyOne .span-label {
            width: 108px;
        }
        .picker {
            display: flex;
            justify-content: flex-start;
        }
        #addClassify .addAvatarItem label {
            display: flex;
            margin-right: 20px;
            align-items: center;
        }
        #addClassify .addAvatarItem label input {
            margin: 0;
            margin-right: 2px;
        }
        #detailPro .detail_inner {
            margin-bottom: 20px;
        }
        #detailPro .detail_title {
            margin-top: 50px;
            font-weight: bold;
            font-size: 16px;
        }
        .bottomBtn {
            text-align: left;
            padding: 30px 15px 12px;
        }
        .layui-layer-shade{
            opacity: 30%;
        }
        .item div {
            display: flex;
        }
        .item div a{
            margin-left: 12px;
        }
        /* 星星 */
        .required-group-name {
            color: red;
            font-size: 20px;
            position: relative;
            top: 6px;
        }
        .groupName {
            border: 1px solid #dfdfdf;
        }
        .required-province {
            color: red;
            display: inline-block;
            margin-right: 3px;
            position: relative;
            top: 6px;
            font-size: 20px;
        }
        /* 必填红色文字 */
        .required-group-text {
            height: 20px;
            color: red;
        }
        .required-province-text {
            color: red;
            height: 20px;
        }
        .search-wrapper {
            width: 100%;
        }
    </style>
</head>
<body>
<div>
    <div class="content_item">
        <div class="content_title">
            <h3><span></span>增加关联活动</h3>
        </div>
        <!-- row -->
        <div class="basis_data">
            <span>
                <em class="required">*</em>
                活动名称：
            </span>
            <div class="input-group" style="width: 300px;">
                <input type="text" class="form-control" id="activeName" placeholder="">
            </div>
        </div>

        <div class="basis_data">
            <span>
                <em class="required">*</em>
                关联类型：
            </span>
            <div class="input-group" style="width: 300px;">
                <select name="activeType" id="activeType" class="form-control m-b">
                    <option value="1">NFT</option>
                    <option value="2">组合购</option>
                    <option value="3">演出</option>
                    <option value="4">商品</option>
                </select>
            </div>
        </div>

        <div class="basis_data">
            <span>
                <em class="required">*</em>
                关联名称：
            </span>
            <div class="input-group" style="width: 300px;">
                <div class="search-wrapper" style="margin-bottom: 15px;">
                    <!-- 关联 模糊搜索 回显的话添加id再赋值 -->
                    <div id="search"  placeholder="请搜索" name="seaarchSelect"></div>
                </div>
            </div>
        </div>

        <div class="basis_data">
            <span>
                <em class="required">*</em>
                状态：
            </span>
            <div class="input-group" style="width: 300px;">
                <select name="status" id="status" class="form-control m-b">
                    <option value="0">开启</option>
                    <option value="1">未开启</option>
                </select>
            </div>
        </div>

        <!-- row -->
        <div class="basis_data">
            <span>
                <em class="required">*</em>
                时间范围：
            </span>
            <input type="text" class="layui-input form-control" id="startTime" autocomplete="off" placeholder="开始时间选择">
            ~
            <input type="text" class="layui-input form-control"  id="endTime" style="margin-left: 10px;" autocomplete="off" placeholder="结束时间选择">
        </div>

        <div class="basis_data">
            <span>
                <em class="required">*</em>
                推荐：
            </span>
            <!-- 动态 input -->
            <div class="input-group" id="addClassify2">

            </div>

        </div>

        <div class="basis_data">
            <span>
                <em class="required"></em>

            </span>
            <a class="btn btn-default btn-xs" href="javascript:void(0)" onclick="addDom()">+ 添加推荐</a>
        </div>

        <!--  -->
        <div class="first_footer editshow" style="padding-left: 60px; margin-top: 12px;">
            <button class="btn btn-primary" onclick="save()">确定</button>
        </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:src="@{/js/searchSelect.js}"></script>
<script th:inline="javascript">

    let prefix2 = ctx + "local";
    // let itemId = Number(getUrlParms('id'))
    let affiliatedUrl = ['goblin/common/sku', 'goblin/common/mix', 'kylin/performances/roadShow/performance/status', 'compilations/goodsList']
    let listData = []
    let isOneDom = $('#addClassify2').find($('.addAvatarItem')).length + 1 // 判断是否默认一组表单
    let currentUrl = 'goblin/common/sku'
    let activeTypeChangeVal = 1
    console.log('isOneDom-length', isOneDom)
    let varObj = {}

    // init
    $(function() {

        layui.use('laydate', function() {
            let laydate = layui.laydate;

            // 执行一个laydate实例
            laydate.render({
                elem: '#startTime', //指定元素
                type: 'datetime'
            });
            laydate.render({
                elem: '#endTime', //指定元素
                type: 'datetime'
            });
        });

        $("#status").attr('value', 0)

        $("#activeType").attr('value', 1)

        // 选择select
        $('#activeType').change(function () {
            activeTypeChangeVal = Number($(this).val()) // 1 2 3 4
            currentUrl = affiliatedUrl[activeTypeChangeVal - 1] // 获取选中的，对应地址

        })

        // 监听 模糊搜索
        let search = new searchSelect('#search', [], function(val) {
            let _params = {}
            if (activeTypeChangeVal == 1) {
                _params['type'] = 1
                _params['title'] = val
            } else if (activeTypeChangeVal == 2) { // 组合购
                _params['title'] = val
            } else if (activeTypeChangeVal == 3) { // 演出
                _params['status'] = '(3,6,7,9,10)'
                _params['title'] = val
            } else { // 商品
                _params['name'] = val
                // _params['title'] = val
            }
            $.ajax({
                type: 'get',
                url: ctx + currentUrl,
                contentType: "application/json;charset=UTF-8",
                data: _params,
                success: function(res) {
                    let _data = []
                    let nft = res.data || []
                    let group = res.data || []
                    let yan = res.value || []
                    let sp = res.data || []

                    if (activeTypeChangeVal == 1) {
                        _data = nft?.map(item => { // 组装返回nft数据
                            return { id: item.spuId, value: item.spuName }
                        })
                    } else if (activeTypeChangeVal == 2) {
                        _data = group?.map(item => {
                            return { id: item.mixId, value: item.name }
                        })
                    } else if (activeTypeChangeVal == 3) {
                        _data = yan?.map(item => {
                            return { id: item.performancesId, value: item.title }
                        })
                    } else if (activeTypeChangeVal == 4) {
                        _data = sp?.map(item => {
                            return { id: item.spuId, value: item.name }
                        })
                    }
                    search.update(_data)

                }
            })
        })

    }) // init end

    getPageData() // 最开始加载

    // 获得当前页面回显数据
    function getPageData () {
        let list = []

        list = [{type: 1}]

        assembleDom(list)

        // 创建监听
        setTimeout(() => {
            for (let i = 0; i < list.length; i++) {
                createListenerSearch(i + 1)
            }
        }, 500)

        // 回显 search
        setTimeout(() => {
            for (let i = 0; i < list.length; i++) {
                $('#listRemoteSearch' + (i + 1) + ' input').attr('value', '')
                $('#listActiveType' + (i + 1)).find(`option[value=${list[i].type}]`).attr('selected', true)
            }
        }, 800)


    }

    // 组装 html
    function assembleDom (list) {
        list.forEach((item, index) => {
            let dynamicAddDom = `<div class="addAvatarItem" style="padding: 20px;">
                <div class="selectClassifyOne" style="margin-bottom: 20px;">
                    <span class="span-label"><i style="color: red;">*</i>推荐商品：</span>
                    <div class="search-wrapper">
                        <div class="search-wrapper" style="margin-bottom: 15px;">
                            <div id="listRemoteSearch${index + 1}" placeholder="请搜索" name="searchSelect${index + 1}"></div>
                        </div>
                    </div>
                </div>
                <div class="selectClassifyOne">
                    <span class="span-label"><i style="color: red;">*</i>推荐类型：</span>
                    <select id="listActiveType${index + 1}" value="${item.type}" class="form-control m-b">
                        <option value="1">NFT</option>
                        <option value="2">组合购</option>
                        <option value="3">演出</option>
                        <option value="4">商品</option>
                    </select>
                </div>`

            $('#addClassify2').append(dynamicAddDom) // 组装好，添加进去

        })
    }

    // 添加关联推荐 html 单个添加
    function addDom () {
        let dynamicDomLength = $('#addClassify2').find($('.addAvatarItem')).length // dom1 dom2 dom3

        let dynamicAddDom = `<div class="addAvatarItem" style="padding: 20px;">
                <div class="selectClassifyOne" style="margin-bottom: 20px;">
                    <span class="span-label"><i style="color: red;">*</i>推荐商品：</span>
                    <div class="search-wrapper">
                        <div class="search-wrapper" style="margin-bottom: 15px;">
                            <div id="listRemoteSearch${dynamicDomLength + 1}"  placeholder="请搜索" name="searchSelect${dynamicDomLength + 1}"></div>
                        </div>
                    </div>
                </div>
                <div class="selectClassifyOne">
                    <span class="span-label"><i style="color: red;">*</i>推荐类型：</span>
                    <select id="listActiveType${dynamicDomLength + 1}" class="form-control m-b">
                        <option value="1">NFT</option>
                        <option value="2">组合购</option>
                        <option value="3">演出</option>
                        <option value="4">商品</option>
                    </select>
                </div>`


        // 只有一组，可添加
        if (dynamicDomLength) {
            console.log('dynamicDomLength', dynamicDomLength)

            $('#addClassify2').append(dynamicAddDom)

            // 设置 实例化 一个 input search监听
            setTimeout(() => {
                varObj['listRemoteSearch'+(dynamicDomLength+1)] = new searchSelect(`#listRemoteSearch${dynamicDomLength + 1}`, [], function(val) {
                    searchAjax(val, dynamicDomLength + 1)
                })

            }, 600)

        } else {
            layer.msg('不能添加')
        }

        // const new search

    }

    // 添加dom同时，添加表单监听
    function createListenerSearch (index) {

        varObj['listRemoteSearch'+index] = new searchSelect(`#listRemoteSearch${index}`, [], function(val) {
            searchAjax(val, index)
        })

        console.log('varObj', varObj)

    }

    function searchAjax (val, index) {
        let _selectVal = $("#listActiveType" + index).find("option:selected").val() // 当前子select val

        if (_selectVal) {
            let _params = {}
            if (_selectVal === 1) {
                _params['type'] = 1
                _params['title'] = val
            } else if (_selectVal === 2) { // 组合购
                _params['title'] = val
            } else if (_selectVal === 3) { // 演出
                _params['status'] = '(3,6,7,9,10)'
                _params['title'] = val
            } else { // 商品
                _params['name'] = val
                // _params['title'] = val
            }
            $.ajax({
                type: 'get',
                url: ctx + affiliatedUrl[_selectVal - 1],
                contentType: "application/json;charset=UTF-8",
                data: _params,
                success: function(res) {
                    let _data = []
                    let nft = res.data || []
                    let group = res.data || []
                    let yan = res.value || []
                    let sp = res.data || []

                    console.log('_selectVal', _selectVal)

                    if (_selectVal == 1) {
                        _data = nft?.map(item => { // 组装返回nft数据
                            return { id: item.spuId, value: item.spuName }
                        })
                    } else if (_selectVal == 2) {
                        _data = group?.map(item => {
                            return { id: item.mixId, value: item.name }
                        })
                    } else if (_selectVal == 3) {
                        _data = yan?.map(item => {
                            return { id: item.performancesId, value: item.title }
                        })
                    } else if (_selectVal == 4) {
                        _data = sp?.map(item => {
                            return { id: item.spuId, value: item.name }
                        })
                    }

                    varObj[Object.keys(varObj)[index - 1]].update(_data) // 更新数据

                }
            })
        }

    }

    // 保存/更新
    function save () {
        listData = []

        let evryGroup = $('#addClassify2').find($('.addAvatarItem'))

        // 遍历所有的dom组，取值组装
        for (let i = 0; i < evryGroup.length; i++) {
            listData.push({
                recommendBindId: $('#listRemoteSearch' + (i+1)).find('input').attr('data-id'),
                type: Number($("#listActiveType" + (i+1)).find("option:selected").val())
            })

        }

        console.log('listData', listData)

        // recommendId: _recommendId, 更新接口需要

        let _params = {
            activeBindId: $('#search input').attr('data-id'),
            activeName: $('#activeName').val(),
            activeType: Number($("#activeType").find("option:selected").val()),
            endTime: $('#endTime').val(),
            list: listData,
            startTime: $('#startTime').val(),
            status: Number($("#status").find("option:selected").val())
        }

        console.log('save_params', _params)

        let isRequired = _params.startTime && _params.endTime && _params.activeType

        if (isRequired) {
            // 增加接口
            promiseMethods('/kylin-recommend-active/addKylinRecommendActive','post', JSON.stringify(_params), 'application/json').then(res => {

                if (res.code == 0) {
                    layer.msg('新增成功')
                    $.operate.successTabCallback(res);
                    closeItem();
                } 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);
                }
            })
        })
    }

    function getUrlParms (name) {
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r != null)
            return unescape(r[2]);
        return null;
    }

</script>
</html>
