<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('修改banner')"/>
    <th:block th:include="include :: select2-css"/>
    <th:block th:include="include :: datetimepicker-css"/>
    <th:block th:include="include :: bootstrap-fileinput-css"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-post-add">
        <div class="form-group">
            <label class="col-sm-2 control-label is-required">标题：</label>
            <div class="col-sm-10">
                <input th:value="${KylinBannersVo.bannersName}" class="form-control" type="text" name="bannersName"
                       id="bannersName" required>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">排序（越大越靠前）：</label>
            <div class="col-sm-10">
                <input th:value="${KylinBannersVo.bannersSort}" class="form-control" type="text" name="bannersSort"
                       id="bannersSort">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label is-required">展示位置</label>
            <div class="col-sm-10">
                <label th:each="type : ${BannersDisplayLocation}" class="checkbox-inline">
                    <!--                    <input th:checked="${#arrays.contains(#strings.arraySplit(KylinBannersVo.positionList,','),#strings.toString(type.id))}" name="positionList" th:text="${type.name}" th:value="${type.id}" type="checkbox">-->
                    <input th:checked="${#arrays.contains(KylinBannersVo.positionList,#strings.toString(type.id))}"
                           name="positionList" th:text="${type.name}" th:value="${type.id}" type="checkbox">
                </label>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label is-required">请选择跳转类型</label>
            <div class="col-sm-5">
                <select class="form-control" name="targetType" id="targetType">
                    <option value="">--请选择跳转类型--</option>
                    <option th:each="type : ${BannersTargetType}" th:text="${type.name}" th:value="${type.id}"
                            th:field="*{KylinBannersVo.targetType}"></option>
                </select>
            </div>
            <div class="col-sm-5">
                <input th:value="${KylinBannersVo.targetObj}" class="form-control" type="text" placeholder="请填写url"
                       id="targetObjInput">
                <!--<div hidden="hidden" id="targetObjSelectShow">
                    <select class="form-control" id="targetObjSelect">
                        <option value="">&#45;&#45;请选择&#45;&#45;</option>
                    </select>
                </div>-->
                <div hidden class="row" id="targetObjSelectShow">
                    <div class="col-lg-6">
                        <div class="input-group">
                            <input type="text" class="form-control" id="targetObjSelect">
                            <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>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">推广省份</label>
            <div class="col-sm-10">
                <div class="radio check-box">
                    <label>
                        <input th:checked="${KylinBannersVo.promotionType==1 ? true : false}"
                               type="radio" value="1" name="promotionType" checked=""> 全国
                    </label>
                </div>
                <div class="radio check-box">
                    <label>
                        <input th:checked="${KylinBannersVo.promotionType==2 ? true : false}"
                               type="radio" value="2" name="promotionType"> 省份
                    </label>
                </div>
            </div>
        </div>
        <div class="form-group" id="provincesListSelect">
            <label class="col-sm-2 control-label">请选择省份</label>
            <th:block th:if="${#lists.isEmpty(KylinBannersVo.provincesList)}">
                <div class="col-sm-12 provincesAll">
                    <label class="col-sm-2 control-label"></label>
                    <div class="col-sm-5">
                        <select class="form-control provincesList" name="provincesList"></select>
                    </div>
                    <div class="col-sm-5">
                        <button type="button" class="btn btn-danger btn-sm provincesDel">删除</button>
                        <button type="button" class="btn btn-success btn-sm provincesAdd">添加</button>
                    </div>
                </div>
            </th:block>
            <div class="col-sm-12 provincesAll" th:each="provinces : ${KylinBannersVo.provincesList}">
                <label class="col-sm-2 control-label"></label>
                <div class="col-sm-5">
                    <select class="form-control provincesList" name="provincesList"></select>
                </div>
                <div class="col-sm-5">
                    <button type="button" class="btn btn-danger btn-sm provincesDel">删除</button>
                    <button type="button" class="btn btn-success btn-sm provincesAdd">添加</button>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">是否上线</label>
            <div class="col-sm-10">
                <div class="radio check-box">
                    <label>
                        <input type="radio" value="1" name="isOnline"
                               th:checked="${KylinBannersVo.isOnline==1 ? true : false}"> <i></i> 上线
                    </label>
                </div>
                <div class="radio check-box">
                    <label>
                        <input type="radio" value="0" name="isOnline"
                               th:checked="${KylinBannersVo.isOnline==0 ? true : false}"> <i></i> 下线
                    </label>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">上线开始/结束时间</label>
            <div class="col-sm-10">
                <div class="input-daterange input-group">
                    <input th:value="${KylinBannersVo.onlineStartTime}" name="onlineStartTime" type="text"
                           class="input-sm form-control" id="laydate-startTime"
                           placeholder="yyyy-MM-dd HH:mm:ss"/>
                    <span class="input-group-addon">到</span>
                    <input th:value="${KylinBannersVo.onlineEndTime}" name="onlineEndTime" type="text"
                           class="input-sm form-control" id="laydate-endTime"
                           placeholder="yyyy-MM-dd HH:mm:ss"/>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="font-noraml">请上传封面图</label>
            <div class="file-loading">
                <input id="fileinput-demo-1" type="file" name="files" th:value="${KylinBannersVo.coverImg}" data-browse-on-zone-click="true"
                       data-msg-placeholder="Select {files} for upload...">
            </div>
        </div>
        <input hidden id="coverImg" name="coverImg" th:value="${KylinBannersVo.coverImg}">
    </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: select2-js"/>
<th:block th:include="include :: datetimepicker-js"/>
<th:block th:include="include :: bootstrap-fileinput-js"/>
<th:block th:include="include :: bootstrap-suggest-js"/>
<script type="text/javascript">
    var prefix = ctx + "kylin/banners";
    var platformUrl = "[[${platformUrl}]]";
    var provinces = "[[${provinces}]]";
    var url1 = "[[${url1}]]";
    var url2 = "[[${url2}]]";
    var url5 = "[[${url5}]]";
    var url6 = "[[${url6}]]";
    var url7 = "[[${url7}]]";
    var url8 = "[[${url8}]]";
    var url13 = "[[${url13}]]";
    var url14 = "[[${url14}]]";
    var url20 = "[[${url20}]]";
    var url21 = "[[${url21}]]";
    var url22 = "[[${url22}]]";
    var url23 = "[[${url23}]]";
    var url24 = "[[${url24}]]";
    var url26 = "[[${url26}]]";
    var targetObj = "[[${KylinBannersVo.targetObj}]]";
    var targetObjName = "[[${KylinBannersVo.targetObjName}]]";
    var targetObjType = "[[${KylinBannersVo.targetType}]]";
    var provincesListOld = "[[${KylinBannersVo.provincesList}]]";
    var coverImg = "[[${KylinBannersVo.coverImg}]]";
    var bannersId = "[[${KylinBannersVo.bannersId}]]";

    function submitHandler() {
        var bannersName = $('#bannersName').val();
        if (!bannersName) {
            layer.msg("请填写banner标题");
            return false;
        }
        var positionList = $.form.selectCheckeds("positionList");
        if (!positionList) {
            layer.msg("请选择展示位置");
            return false;
        }
        var targetType = $('#targetType').select2('val');
        if (!targetType) {
            layer.msg("请选择跳转方式");
            return false;
        }
        if ($.validate.form()) {
            var data = $('#form-post-add').serializeArray();

            var targetObj = '';
            var targetObjName = '';
            if (12 == targetType || 100 == targetType) { // 请填写url
                targetObj = $("#targetObjInput").val();
                if (!targetObj) {
                    layer.msg("请填写跳转的url");
                    return false;
                }
            } else if (0 == targetType || 201 == targetType) { // 无需跳转
                targetObj = '';
            } else {
                targetObj = $("#targetObjSelect").attr("data-id");
                targetObjName = $("#targetObjSelect").val();
                if (!targetObj) {
                    layer.msg("请选择跳转的目标");
                    return false;
                }
            }
            var coverImg = $('#coverImg').val();
            if (!coverImg) {
                layer.msg("请上传图片,请勿忘记点击上传按钮先上传图片哦～");
                return false;
            }
            data.push({"name": "targetObj", "value": targetObj});
            data.push({"name": "targetObjName", "value": targetObjName});
            data.push({"name": "bannersId", "value": bannersId});
            /*data.push({"name": "positionList", "value": positionList});
            var provincesList = $.form.selectSelects("provincesList");
            data.push({"name": "provincesList", "value": provincesList});*/
            var provincesListText = $.form.selectSelectsOfClassToText("provincesList");
            if (provincesListText) {
                data.push({"name": "provincesNameList", "value": provincesListText});
            }
            $.operate.save(prefix + "/update", data);
        }
    }

    $(function () {
        layui.use(['laydate'], function () {
            var laydate = layui.laydate;

            var startDate = laydate.render({
                elem: '#laydate-startTime',
                type: 'datetime',
                // max: $('#laydate-endTime').val(),
                theme: 'molv',
                trigger: 'click',
                done: function (value, date) {
                    // 结束时间大于开始时间
                    if (value !== '') {
                        endDate.config.min.year = date.year;
                        endDate.config.min.month = date.month - 1;
                        endDate.config.min.date = date.date;
                    } else {
                        endDate.config.min.year = '';
                        endDate.config.min.month = '';
                        endDate.config.min.date = '';
                    }
                }
            });

            var endDate = laydate.render({
                elem: '#laydate-endTime',
                type: 'datetime',
                // min: $('#laydate-startTime').val(),
                theme: 'molv',
                trigger: 'click',
                done: function (value, date) {
                    // 开始时间小于结束时间
                    if (value !== '') {
                        startDate.config.max.year = date.year;
                        startDate.config.max.month = date.month - 1;
                        startDate.config.max.date = date.date;
                    } else {
                        startDate.config.max.year = '';
                        startDate.config.max.month = '';
                        startDate.config.max.date = '';
                    }
                }
            });

            // 全国/省份的选中事件
            /*form.on('radio(promotionType)', function (data) {
                console.log(data);
                var value = data.value;
                console.log(value);
                if (2 == value) {
                    $("#provincesListSelect").show();
                } else {
                    $("#provincesListSelect").hide();
                }
            });
            form.render();*/
        });

        $('body').on('click', '.provincesDel', function () {
            $(this).parents('.provincesAll').remove();
        })
        $('body').on('click', '.provincesAdd', function () {
            var selecthtml = $('.provincesList').eq(0).select2("destroy").html();
            var html = '<div class="col-sm-12 provincesAll">' +
                '                <label class="col-sm-2 control-label"></label>' +
                '                <div class="col-sm-5"><select class="form-control provincesList" name="provincesList">';


            html += selecthtml;

            html += '</select></div>' +
                '                <div class="col-sm-5">' +
                '                    <button type="button" class="btn btn-danger btn-sm provincesDel">删除</button>' +
                '                    <button type="button" class="btn btn-success btn-sm provincesAdd">添加</button>' +
                '                </div>' +
                '            </div>';
            $(this).parents('.provincesAll').after(html)
            $("select").select2();
        })
        // 获取省份数据
        function provincesStr() {
            var provincesStr = '[{"id":1,"adcode":"820000","name":"澳门特别行政区"},{"id":2,"adcode":"110000","name":"北京市"},{"id":3,"adcode":"500000","name":"重庆市"},{"id":4,"adcode":"350000","name":"福建省"},{"id":5,"adcode":"440000","name":"广东省"},{"id":6,"adcode":"450000","name":"广西壮族自治区"},{"id":7,"adcode":"460000","name":"海南省"},{"id":8,"adcode":"520000","name":"贵州省"},{"id":9,"adcode":"710000","name":"台湾省"},{"id":10,"adcode":"140000","name":"山西省"},{"id":11,"adcode":"620000","name":"甘肃省"},{"id":12,"adcode":"410000","name":"河南省"},{"id":13,"adcode":"130000","name":"河北省"},{"id":14,"adcode":"340000","name":"安徽省"},{"id":15,"adcode":"430000","name":"湖南省"},{"id":16,"adcode":"420000","name":"湖北省"},{"id":17,"adcode":"310000","name":"上海市"},{"id":18,"adcode":"230000","name":"黑龙江省"},{"id":19,"adcode":"360000","name":"江西省"},{"id":20,"adcode":"640000","name":"宁夏回族自治区"},{"id":21,"adcode":"210000","name":"辽宁省"},{"id":22,"adcode":"220000","name":"吉林省"},{"id":23,"adcode":"150000","name":"内蒙古自治区"},{"id":24,"adcode":"370000","name":"山东省"},{"id":25,"adcode":"320000","name":"江苏省"},{"id":26,"adcode":"630000","name":"青海省"},{"id":27,"adcode":"610000","name":"陕西省"},{"id":28,"adcode":"120000","name":"天津市"},{"id":29,"adcode":"650000","name":"新疆维吾尔自治区"},{"id":30,"adcode":"810000","name":"香港特别行政区"},{"id":31,"adcode":"540000","name":"西藏自治区"},{"id":32,"adcode":"510000","name":"四川省"},{"id":33,"adcode":"530000","name":"云南省"},{"id":34,"adcode":"330000","name":"浙江省"}]';
            var dataObj = eval("(" + provincesStr + ")");  // 转换为json对象
            var html = '<option value="">--请选择省份--</option>';
            for (var i = 0, l = dataObj.length; i < l; i++) {
                html += '<option value="' + dataObj[i].adcode + '">' + dataObj[i].name + '</option>';
            }
            $(".provincesList").html(html);
            provincesListOld = eval(provincesListOld);
            for (var i = 0, l = provincesListOld.length; i < l; i++) {
                $(".provincesList").eq(i).val(provincesListOld[i])
            }
        }
        provincesStr();
        /*var configProvinces = {
            url: provinces,
            type: "get",
            dataType: "json",
            data: {},
            beforeSend: function () {
                // $.modal.loading("正在处理中，请稍后...");
            },
            success: function (result) {
                var html = '<option value="">--请选择省份--</option>';
                for (var i = 0, l = result.length; i < l; i++) {
                    html += '<option value="' + result[i].adcode + '">' + result[i].name + '</option>';
                }
                $(".provincesList").html(html);
                provincesListOld = eval(provincesListOld);
                for (var i = 0, l = provincesListOld.length; i < l; i++) {
                    $(".provincesList").eq(i).val(provincesListOld[i])
                }
            }
        };
        $.ajax(configProvinces)*/

        // 全国/省份的选中事件
        /*$("input[name=promotionType]").parent(".iradio-blue").click(function(){
            var sex = $(this).val();
            alert(sex);
        });*/

        // 跳转类型选择事件
        // 跳转类型选择事件
        function targetObjBsSuggest(searchUrl, targetType) {
            var bsSuggest = $("#targetObjSelect").bsSuggest({
                indexId: 0,                 // data.value 每组数据的第几个数据，作为input输入框的 data-id，设为 -1 且 idField 为空则不设置此值
                indexKey: 1,                // data.value 的第几个数据，作为input输入框的内容
                showBtn: false, //是否显示下拉按钮
                hideOnSelect:true, //鼠标从列表单击选择了值时，是否隐藏选择列表
                searchingTip: "获取中...",
                clearable: true, //是否可清除已输入的内容
                allowNoKeyword: false,      // 是否允许无关键字时请求数据
                multiWord: false,            // 以分隔符号分割的多关键字支持
                separator: ",",             // 多关键字支持时的分隔符，默认为空格
                getDataMethod: "url",       // 获取数据的方式，总是从 URL 获取
                effectiveFieldsAlias: {
                    Id: "ID",
                    Keyword: "名称"
                },
                showHeader: true,
                url: searchUrl + '&title=',
                /*优先从url ajax 请求 json 帮助数据，注意最后一个参数为关键字请求参数*/
                // jsonp: 'callback',
                /*如果从 url 获取数据，并且需要跨域，则该参数必须设置*/
                processData: function (json) { // url 获取数据时，对数据的处理，作为 getData 的回调函数
                    var i, len, data = {
                        value: []
                    };

                    if (!json) {
                        return false;
                    }

                    if (6 == targetType) {
                        dataList = json.value;
                    } else if(8 == targetType) {
                        dataList = json.rows;
                    } else if(24 == targetType) {
                        dataList = json.data;
                    } else if(26 == targetType) {
                        dataList = json.data;
                    } else {
                        dataList = json.data
                    }

                    console.log(dataList);
                    len = dataList.length;

                    for (i = 0; i < len; i++) {
                        var Title = '';
                        var Id = '';
                        if (6 == targetType) {
                            Id = dataList[i].performancesId;
                            Title = dataList[i].title;
                        } else if(8 == targetType) {
                            Id = dataList[i].roadShowId;
                            Title = dataList[i].title;
                        } else if(24 == targetType) {
                            Id = dataList[i].id;
                            Title = dataList[i].collect_name;
                        } else if(26 == targetType) {
                            Id = dataList[i].id;
                            Title = dataList[i].name;
                        } else {
                            Id = dataList[i].id;
                            Title = dataList[i].title;
                        }

                        data.value.push({
                            "Id": Id,
                            "Title": Title,
                        });
                    }
                    console.log(data);
                    return data;
                }
            });
        }

        function targetType() {
            $("#targetObjSelect").bsSuggest("destroy");
            var targetType = $('#targetType').select2('val');
            if (12 == targetType || 100 == targetType) { // 请填写url
                $("#targetObjSelectShow").hide();
                $("#targetObjInput").show();
            } else if (0 == targetType || 201 == targetType) { // 无需跳转
                $("#targetObjSelectShow").hide();
                $("#targetObjInput").hide();
            } else {
                var urlVarName = 'url' + targetType;
                var urleval = eval(urlVarName);
                var arrEntities = {'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"'};
                searchUrl = urleval.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) {
                    return arrEntities[t];
                });

                $("#targetObjSelectShow").show();
                $("#targetObjInput").hide();
                if (targetType == targetObjType) { //如果是之前选中的类型 设置值
                    $("#targetObjSelect").attr("data-id", targetObj);
                    $("#targetObjSelect").val(targetObjName);
                }

                targetObjBsSuggest(searchUrl, targetType);
                // 获取相关数据
                /*var configUrl = {
                    url: url,
                    type: "get",
                    dataType: "json",
                    data: {},
                    beforeSend: function () {
                        // $.modal.loading("正在处理中，请稍后...");
                    },
                    success: function (result) {
                        var data = [];
                        var html = '<option value="">--请选择--</option>';
                        if (6 == targetType) {
                            data = result.value;
                            for (var i = 0, l = data.length; i < l; i++) {
                                html += '<option value="' + data[i].performancesId + '">' + data[i].title + '</option>';
                            }
                        } else if(8 == targetType) {
                            data = result.rows;
                            for (var i = 0, l = data.length; i < l; i++) {
                                html += '<option value="' + data[i].roadShowId + '">' + data[i].title + '</option>';
                            }
                        } else if(24 == targetType) {
                            data = result.data;
                            for (var i = 0, l = data.length; i < l; i++) {
                                html += '<option value="' + data[i].id + '">' + data[i].collect_name + '</option>';
                            }
                        } else if(26 == targetType) {
                            data = result.data;
                            for (var i = 0, l = data.length; i < l; i++) {
                                html += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
                            }
                        } else {
                            data = result.data
                            for (var i = 0, l = data.length; i < l; i++) {
                                html += '<option value="' + data[i].id + '">' + data[i].title + '</option>';
                            }
                        }
                        $("#targetObjSelect").html(html);
                        $("#targetObjSelectShow").show();
                        $("#targetObjInput").hide();
                        if (targetType == targetObjType) { //如果是之前选中的类型 设置值
                            $("#targetObjSelect").val(targetObj)
                        }
                    }
                };
                $.ajax(configUrl)*/
            }
        }

        targetType();
        // $("#targetType").val(20).trigger("change");
        $('#targetType').on('select2:select', function (e) {
            // var cardTypeW = $("#cardType option:checked").text(); // 获取选中的名
            // var targetType = $("#targetType option:checked").val();
            targetType();
        });

        $("#fileinput-demo-1").fileinput({
            'theme': 'explorer-fas',
            // 'uploadUrl': "/kylin/banners/upload3",
            // 'uploadUrl': ctx + "system/user/profile/updateAvatar",
            // 'uploadUrl': "http://127.0.0.1:9003" + "/platform/basicServices/alOss/upload",
            'uploadUrl': platformUrl + "/platform/basicServices/alOss/upload",
            "uploadExtraData": {
                "pathName" : "banner",
                "buckType" : 1
            },
            overwriteInitial: false,
            initialPreviewAsData: true,
            dropZoneTitle: "请上传文件",
            autoReplace: true,
            maxFileCount: 1,
            initialPreview: [
                "https://img.zhengzai.tv/" + coverImg
            ]

        });
        $("#fileinput-demo-1").on("fileuploaded", function (event, data, previewId, index) {
            $("#coverImg").val(data.response.ossPath)
        });
    })
</script>
</body>
</html>