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

        #addClassify2, #detailPro {
            width: 450px;
            height: 260px;
            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="">所有</option>
                    <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="">所有</option>
                    <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>
            <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 _recommendId = ''
    let varObj = {}

    console.log('isOneDom', isOneDom)

    // init
    $(function() {

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

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

        // 监听 模糊搜索
        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'] = 1
                _params['title'] = val
            }
            $.ajax({
                type: 'get',
                url: ctx + currentUrl,
                contentType: "application/json;charset=UTF-8",
                data: _params,
                success: function(res) {
                    let forData = activeTypeChangeVal === 3 ? res.value : res.data
                    let _data = forData.map(item => {
                        if (activeTypeChangeVal === 1) { // NFT
                            return { id: item.spuId, value: item.spuName }
                        } else if (activeTypeChangeVal === 2) {
                            return { id: item.mixId, value: item.name }
                        } else if (activeTypeChangeVal === 3) {
                            return { id: item.performancesId, value: item.title }
                        } else if (activeTypeChangeVal === 4) { // 商品
                            return { id: item.spuId, value: item.name }
                        }
                    })
                    search.update(_data)

                }
            })
        })
        search.search(true)

    }) // init end

    getPageData() // 最开始加载

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

        if (itemId) {
            // 请求数据
            promiseMethods('/kylin-recommend-active/getActiveById', 'post', { mid: itemId }).then(res => {
                console.log('res', res)
                if (res) {
                    // $.operate.successCallback(res);

                    list = res.list

                    _recommendId = res.recommendId

                    $('#activeName').attr('value', res.name)

                    $('#activeType').find(`option[value=${res.activeType}]`).attr('selected', true)

                    $('#search input').attr('value', res.activeBindId)

                    $('#status').find(`option[value=${res.status}]`).attr('selected', true)

                    $('#startTime').attr('value', res.startTime)

                    $('#endTime').attr('value', res.endTime)

                    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', list[i].recommendActiveId)
                            $('#listActiveType' + (i + 1)).find(`option[value=${list[i].type}]`).attr('selected', true)
                        }
                    }, 800)



                } else {
                    layer.msg(res.message)
                }

            })
        }

    }

    // 组装 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="">所有</option>
                        <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 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${isOneDom + 1}"  placeholder="请搜索" name="searchSelect${isOneDom + 1}"></div>
                        </div>
                    </div>
                </div>
                <div class="selectClassifyOne">
                    <span class="span-label"><i style="color: red;">*</i>推荐类型：</span>
                    <select id="listActiveType${isOneDom + 1}" class="form-control m-b">
                        <option value="">所有</option>
                        <option value="1">NFT</option>
                        <option value="2">组合购</option>
                        <option value="3">演出</option>
                        <option value="4">商品</option>
                    </select>
                </div>`


        // 只有一组，可添加
        if (isOneDom) {
            console.log('只有一组，可添加', isOneDom)
            $('#addClassify2').append(dynamicAddDom)

            setTimeout(() => {
                varObj['listRemoteSearch'+(isOneDom+1)] = new searchSelect(`#listRemoteSearch${isOneDom + 1}`, [], function(val) {
                    searchAjax(val, isOneDom + 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

        console.log('111', val, _selectVal)

        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'] = 1
                _params['title'] = val
            }
            $.ajax({
                type: 'get',
                url: ctx + affiliatedUrl[_selectVal],
                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) {
                        console.log('111')
                        _data = nft.map(item => { // 组装返回nft数据
                            return { id: item.spuId, value: item.spuName }
                        })
                    } else if (_selectVal == 2) {
                        console.log('222')
                        _data = group?.map(item => {
                            return { id: item.mixId, value: item.name }
                        })
                    } else if (_selectVal == 3) {
                        console.log('333')
                        _data = yan?.map(item => {
                            return { id: item.performancesId, value: item.title }
                        })
                    } else if (_selectVal == 4) {
                        console.log('444')
                        _data = sp?.map(item => {
                            return { id: item.spuId, value: item.name }
                        })
                    }

                    console.log(Object.keys(varObj), index, _data)

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



                }
            })
        }

    }

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

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

        for (let i = 0; i < evryGroup.length; i++) {
            listData.push({
                recommendBindId: $('#listRemoteSearch' + (i+1)).find('input').val(),
                type: $("#listActiveType" + (i+1)).find("option:selected").val()
            })


        }

        console.log('listData', listData)

        let _params = {
            activeBindId: $('#search input').val(),
            activeName: $('#activeName').val(),
            activeType: Number($("#activeType").find("option:selected").val()),
            endTime: $('#endTime').val(),
            list: listData,
            mid: itemId,
            recommendId: _recommendId,
            startTime: $('#startTime').val(),
            status: Number($("#status").find("option:selected").val())
        }

        console.log('_params', _params)

        // 修改活动
        promiseMethods('/kylin-recommend-active/updateKylinRecommendActive','post', JSON.stringify(_params), 'application/json').then(res => {

            if (res.code == 200) {
                $.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);
                }
            })
        })
    }

    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>
