<!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;
        }
        .sortable-list {
            width: 700px;
        }
        .sortable-list li {
            width: 100%;
        }
        .sortable-list li .addAvatarItem {
            width: 100%;
            display: flex;
            justify-content: flex-start;
        }
        #addClassify2, #detailPro {
            width: 450px;
            padding-top: 20px;
        }
        .input-group-wrapper {
            padding: 20px;
            border-radius: 8px;
            border: 1px solid #cccccc;
        }
        .addAvatarItem .selectClassifyOne {
            width: 100%;
            display: flex;
            margin-right: 15px;
        }
        .addAvatarItem .selectClassifyOne .span-label {
            width: 108px;
            padding-top: 5px;
        }
        .picker {
            display: flex;
            justify-content: flex-start;
        }
        #addClassify .addAvatarItem label {
            display: flex;
            margin-right: 20px;
            margin-left: 5px;
            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="">所有</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 class="input-group-wrapper">
                    <ul class="sortable-list connectList agile-list">

                    </ul>
                </div>
            </div>

        </div>

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

            </span>
            <a class="btn btn-default btn-xs" href="javascript:void(0)" style="margin-right: 10px;" onclick="addDom()">添加推荐</a>
            <a class="btn btn-info btn-xs" href="javascript:void(0)" onclick="saveList()">保存推荐</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:src="@{/js/jquery-ui-1.10.4.min.js}"></script>
<script th:inline="javascript">

    let prefix2 = ctx + "local";
    let itemId = Number(getUrlParms('id'))
    // 'compilations/goodsList'
    let affiliatedUrl = ['goblin/common/sku', 'goblin/common/mix', 'kylin/performances/roadShow/performance/status', 'goblin/common/goods']
    let currentUrl = 'goblin/common/sku'
    let activeTypeChangeVal = 1
    let listData = []
    let count = 0 // 判断是否默认一组表单
    let _recommendId = ''
    let _recommendActiveId = ''
    let varObj = {}

    $(document).ready(function () {
        $('.sortable-list').sortable({connectWith: '.connectList'}).disableSelection()
    })

    // init
    $(function() {

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

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

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

        // 监听 模糊搜索
        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['title'] = val
                _params['status'] = '(3,6,7,8,9,10)'
            } else if (activeTypeChangeVal == 4) { // 商品
                _params['type'] = 0
                _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.sellName }
                        })
                    } 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.spuName }
                        })
                    }
                    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 => {
                if (res) {

                    list = res.list

                    _recommendId = res.recommendId

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

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

                    activeTypeChangeVal = res.activeType

                    currentUrl = affiliatedUrl[res.activeType - 1]

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

                    $('#search input').attr('data-id', res.activeBindId)

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

                    $('#startTime').attr('value', $.common.dateFormat(new Date(res.startTime), 'yyyy-MM-dd HH:mm:ss'))

                    $('#endTime').attr('value', $.common.dateFormat(new Date(res.endTime), 'yyyy-MM-dd HH:mm:ss'))

                    _recommendActiveId = list[0]?.recommendActiveId

                    assembleDom(list)

                    // 创建监听
                    setTimeout(() => {
                        for (let i = 0; i < list.length; i++) {
                            createListenerSearch(i + 1)
                            $(`#listActiveType${i+1}`).change(function () {
                                $('#listRemoteSearch' + (i + 1) + ' input').attr('value', '')
                            })
                        }
                    }, 500)

                    // 回显 search
                    setTimeout(() => {
                        for (let i = 0; i < list.length; i++) {
                            $('#listRemoteSearch' + (i + 1) + ' input').attr('value', list[i].name)
                            $('#listRemoteSearch' + (i + 1) + ' input').attr('data-id', list[i].recommendBindId)
                            $('#listRemoteSearch' + (i + 1) + ' input').attr('data-mid', list[i].mid)
                            $('#listRemoteSearch' + (i + 1) + ' input').attr('data-recommendActiveId', list[i].recommendActiveId)
                            $('#listRemoteSearch' + (i + 1) + ' input').attr('data-recommendRelationId', list[i].recommendRelationId)
                            $('#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) => {
            count++
            let dynamicAddDom = `<li class="info-element" id="liItem${count}">
                <div class="addAvatarItem" style="padding: 20px;">
                    <div class="selectClassifyOne">
                        <span class="span-label"><i style="color: red; position: relative; top: 3px;">*</i>推荐类型：</span>
                        <select id="listActiveType${count}" value="${item.type}" class="form-control m-b list-active-type">
                            <option value="1">NFT</option>
                            <option value="2">组合购</option>
                            <option value="3">演出</option>
                            <option value="4">商品</option>
                        </select>
                    </div>
                    <div class="selectClassifyOne">
                        <span class="span-label"><i style="color: red; position: relative; top: 3px;">*</i>推荐商品：</span>
                        <div class="search-wrapper">
                            <div class="search-wrapper">
                                <div id="listRemoteSearch${count}" placeholder="请搜索" name="searchSelect${count}"></div>
                            </div>
                        </div>
                    </div>
                    <div><a href="#" class="pull-right btn btn-xs btn-white" style="margin-top: 5px;background: none;border: none;"><i class="fa fa-navicon"></i></a></div>
                    <div style="position: relative;"><i class="fa fa-remove" onclick="removeListItem('${count}')" style="margin-top: 8px; position: absolute; left: 10px;"></i></div>
                </li>`

            $('.sortable-list').append(dynamicAddDom) // 组装好，添加进去


        })
    }

    // 添加关联推荐 html 单个添加
    function addDom () {
        count++;
        let dynamicAddDom = `<li class="info-element" id="liItem${count}">
                <div class="addAvatarItem" style="padding: 20px;">
                    <div class="selectClassifyOne">
                        <span class="span-label"><i style="color: red; position: relative; top: 3px;">*</i>推荐类型：</span>
                        <select id="listActiveType${count}" 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 class="selectClassifyOne">
                        <span class="span-label"><i style="color: red; position: relative; top: 3px;">*</i>推荐商品：</span>
                        <div class="search-wrapper">
                            <div class="search-wrapper">
                                <div id="listRemoteSearch${count}"  placeholder="请搜索" name="searchSelect${count}"></div>
                            </div>
                        </div>
                    </div>
                    <div><a href="#" class="pull-right btn btn-xs btn-white" style="margin-top: 5px;background: none;border: none;"><i class="fa fa-navicon"></i></a></div>
                    <div style="position: relative;"><i class="fa fa-remove" onclick="removeListItem('${count}')" style="margin-top: 8px; position: absolute; left: 10px;"></i></div>
                </li>`


        // 只有一组，可添加
        if (count >= 0 && count <= 19) {
            $('.sortable-list').append(dynamicAddDom)

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

            }, 500)

            setTimeout(() => {
                $(`#listActiveType${count}`).change(function () {
                    $('#listRemoteSearch' + count + ' input').attr('value', '')
                })

            }, 800)

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

        // const new search

    }

    // 删除list item
    function removeListItem (index) {
        let evryGroup = $('#addClassify2').find($('.addAvatarItem'))
        if (evryGroup.length <= 1) return layer.msg('至少保留一个');
        $(`#liItem${index}`).remove()
        $.modal.loading("请稍等...");
        setTimeout(function () {
            $.modal.closeLoading();
        }, 500)
    }

    // 保存 list
    function saveList () {
        listData = []

        $('#addClassify2').find($('.addAvatarItem')).each(function (index) {
            listData.push({
                mid: $(this).find('input').attr('data-mid'),
                recommendActiveId: _recommendActiveId,
                recommendRelationId: $(this).find('input').attr('data-recommendRelationId'),
                recommendBindId: $(this).find('input').attr('data-id'),
                type: Number($(this).find("option:selected").val()),
                indexs: index + 1
            })
        })

        let idList = listData.filter(item => item.recommendBindId == undefined)

        if (idList.length >= 1) {
            layer.msg('推荐活动需填写完整')
        } else {
            // 增加接口
            promiseMethods('/kylin-recommend-active/addOrUpdateListKylinRecommendActiveRelation','post', JSON.stringify(listData), 'application/json').then(res => {

                if (res.code == 0) {
                    layer.msg('修改成功')
                    // $.operate.successTabCallback(res);
                    // closeItem();
                } else {
                    layer.msg(res.msg)
                }

            })
        }

    }

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

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

    }

    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,8,9,10)'
                _params['title'] = val
            } else if (_selectVal == 4) { // 商品
                _params['type'] = 0
                _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.sellName }
                        })
                    } 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.spuName }
                        })
                    }

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

                }
            })
        }

    }

    // 保存/更新
    function save () {

        // bindId - 关联 id
        let _params = {
            activeBindId: $('#search input').attr('data-id'),
            recommendActiveId: $('#search input').attr('data-recommendActiveId'),
            activeName: $('#activeName').val(),
            activeType: Number($("#activeType").find("option:selected").val()),
            endTime: $.common.dateFormat($('#endTime').val(), 'yyyy-MM-dd HH:mm:ss'),
            mid: itemId,
            recommendId: _recommendId,
            startTime: $.common.dateFormat($('#startTime').val(), 'yyyy-MM-dd HH:mm:ss'),
            status: Number($("#status").find("option:selected").val())
        }

        if (!_params.activeName) {
            layer.msg('请填写活动名称')
            return
        }
        if (!_params.activeType) {
            layer.msg('请填写活动类型')
            return
        }
        if (!_params.activeBindId) {
            layer.msg('请填写关联活动名称')
            return
        }
        if (!_params.startTime) {
            layer.msg('请填写开始时间')
            return
        }
        if (!_params.endTime) {
            layer.msg('请填写结束时间')
            return
        }

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

            if (res.code == 0) {
                layer.msg('修改成功')
                $.operate.successTabCallback(res);
                closeItem();
            } else {
                layer.msg(res.msg)
            }

        })


    }

    // 请求方法封装
    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>
