<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增赛事发布')"/>
    <th:block th:include="include :: datetimepicker-css"/>
    <th:block th:include="include :: summernote-css"/>
    <th:block th:include="include :: image-upload-css"/>

    <!-- 自定义 CSS -->
    <style>
        /* 修改文本域的背景颜色和文字颜色 */
        .note-editable {
            background-color: black !important; /* 黑色背景 */
            color: white !important; /* 白色文字 */
        }
    </style>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-competition-add">
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-2 control-label is-required">赛事标题：</label>
                <div class="col-sm-4">
                    <input name="competitionTitle" class="form-control" type="text" placeholder="请输入赛事标题"
                           maxlength="50"
                           required>
                </div>
                <label class="col-sm-2 control-label is-required">赛事类型：</label>
                <div class="col-sm-4">
                    <select name="competitionType" class="form-control"
                            th:with="type=${@dict.getType('competition_type')}" required>
                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}"
                                th:value="${dict.dictValue}"></option>
                    </select>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-2 control-label is-required">最大人数/团队数：</label>
                <div class="col-sm-4">
                    <input name="teamMax" class="form-control" type="number" placeholder="请输入最大人数或团队数"
                           required>
                </div>
                <label class="col-sm-2 control-label">场地：</label>
                <div class="col-sm-4">
                    <select name="competitionPlace" class="form-control">
                        <option th:each="site : ${siteList}" th:value="${site.id}" th:text="${site.name}"></option>
                    </select>
                </div>
                <!--<input name="competitionPlace" class="form-control" type="text" placeholder="请输入场地名称" maxlength="50">-->
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-2 control-label is-required">报名费用：</label>
                <div class="col-sm-4">
                    <input name="competitionExpense" class="form-control" type="number" placeholder="请输入报名费用"
                           required>
                </div>
                <label class="col-sm-2 control-label is-required">观看费用：</label>
                <div class="col-sm-4">
                    <input name="viewingTicket" class="form-control" type="number" placeholder="请输入观看费用"
                           required>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-2 control-label is-required">赛事开始时间：</label>
                <div class="col-sm-4">
                    <div class="input-group date">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        <input name="applyStartTime" type="text" class="form-control" id="applyStartTime"
                               placeholder="年-月-日 时:分" required>
                    </div>
                </div>
                <label class="col-sm-2 control-label is-required">赛事结束时间：</label>
                <div class="col-sm-4">
                    <div class="input-group date">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        <input name="applyEndTime" type="text" class="form-control" id="applyEndTime"
                               placeholder="年-月-日 时:分" required>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-2 control-label is-required">取消报名截至时间：</label>
                <div class="col-sm-4">
                    <select name="applyBeforeTime" class="form-control" required>
                        <option value="1">赛事开始前1小时</option>
                        <option value="2">赛事开始前2小时</option>
                        <option value="3">赛事开始前3小时</option>
                        <option value="6">赛事开始前6小时</option>
                        <option value="12">赛事开始前12小时</option>
                        <option value="24">赛事开始前24小时</option>
                        <option value="48">赛事开始前48小时</option>
                    </select>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-2 control-label is-required">赛事详情：</label>
                <div class="col-sm-4">
                    <input type="hidden" class="form-control" name="competitionDetails" required>
                    <div class="summernote" id="competitionDetails"></div>
                </div>


                <label class="col-sm-2 control-label">报名须知：</label>
                <div class="col-sm-4">
                    <input type="hidden" class="form-control" name="registrationNotes">
                    <div class="summernote" id="registrationNotes"></div>
                </div>


            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">封面：</label>
            <div class="col-sm-10">
                <!-- 图片上传组件 -->
                <div id="image-upload-container"></div>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: datetimepicker-js"/>
<th:block th:include="include :: summernote-js"/>
<th:block th:include="include :: image-upload-js"/>

<script th:inline="javascript">
    var prefix = ctx + "competition"
    $("#form-competition-add").validate({
        focusCleanup: true,
        rules: {
            teamMax: {
                digits: true
            },
            competitionExpense: {
                required: true, // 必填
                digits: true, // 必须为整数
                min: 1 // 最小值为1，确保为正整数
            },
            viewingTicket: {
                required: true, // 必填
                digits: true, // 必须为整数
                min: 1 // 最小值为1，确保为正整数
            }
        },
        messages: {
            competitionExpense: {
                required: "报名费用不能为空",
                digits: "报名费用必须为整数",
                min: "报名费用必须大于0"
            },
            viewingTicket: {
                required: "观看费用不能为空",
                digits: "观看费用必须为整数",
                min: "观看费用必须大于0"
            }
        }
    });

    function submitHandler() {
        var uploadInstance = $('#image-upload-container').data('imageUpload');

        // 检查是否有上传组件实例
        if (uploadInstance) {
            var uploadedFiles = uploadInstance.getFiles();
            console.log('已上传的图片:', uploadedFiles);

            // 如果需要封面必填
            if (uploadedFiles.length === 0) {
                $.modal.alertWarning("请上传封面图片");
                return false;
            }

            // 将图片URL数组转换为逗号分隔的字符串
            var imageUrls = uploadedFiles.join(',');
            console.log('图片URL字符串:', imageUrls);

            // 注意：图片上传组件已经通过 addHiddenField 方法添加了隐藏字段
            // 我们不需要再次添加，只需要确保所有图片都已被收集
            // 组件会自动处理隐藏字段
        } else {
            // 如果没有上传组件实例，直接检查是否有隐藏字段
            var existingImages = $('#form-competition-add input[name="competitionImg"]').map(function() {
                return $(this).val();
            }).get().filter(function(val) {
                return val && val.trim() !== '';
            });

            if (existingImages.length === 0) {
                $.modal.alertWarning("请上传封面图片");
                return false;
            }
        }

        var applyStartTime = $('#applyStartTime').val()
        var applyEndTime = $('#applyEndTime').val()
        var currentTime = getNowDate() // 当前时间，格式为 YYYY-MM-DD HH:MM

        if ($.validate.form()) {

            // 检查赛事开始时间不能小于当前时间
            if (applyStartTime < currentTime) {
                $.modal.alertWarning("赛事开始时间不能小于当前时间");
                return false;
            }

            // 检查赛事结束时间不能小于赛事开始时间
            if (applyEndTime < applyStartTime) {
                $.modal.alertWarning("赛事结束时间不能小于赛事开始时间");
                return false;
            }

            $.operate.save(prefix + "/add", $('#form-competition-add').serialize());
        }
    }

    $("input[name='applyStartTime']").datetimepicker({
        format: "yyyy-mm-dd hh:ii",
        autoclose: true
    });

    $("input[name='applyEndTime']").datetimepicker({
        format: "yyyy-mm-dd hh:ii",
        autoclose: true
    });

    function getNowDate() {
        // 获取当前时间
        var now = new Date();

        // 格式化日期和时间
        var year = now.getFullYear(); // 获取年份
        var month = ("0" + (now.getMonth() + 1)).slice(-2); // 获取月份，加1是因为 getMonth() 返回的月份是从0开始的
        var day = ("0" + now.getDate()).slice(-2); // 获取日期
        var hours = ("0" + now.getHours()).slice(-2); // 获取小时
        var minutes = ("0" + now.getMinutes()).slice(-2); // 获取分钟

        // 拼接成所需的格式
        return year + "-" + month + "-" + day + " " + hours + ":" + minutes;

    }

    $(function () {
        $('.summernote').summernote({
            lang: 'zh-CN',
            dialogsInBody: true,
            height: 300,
            callbacks: {
                onChange: function (contents, $edittable) {
                    $("input[name='" + this.id + "']").val(contents);
                },
                onImageUpload: function (files) {
                    var obj = this;
                    var data = new FormData();
                    data.append("file", files[0]);
                    $.ajax({
                        type: "post",
                        url: ctx + "common/upload",
                        data: data,
                        cache: false,
                        contentType: false,
                        processData: false,
                        dataType: 'json',
                        success: function (result) {
                            if (result.code == web_status.SUCCESS) {
                                $('#' + obj.id).summernote('insertImage', result.url);
                            } else {
                                $.modal.alertError(result.msg);
                            }
                        },
                        error: function (error) {
                            $.modal.alertWarning("图片上传失败。");
                        }
                    });
                }
            }
        });


        // 初始化图片上传组件
        $('#image-upload-container').imageUpload({
            uploadUrl: ctx + "common/upload",
            maxFiles: 3,
            maxSize: 5 * 1024 * 1024,
            allowedTypes: ['image/jpeg', 'image/png'],
            previewWidth: 200,
            previewHeight: 150,
            inputName: 'competitionImg'
        });
    });
</script>
</body>
</html>