<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="utf-8">
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta content="" name="keywords">
    <meta content="" name="author">
    <meta content="" name="robots">
    <meta content="width=device-width, initial-scale=1" name="viewport">

    <!-- PAGE TITLE HERE -->
    <title>白名单申请</title>

    <link href="/css/nice-select.css" rel="stylesheet">
    <link href="/css/lightgallery.min.css" rel="stylesheet">
    <link href="/css/style.css" rel="stylesheet">
    <link href="/layui/css/layui.css" rel="stylesheet">

    <style>
        .flex-blank {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            padding: 15px;
            border: 1px solid #eee;
            border-radius: 4px;
        }

        .flex-blank input {
            display: inline-block;
            width: fit-content;
            min-width: 80px;
            max-width: 200px;
            block-size: auto;
            flex: 0 1 auto;
            font-size: 14px;
            box-sizing: border-box;
        }

        /* 可选：调整标题与容器的间距 */
        .form-label p {
            margin-bottom: 5px;
        }
    </style>

</head>

<body>
<div id="preloader">
    <div class="lds-ripple">
        <div></div>
        <div></div>
    </div>
</div>

<div id="main-wrapper">
    <div class="header" style="margin-left: 0;padding-left: 0">
        <div class="header-content">

            <nav class="navbar navbar-expand">
                <div class="collapse navbar-collapse justify-content-between">
                    <div class="header-left">

                        <div class="dashboard_bar text-primary">
                            闲趣时坞
                        </div>

                    </div>

                    <h2 class="text-primary">
                        白名单申请
                    </h2>
                    <ul class="navbar-nav header-right">
                        <li class="nav-item dropdown header-profile">
                            <a class="nav-link" data-bs-toggle="dropdown" href="javascript:void(0);" role="button">
                                <img alt="" th:if="${avatar == null}" src="/picture/5.png">
                                <img th:if="${avatar != null}" th:src="@{'data:image/jpeg;base64,' + ${avatar}}">
                            </a>
                            <div class="dropdown-menu dropdown-menu-end">
                                <a class="dropdown-item ai-icon" th:if="${session.qq != null}">
                                    <span class="ms-2" th:text="${session.qq}"></span>
                                </a>
                                <a class="dropdown-item ai-icon" th:if="${session.mcName != null}">
                                    <span class="ms-2" th:text="${session.mcName}"></span>
                                </a>
                                <a class="dropdown-item ai-icon" href="/player/logout">
                                    <span class="ms-2">重新输入qq和游戏id</span>
                                </a>
                            </div>
                        </li>
                    </ul>
                </div>
            </nav>
        </div>
    </div>

    <div class="content-body" style="margin-left: 0">
        <div class="container-fluid">
            <div class="row">
                <div class="col-xl-4">
                    <div class="row">
                        <div class="col-xl-12">
                            <div class="widget-timeline dlab-scroll style-1 ps ps--active-y p-3" id="DZ_W_TimeLine02">
                                <ul class="timeline">
                                    <li>
                                        <div class="timeline-badge primary"></div>
                                        <a class="timeline-panel text-muted" href="javascript:void(0);">
                                            <span>最近</span>
                                            <h6 class="mb-0">8周目合拍照<img alt=""
                                                                             class="img-fluid w-100"
                                                                             src="/pic/1-1.png"></h6>
                                            <p class="mb-0">来也匆匆，去也匆匆</p>
                                            <h6 class="mb-0">8周目刚开始时<img alt=""
                                                                                            class="img-fluid w-100"
                                                                                            src="/pic/1_1.png"></h6>
                                            <p class="mb-0">机械动力，太卡了XwX</p>
                                        </a>

                                    </li>
                                    <li>
                                        <div class="timeline-badge info"></div>
                                        <a class="timeline-panel text-muted" href="javascript:void(0);">
                                            <span>早些时候……</span>
                                            <h6 class="mb-0">玩家合影！
                                                <img alt="" class="img-fluid mb-2 w-100" src="/pic/2.jpeg">
                                                <img alt="" class="img-fluid w-100" src="/pic/2-1.png">
                                            </h6>
                                            <p class="mb-0">还记得这是第几周目吗~</p>
                                        </a>
                                    </li>
                                    <li>
                                        <div class="timeline-badge danger"></div>
                                        <a class="timeline-panel text-muted" href="javascript:void(0);">
                                            <span>这是四周目~</span>
                                            <h6 class="mb-0">天境奇景~
                                                <img alt="" class="img-fluid mb-2 w-100" src="/pic/3.png">
                                                <img alt="" class="img-fluid w-100" src="/pic/3-1.png">
                                            </h6>
                                            <p class="mb-0">itt3神力</p>
                                        </a>
                                    </li>
                                    <li>
                                        <div class="timeline-badge success">
                                        </div>
                                        <a class="timeline-panel text-muted" href="javascript:void(0);">
                                            <span>还发生了……</span>
                                            <h6 class="mb-0">❤impact启动❤
                                                <img alt="" class="img-fluid mb-2 w-100" src="/pic/4.png">
                                                <img alt="" class="img-fluid w-100" src="/pic/4-1.jpeg">
                                            </h6>
                                            <p class="mb-0">某鸢：我的战绩</p>
                                        </a>
                                    </li>
                                    <li>
                                        <div class="timeline-badge warning"></div>
                                        <a class="timeline-panel text-muted" href="javascript:void(0);">
                                            <span>依然四周目</span>
                                            <h6 class="mb-0">开会
                                                <img alt="" class="img-fluid mb-2 w-100" src="/pic/5.jpeg">
                                                <img alt="" class="img-fluid w-100" src="/pic/5-1.jpeg">
                                            </h6>
                                            <p class="mb-0">讨论如何开impact（bushi）</p>
                                        </a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xl-8">
                    <div class="card">
                        <div class="card-body">
                            <div class="profile-tab">
                                <div class="custom-tab-1">
                                    <ul class="nav nav-tabs">
                                        <li class="nav-item"><a class="nav-link active show" data-bs-toggle="tab"
                                                                href="#about-me">关于我们</a></li>
                                        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab"
                                                                href="#profile-settings">白名单申请</a></li>
                                    </ul>
                                    <div class="tab-content">
                                        <div class="tab-pane fade active show" id="about-me">
                                            <div class="profile-about-me">
                                                <div class="pt-4 border-bottom-1 pb-3">
                                                    <h4 class="text-primary">关于我们</h4>
                                                    <p class="mb-0">
                                                        这是一个普普通通，爱好涩涩(划掉)和平的正版服务器。在这里，你可以看到许多你未曾见闻的东西……</p>
                                                    <p class="mb-0">
                                                        你可以在闲趣时坞简单地发展发展科技，打造属于自己的全自动生产线（造成卡服的时候还能体验到被管理破门而入的快感）；</p>
                                                    <p class="mb-0">
                                                        也可以拿起你的鱼竿，建造一个简单温馨的小房子，然后开始养老（虽然你每次挂机回来大概率都会发现自己被绑着）；</p>
                                                    <p class="mb-0">
                                                        当然也可以拿起你的绳子到处去绑人（虽然但是，还是小心别把人惹恼了比较好……）；</p>
                                                    <p class="mb-0">
                                                        当然！你也可以去找几个可爱的宠物，亦或者是……去当宠物……❤</p>
                                                </div>
                                            </div>
                                            <div class="profile-skills mb-5">
                                                <h4 class="text-primary mb-2">服务器标签</h4>
                                                <a class="btn btn-primary light btn-xs mb-1" href="javascript:void(0);">养老</a>
                                                <a class="btn btn-primary light btn-xs mb-1" href="javascript:void(0);">生存</a>
                                                <a class="btn btn-primary light btn-xs mb-1" href="javascript:void(0);">轻科技</a>
                                                <a class="btn btn-primary light btn-xs mb-1" href="javascript:void(0);">捆绑</a>
                                                <a class="btn btn-primary light btn-xs mb-1" href="javascript:void(0);">涩涩</a>
                                                <a class="btn btn-primary light btn-xs mb-1" href="javascript:void(0);">正版</a>
                                                <a class="btn btn-primary light btn-xs mb-1" href="javascript:void(0);">长期</a>
                                            </div>
                                            <div class="profile-lang  mb-5">
                                                <h4 class="text-primary mb-2">服务器文档</h4>
                                                <a class="text-muted pe-3 f-s-16" href="javascript:void(0);"><i
                                                        class="flag-icon flag-icon-us"></i> 请加群获取</a>
                                            </div>
                                            <div class="profile-personal-info">
                                                <h4 class="text-primary mb-4">服务器目前状态</h4>
                                                <div class="row mb-2">
                                                    <div class="col-sm-3 col-5">
                                                        <h5 class="f-w-500">正版验证 <span class="pull-end">:</span>
                                                        </h5>
                                                    </div>
                                                    <div class="col-sm-9 col-7"><span>开启</span>
                                                    </div>
                                                </div>
                                                <div class="row mb-2">
                                                    <div class="col-sm-3 col-5">
                                                        <h5 class="f-w-500">白名单系统 <span class="pull-end">:</span>
                                                        </h5>
                                                    </div>
                                                    <div class="col-sm-9 col-7"><span>开启</span>
                                                    </div>
                                                </div>
                                                <div class="row mb-2">
                                                    <div class="col-sm-3 col-5">
                                                        <h5 class="f-w-500">服务器群 <span class="pull-end">:</span>
                                                        </h5>
                                                    </div>
                                                    <div class="col-sm-9 col-7"><span>538751386</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="tab-pane fade" id="profile-settings">
                                            <div class="pt-3">
                                                <div class="settings-form" th:if="${session.apply == null}">
                                                    <form id="questionForm" enctype="multipart/form-data">
	                                                    <input type="hidden" name="code" id="code">
                                                        <div class="row" id="addressSelect">
                                                            <h4 class="text-primary">
                                                                <label class="form-label">请登记你的地址（仅用于统计数据）</label>
                                                            </h4>
                                                            <div class="mb-3 col-xl-4">
                                                                <select class="form-control form-select wide"
                                                                        id="provinceSelect"
                                                                        onchange="changeNext(this,$('#citySelect'))"
                                                                        required>
                                                                    <option value="">请选择省份</option>
                                                                </select>
                                                            </div>
                                                            <div class="mb-3 col-xl-4">
                                                                <select class="form-control form-select wide" disabled
                                                                        id="citySelect"
                                                                        onchange="changeNext(this,$('#districtSelect'))"
                                                                        required>
                                                                    <option value="">请选择城市</option>
                                                                </select>
                                                            </div>
                                                            <div class="mb-3 col-xl-4">
                                                                <select class="form-control form-select wide" disabled
                                                                        id="districtSelect"
                                                                        onchange="updateCode(this)"
                                                                        required>
                                                                    <option value="">请选择区县</option>
                                                                </select>
                                                            </div>
                                                            <h4 class="text-primary">
                                                                <label class="form-label">来历（尽量具体，如b站视频bv号）</label>
                                                            </h4>
                                                            <div class="mb-3 ">
                                                                <input type="text" class="form-control" id="description">
                                                            </div>
                                                        </div>
                                                        <button id="getQuestion" class="btn btn-primary" type="button" style="margin-bottom: 20px">打开白名单问卷</button>
                                                        <div class="row" id="questionContainer">

                                                        </div>
	                                                    <button id="putQuestion" class="btn btn-primary" type="button" style="display:none;">提交答案</button>
                                                    </form>
                                                </div>
	                                            <div th:if="${session.apply != null}">
		                                            <h2 class="text-primary" th:if="${session.apply == 1}">你已经通过申请了</h2>
		                                            <h2 class="text-primary" th:if="${session.apply == 2}">申请正在处理中</h2>
		                                            <h2 class="text-primary" th:if="${session.apply == 3}">你的申请被拒绝了</h2>
		                                            <h2 class="text-primary" th:if="${session.apply > 3 || session.apply < 1}">申请状态出错，请联系管理</h2>
                                                    <h2 class="text-primary" th:if="${session.apply == 1 || session.apply == 3}" th:text="${'答题得分：' + session.score}"></h2>
	                                            </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="footer">
        <div class="copyright">
            <p>@闲趣时坞 qq群号538751386</p>
        </div>
    </div>
</div>

<script id="questionData" type="text/html">
	<div>
		{{# if(d.optionQuestions != null) { }}
		<h4 class="text-primary">一、选择题</h4>
		<div class="mb-3" id="optionContainer"></div>
		{{# } }}

		{{# if(d.blankQuestions != null) { }}
		<h4 class="text-primary">二、填空题</h4>
		<div class="mb-3" id="blankContainer"></div>
		{{# } }}

		{{# if(d.textQuestions != null) { }}
		<h4 class="text-primary">三、简答题</h4>
		<div class="mb-3" id="textareaContainer"></div>
		{{# } }}
	</div>
</script>

<script id="optionTpl" type="text/html">
    {{# for(let i = 0; i < d.optionQuestions.length; i++) { }}
    <div class="form-label" style="width: 100%; margin-bottom: 10px">
	    <input type="hidden" class="question-id" value="{{d.optionQuestions[i].id}}">
        <span style="font-size: medium">{{(i+1) + '. ' + d.optionQuestions[i].title}}</span>
	    {{# const options = JSON.parse(d.optionQuestions[i].options) }}
        {{# for(let j = 0; j < options.length; j++) { }}
        <div class="layui-form-item" style="position: relative; margin-bottom: 10px; display: flex; align-items: center;">

            <div class="layui-input-inline" style="width: auto; height:100%; text-align: left;">
                <input type="checkbox" class="form-check-input option-checkbox" style="padding:55%;">
            </div>
            <div class="layui-input-inline" style="width: 100%">
                <input type="text" class="form-control option-input" readOnly value="{{options[j]}}">
            </div>
        </div>
        {{# } }}
    </div>
    {{# } }}
</script>
<script id="blankTpl" type="text/html">
	{{# for(let i = 0; i < d.blankQuestions.length; i++) { }}
	<div class="form-label" style="width: 100%; margin-bottom: 10px">
		<input type="hidden" class="question-id" value="{{d.blankQuestions[i].id}}">
		<span style="font-size: medium">{{(i+1) + '. ' + d.blankQuestions[i].title}}</span>
		<div class="layui-form-item flex-blank">
			{{# const options = JSON.parse(d.blankQuestions[i].options) }}
			{{# for(let j = 0; j < options.length; j++) { }}

			{{# if(options[j] === '${}') { }}
			<input type="text" class="form-control blank-answer" placeholder="请输入答案">
			{{# } else { }}
			<span>{{options[j]}}</span>
			{{# } }}

			{{# } }}
		</div>
	</div>
	{{# } }}
</script>
<script id="textareaTpl" type="text/html">
	{{# for(let i = 0; i < d.textQuestions.length; i++) { }}
	<div class="form-label" style="width: 100%; margin-bottom: 10px">
		<input type="hidden" class="question-id" value="{{d.textQuestions[i].id}}">
		<span style="font-size: medium">{{(i+1) + '. ' + d.textQuestions[i].title}}</span>
		<div class="layui-form-item">
			<textarea class="form-text text-answer" style="width: 100%" rows="3"></textarea>
		</div>
	</div>
	{{# } }}
</script>

<script src="/js/jquery.3.6.0.js"></script>
<script src="/js/global.min.js"></script>
<script src="/js/custom.min.js"></script>
<script src="/js/sweetalert.js"></script>
<script src="/js/styleSwitcher.js"></script>
<script src="/layui/layui.js"></script>
<script src="/js/bootstrap-select.min.js"></script>

<script>

    function initCascader() {
        // 加载省份数据
        $.ajax({
            url: "/api/region/findRegion",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({level: 1}),
            success: function (data) {
                if (data.code === 200) {
                    const $province = $('#provinceSelect');
                    $province.empty().append('<option value="">请选择省份</option>');
                    data.data.forEach(region => {
                        $province.append($('<option></option>').val(region.code).text(region.name));
                    });
                }
            },
            error: function () {
                console.error('省份数据加载失败');
            }
        });
    }
    $(document).ready(function () {
        initCascader()
    })
    function updateCode(input) {
        $('#code').val(Number.parseInt(input.value))
    }
    function changeNext(input, next) {
        if (input != null) {
            if (next != null) {
                if (!input.value) return
                $.ajax({
                    url: "/api/region/findRegion",
                    type: "POST",
                    contentType: "application/json",
                    data: JSON.stringify({parentCode: input.value}),
                    success: function (data) {
                        if (data.code === 200) {
                            next.empty().append('<option value="">请选择</option>')
                            next.prop('disabled', false)
                            data.data.forEach(region => {
                                next.append(
                                    $('<option></option>')
                                        .val(region.code)
                                        .text(region.name)
                                )
                            })
                        }
                    },
                    error: function () {
                        $('#provinceSelect').html('<option value="">数据加载失败</option>');
                        console.error('区域数据加载异常');
                    }
                });
            }
        }
    }
    function adjustInputWidth($input) {
        const value = $input.val().trim() || '请输入答案';

        // 获取输入框的字体样式（确保与span一致）
        const fontStyle = {
            fontFamily: $input.css('font-family'),
            fontSize: $input.css('font-size'),
            fontWeight: $input.css('font-weight'),
            lineHeight: $input.css('line-height'),
            whiteSpace: 'nowrap'  // 不换行，确保文字一行显示
        };

        // 创建隐藏的span元素（用于计算文字宽度）
        const $span = $('<span></span>')
            .text(value)
            .css(fontStyle)
            .css({
                visibility: 'hidden',  // 隐藏但保留布局
                position: 'absolute',  // 脱离文档流，不影响页面
                top: '-9999px'         // 放到页面外，避免干扰
            });

        // 添加span到页面（必须添加才能获取宽度）
        $('body').append($span);
        // 获取文字宽度（span的outerWidth，不含边框）
        const textWidth = $span.outerWidth();
        // 移除span（避免占用内存）
        $span.remove();

        // 计算输入框的内边距总和（左右padding）
        const paddingLeft = parseInt($input.css('padding-left'));
        const paddingRight = parseInt($input.css('padding-right'));
        const totalPadding = paddingLeft + paddingRight;

        // 计算输入框需要的宽度（文字宽度 + 内边距）
        const inputWidth = textWidth + totalPadding + 5;
        // 获取最小宽度（避免输入框过窄）
        const minWidth = parseInt($input.css('min-width'));

        // 设置输入框宽度（取最大值，不小于最小宽度）
        $input.css('width', Math.max(inputWidth, minWidth) + 'px');
    }
    var resData;
    $('#getQuestion').on('click', function (){
	    if($('#getQuestion').text() === '重置答案'){
            loadQuestion(resData)
		    return
	    }
        var code = $('#code').val();
        var description = $('#description').val()
        $.ajax({
            url: '/api/answer/getQuestion',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({code:code, description: description}),
            success: function (res) {
                if (res.code === 200) {
                    resData = res.data;
					$('#addressSelect').hide()
	                $('#getQuestion').text('重置答案')
	                $('#putQuestion').show()
                    loadQuestion(res.data)
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: '失败',
                        text: res.msg,
                        showConfirmButton: true
                    });
                }
            },
            error: function () {
                Swal.fire({
                    icon: 'error',
                    title: '失败',
                    text: '操作失败',
                    showConfirmButton: true
                });
            }
        });
    })

    var answerJson = [];
    $('#putQuestion').on('click', function (){
        answerJson = [];
        var $questionContainer = $('#questionContainer');
        $questionContainer.find('#optionContainer .form-label').each(function (){
            var answer = {}
	        var check = [];
	        $(this).find('.option-checkbox').each(function (){
                check.push($(this).prop('checked'))
	        })
            answer['id'] = Number.parseInt($(this).find('.question-id').val());
            answer['type'] = 1;
	        answer['answer'] = JSON.stringify(check);
            answerJson.push(answer)
        })

        $questionContainer.find('#blankContainer .form-label').each(function (){
            var answer = {}
            var blank = [];
            $(this).find('.blank-answer').each(function (){
                blank.push($(this).val())
            })
            answer['id'] = Number.parseInt($(this).find('.question-id').val());
            answer['type'] = 2;
            answer['answer'] = JSON.stringify(blank);
            answerJson.push(answer)
        })

        $questionContainer.find('#textareaContainer .form-label').each(function (){
            var answer = {}
            answer['id'] = Number.parseInt($(this).find('.question-id').val());
            answer['type'] = 3;
            $(this).find('.text-answer').each(function (){
                answer['answer'] = $(this).val()
            })
            answerJson.push(answer)
        })
        Swal.fire({
            title: "确认提交答案？",
            text: "一经提交将无法更改",
            icon: "question",
            showCancelButton: true,
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                $('#putQuestion').prop('disabled', true)
                $.ajax({
                    url: '/api/answer/putQuestion',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(answerJson),
                    success: function (res) {
                        if (res.code === 200) {
                            Swal.fire({
                                icon: 'success',
                                title: '成功',
                                text: res.msg,
                                showConfirmButton: true
                            }).then(() => {
                                location.reload()
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: '失败',
                                text: res.msg,
                                showConfirmButton: true
                            });
                            $('#putQuestion').prop('disabled', false)
                        }
                    },
                    error: function () {
                        Swal.fire({
                            icon: 'error',
                            title: '失败',
                            text: "操作失败",
                            showConfirmButton: true
                        });
                        $('#putQuestion').prop('disabled', false)
                    }
                });
                Swal.fire({
                    icon: 'warning',
                    title: '提交中……',
                    text: '请稍等几秒',
                    showConfirmButton: false
                });
            }
        });
    })
    function loadQuestion(data) {
        var questionDom = layui.laytpl($('#questionData').html()).render(data);
        var $questionDom = $(questionDom);
        var textareaData = null, optionData = null, blankData = null;
        if(data.textQuestions){
            textareaData = layui.laytpl($('#textareaTpl').html()).render(data);
        }
        if(data.optionQuestions){
            optionData = layui.laytpl($('#optionTpl').html()).render(data);
        }
        if(data.blankQuestions) {
            blankData = layui.laytpl($('#blankTpl').html()).render(data);
        }
        $questionDom.find('#textareaContainer').html(textareaData)
        $questionDom.find('#optionContainer').html(optionData)
        $questionDom.find('#blankContainer').html(blankData)

        var $questionContainer = $('#questionContainer');
        $questionContainer.html($questionDom.html());
        $questionContainer.on('input', '#blankContainer .form-control', function () {
            adjustInputWidth($(this));
        });
        $('#questionContainer #blankContainer .form-control').each(function () {
            adjustInputWidth($(this));
        });
    }

</script>

</body>
</html>