<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <script th:src="@{/js/jquery.min.js}"></script>
    <script th:src="@{/js/jquery.i18n.properties.js}"></script>
    <div id="root-path" th:text="${#servletContext.contextPath}" style="display:none;"></div>
    <div id="lang-country" th:text="${#locale.language + '_' + #locale.country}" style="display:none;"></div>
    <script th:src="@{/js/i18n.js}"></script>
    <title th:text="#{user.login.title}"></title>
    <meta name="description" content="呼叫管理系统">
    <link href="../static/css/bootstrap.min.css" th:href="@{/css/bootstrap.min.css}" rel="stylesheet"/>
    <link href="../static/css/font-awesome.min.css" th:href="@{/css/font-awesome.min.css}" rel="stylesheet"/>
    <link href="../static/css/style.min.css" th:href="@{/css/style.min.css}" rel="stylesheet"/>
    <link href="../static/css/login.min.css" th:href="@{/css/login.min.css}" rel="stylesheet"/>
    <link href="../static/css/theme-modern.css" th:href="@{/css/theme-modern.css?v=20260524}" rel="stylesheet"/>
    <link href="../static/ruoyi/css/ry-ui.css" th:href="@{/ruoyi/css/ry-ui.css?v=4.7.10}" rel="stylesheet"/>
    <link th:href="@{/ajax/libs/select2/select2.min.css?v=4.0.13}" rel="stylesheet"/>
    <link th:href="@{/ajax/libs/select2/select2-bootstrap.min.css?v=4.0.13}" rel="stylesheet"/>
    <!-- 360浏览器急速模式 -->
    <meta name="renderer" content="webkit">
    <!-- 避免IE使用兼容模式 -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="shortcut icon" href="../static/favicon.ico" th:href="@{favicon.ico}"/>
    <style type="text/css">label.error { position:inherit;  }</style>
    <script>
        (function () {
            var inFrame = false;
            try { inFrame = window.self !== window.top; } catch (e) { inFrame = true; }
            var embed = /(?:^|[?&])embed=1(?:&|$)/.test(window.location.search || '');
            // 只要在 iframe 里就按 HIS 嵌入处理（防止 Shiro 踢回 /login 时丢掉 embed=1）
            if (inFrame || embed) {
                try {
                    document.documentElement.className += ' his-ipcc-embed';
                } catch (e) {}
                try { window.alert = function () {}; } catch (e) {}
                // URL 丢了 embed 时补回，避免后续语言脚本按非嵌入逻辑整页跳
                if (inFrame && !embed) {
                    try {
                        var p = new URLSearchParams(window.location.search || '');
                        p.set('embed', '1');
                        if (!p.get('lang')) {
                            p.set('lang', localStorage.getItem('lang') || 'zh_CN');
                        }
                        window.history.replaceState({}, document.title, window.location.pathname + '?' + p.toString());
                    } catch (e) {}
                }
                return;
            }
            // 仅非 iframe 的嵌套页才尝试顶层跳转（正常单页登录不会进这里）
            if (window.top !== window.self) {
                try { window.top.location = window.location; } catch (e) {}
            }
        })();
    </script>
    <style>
        html.his-ipcc-embed body.signin { background: transparent !important; }
        html.his-ipcc-embed .signinpanel,
        html.his-ipcc-embed .language-selector,
        html.his-ipcc-embed .signup-footer { display: none !important; }
    </style>

    <script th:inline="javascript">
        // //获取国际化翻译值
        // console.log("-----------------")
        // console.log(ROOT)
        // console.log(LANG_COUNTRY)
        // console.log(i18n('user.login.username'));
        // console.log(i18n('user.login.password'));
        // console.log(i18n('user.login.code'));
        // console.log(i18n('user.login.remember'));
        // console.log(i18n('user.login.submit'));
    </script>

    <style>
        .language-selector {
            position: absolute;
            top: 10px;
            right: 10px;
            display: flex;
            gap: 10px;
        }

        .lang-option {
            color: #fff;
            text-decoration: none;
            font-size: 14px;
        }

        .lang-option:hover {
            text-decoration: underline;
        }

        /* 下拉框样式 - 白色背景，黑色文字 */
        #groupId {
            background-color: #ffffff;   /* 白色背景 */
            color: #333333;              /* 黑色文字 */
            border: 1px solid #dcdcdc;   /* 浅灰色边框 */
            border-radius: 3px;
            padding: 8px 12px;
            height: 40px;
            font-size: 14px;
            width: 100%;
            cursor: pointer;
        }

        /* 下拉框选项样式 */
        #groupId option {
            background-color: #ffffff;   /* 选项白色背景 */
            color: #333333;              /* 选项黑色文字 */
            padding: 8px;
        }

        /* 下拉框聚焦样式 */
        #groupId:focus {
            background-color: #ffffff;
            border-color: #1abc9c;
            outline: none;
            color: #333333;
        }

        /* 下拉框悬停样式 */
        #groupId:hover {
            background-color: #f5f5f5;   /* 悬停时浅灰背景 */
        }

        /* 占位符选项样式（第一个选项） */
        #groupId option:first-child {
            color: #999999;              /* 灰色提示文字 */
        }

        /* 外呼网关：与登录表单统一的分段切换 */
        .gateway-field {
            margin-top: 14px;
        }
        .gateway-field-label {
            display: block;
            margin: 0 0 8px;
            color: #6b7280;
            font-size: 13px;
            font-weight: 500;
            letter-spacing: 0.02em;
        }
        .gateway-seg {
            display: flex;
            padding: 4px;
            border: 1px solid #dbe1ee;
            border-radius: 12px;
            background: #f3f5fa;
            gap: 4px;
        }
        .gateway-seg label {
            flex: 1;
            position: relative;
            margin: 0;
            cursor: pointer;
            font-weight: 500;
        }
        .gateway-seg input[type="radio"] {
            position: absolute;
            opacity: 0;
            pointer-events: none;
        }
        .gateway-seg-item {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            height: 36px;
            border-radius: 9px;
            color: #6b7280;
            font-size: 13px;
            line-height: 1;
            transition: background .18s ease, color .18s ease, box-shadow .18s ease;
            user-select: none;
        }
        .gateway-seg-item i {
            font-size: 13px;
            opacity: .85;
        }
        .gateway-seg input[type="radio"]:checked + .gateway-seg-item {
            background: #fff;
            color: #1d6fe8;
            box-shadow: 0 2px 8px rgba(15, 23, 42, 0.08);
            font-weight: 600;
        }
        .gateway-seg label:hover .gateway-seg-item {
            color: #374151;
        }
        .gateway-seg input[type="radio"]:checked + .gateway-seg-item:hover {
            color: #1d6fe8;
        }
        #gatewaySelectWrap {
            margin-top: 10px;
            display: none;
            animation: gwFadeIn .2s ease;
        }
        @keyframes gwFadeIn {
            from { opacity: 0; transform: translateY(-4px); }
            to { opacity: 1; transform: translateY(0); }
        }
        #gatewaySelectWrap .select2-container {
            width: 100% !important;
        }
        #gatewaySelectWrap .select2-selection--single {
            height: 46px !important;
            border: 1px solid #dbe1ee !important;
            border-radius: 12px !important;
            background-color: #fff !important;
            box-shadow: none !important;
        }
        #gatewaySelectWrap .select2-selection--single:focus,
        #gatewaySelectWrap .select2-container--open .select2-selection--single {
            border-color: #1d6fe8 !important;
        }
        #gatewaySelectWrap .select2-selection__rendered {
            line-height: 44px !important;
            color: #111827 !important;
            padding-left: 16px !important;
            padding-right: 48px !important;
            font-size: 14px;
        }
        #gatewaySelectWrap .select2-selection__placeholder {
            color: #9ca3af !important;
        }
        #gatewaySelectWrap .select2-selection__arrow {
            height: 44px !important;
            width: 28px !important;
            right: 8px !important;
        }
        #gatewaySelectWrap .select2-selection__clear {
            margin-right: 8px;
            font-size: 16px;
            color: #9ca3af;
        }
        .select2-container--bootstrap .select2-dropdown {
            border: 1px solid #dbe1ee !important;
            border-radius: 12px !important;
            box-shadow: 0 12px 28px rgba(15, 23, 42, 0.1) !important;
            overflow: hidden;
            margin-top: 4px;
        }
        .select2-container--bootstrap .select2-results__option {
            padding: 10px 14px;
            font-size: 13px;
        }
        .select2-container--bootstrap .select2-results__option--highlighted {
            background: #eef4ff !important;
            color: #1d6fe8 !important;
        }
        .select2-gw-option {
            display: flex;
            flex-direction: column;
            gap: 2px;
            line-height: 1.3;
        }
        .select2-gw-option .gw-title {
            color: #111827;
            font-size: 13px;
            font-weight: 500;
        }
        .select2-gw-option .gw-sub {
            color: #9ca3af;
            font-size: 12px;
        }
        .select2-results__option--highlighted .select2-gw-option .gw-title {
            color: #1d6fe8;
        }
        .select2-results__option--highlighted .select2-gw-option .gw-sub {
            color: #6b9ef5;
        }
    </style>
</head>
<body class="signin">
    <div class="language-selector">
        <a href="javascript:void(0);" class="lang-option" onclick="setLanguage('en_US')">英语</a>
        <a href="javascript:void(0);" class="lang-option" onclick="setLanguage('zh_CN')">中文</a>
<!--        <a href="javascript:void(0);" class="lang-option" onclick="setLanguage('ja_JP')">日语</a>-->
    </div>
    <div class="signinpanel">
        <div class="row">
            <div class="col-sm-7">
                <div class="signin-info">
                    <div class="m-b"></div>
                    <h2 th:text="#{user.login.welcome} + ' ' + #{sys.sysName} "></h2>
                </div>
            </div>
            <div class="col-sm-5">
                <form id="signupForm" autocomplete="off">
                    <h4 class="no-margins"><span th:text="#{user.login.submit}"></span>：</h4>
                    <input type="text"     name="username" class="form-control uname"     th:attr="placeholder=#{user.login.username}"    />
                    <input type="password" name="password" class="form-control pword"     th:attr="placeholder=#{user.login.password}" />
                    <input type="text"     name="extNum" class="form-control uname"     th:attr="placeholder=#{user.login.extnum}"    />
                    <input type="hidden"   name="myGateway" id="myGateway" value="" />
                    <div class="gateway-field">
                        <span class="gateway-field-label">外呼网关</span>
                        <div class="gateway-seg" role="radiogroup" aria-label="外呼网关">
                            <label>
                                <input type="radio" name="useGateway" value="0" checked="checked" />
                                <span class="gateway-seg-item"><i class="fa fa-random"></i>自动分配</span>
                            </label>
                            <label>
                                <input type="radio" name="useGateway" value="1" />
                                <span class="gateway-seg-item"><i class="fa fa-sitemap"></i>指定网关</span>
                            </label>
                        </div>
                        <div id="gatewaySelectWrap">
                            <select id="gatewaySelect" class="form-control" style="width:100%;">
                                <option value=""></option>
                            </select>
                        </div>
                    </div>
                    <select th:if="${showDynamicGroupid==true}" name="groupId" id="groupId" class="form-control m-t">

                    </select>
                    <div class="row m-t" th:if="${captchaEnabled==true}">
						<div class="col-xs-6">
						    <input type="text" name="validateCode" class="form-control code" placeholder="验证码" maxlength="5" />
						</div>
						<div class="col-xs-6">
							<a href="javascript:void(0);" title="点击更换验证码">
								<img th:src="@{/captcha/captchaImage(type=${captchaType})}" class="imgcode" width="85%"/>
							</a>
						</div>
					</div>
                    <div class="checkbox-custom" th:if="${isRemembered}" th:classappend="${captchaEnabled==false} ? 'm-t'">
				        <input type="checkbox" id="rememberme" name="rememberme"> <label for="rememberme" th:text="#{user.login.remember}"></label>
				    </div>
                    <button class="btn btn-success btn-block" id="btnSubmit" data-loading="正在验证登录，请稍候..."><span th:text="#{user.login.submit}"></span></button>
                </form>
            </div>
        </div>
        <div class="signup-footer">
            <div class="pull-left">
                Copyright 云联 All Rights Reserved. <br>
            </div>
        </div>
    </div>
<script th:inline="javascript">
    var ctx = [[@{/}]];
    var captchaType = [[${captchaType}]];
    var captchaEnabled = [[${captchaEnabled}]];
    var sysVersion = [[${sysVersion}]];
    var showDynamicGroupid = [[${showDynamicGroupid}]];
</script>
<!--[if lte IE 8]><script>window.location.href=ctx+'html/ie.html';</script><![endif]-->
<!-- 全局js -->
<script src="../static/js/jquery.min.js" th:src="@{/js/jquery.min.js}"></script>
<script src="../static/ajax/libs/validate/jquery.validate.min.js" th:src="@{/ajax/libs/validate/jquery.validate.min.js}"></script>
<script src="../static/ajax/libs/layer/layer.min.js" th:src="@{/ajax/libs/layer/layer.min.js}"></script>
<script src="../static/ajax/libs/blockUI/jquery.blockUI.js" th:src="@{/ajax/libs/blockUI/jquery.blockUI.js}"></script>
<script th:src="@{/ajax/libs/select2/select2.min.js?v=4.0.13}"></script>
<script src="../static/ruoyi/js/ry-ui.js" th:src="@{/ruoyi/js/ry-ui.js?v=4.7.11}"></script>
<script src="../static/ruoyi/login.js" th:src="@{/ruoyi/login.js}"></script>
<script th:inline="javascript">
    // 加载业务组列表
    function loadBusiGroups() {
        if (!showDynamicGroupid) return;

        $.ajax({
            url: ctx + 'aicall/api/busigroup/list',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response && response.code === 0) {
                    var $select = $('#groupId');
                    $select.empty();
                    if (response.data && response.data.length > 0) {
                        $.each(response.data, function(index, item) {
                            var value = item.groupId || '';
                            var text = item.bizGroupName || '';
                            $select.append('<option value="' + value + '">' + text + '</option>');
                        });
                    }
                } else {
                    console.error('获取业务组列表失败:', response);
                }
            },
            error: function(xhr, status, error) {
                console.error('请求业务组列表失败:', error);
            }
        });
    }

    function syncMyGateway() {
        var useGateway = $('input[name="useGateway"]:checked').val() === '1';
        if (!useGateway) {
            $('#myGateway').val('');
            return;
        }
        var gw = $('#gatewaySelect').val() || '';
        $('#myGateway').val(gw);
    }

    function toggleGatewaySelect() {
        var useGateway = $('input[name="useGateway"]:checked').val() === '1';
        if (useGateway) {
            $('#gatewaySelectWrap').show();
            // 指定网关时优先默认选中 gwName=outbound
            if (!$('#gatewaySelect').val()) {
                var $outbound = $('#gatewaySelect option').filter(function() {
                    return $(this).attr('data-gwname') === 'outbound';
                }).first();
                if ($outbound.length) {
                    $('#gatewaySelect').val($outbound.val()).trigger('change');
                }
            }
        } else {
            $('#gatewaySelectWrap').hide();
            $('#gatewaySelect').val(null).trigger('change');
        }
        syncMyGateway();
    }

    function formatGatewayOption(opt) {
        if (!opt.id) {
            return opt.text;
        }
        var $el = $(opt.element);
        var title = $el.data('title') || opt.text;
        var sub = $el.data('sub') || '';
        if (!sub) {
            return $('<span class="select2-gw-option"><span class="gw-title"></span></span>')
                .find('.gw-title').text(title).end();
        }
        return $(
            '<span class="select2-gw-option">' +
                '<span class="gw-title"></span>' +
                '<span class="gw-sub"></span>' +
            '</span>'
        ).find('.gw-title').text(title).end()
         .find('.gw-sub').text(sub).end();
    }

    function formatGatewaySelection(opt) {
        if (!opt.id) {
            return opt.text;
        }
        var $el = $(opt.element);
        var title = $el.data('title') || opt.text;
        var sub = $el.data('sub') || '';
        return sub ? (title + ' · ' + sub) : title;
    }

    function initGatewaySelect() {
        $('#gatewaySelect').select2({
            theme: 'bootstrap',
            placeholder: '请选择外呼网关',
            allowClear: true,
            width: '100%',
            dropdownParent: $('.signinpanel form'),
            templateResult: formatGatewayOption,
            templateSelection: formatGatewaySelection,
            language: {
                noResults: function() { return '无匹配网关'; },
                searching: function() { return '搜索中…'; }
            }
        });
        $('#gatewaySelect').on('change', syncMyGateway);
        $('input[name="useGateway"]').on('change', toggleGatewaySelect);
    }

    function loadGateways() {
        $.ajax({
            url: ctx + 'aicall/api/gateway/phonebarList',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                var $select = $('#gatewaySelect');
                $select.empty().append('<option value=""></option>');
                if (response && response.code === 0 && response.data && response.data.length > 0) {
                    $.each(response.data, function(index, item) {
                        // only purposes 1(phonebar) / 3(unlimited), exclude 2
                        var purpose = item.purpose;
                        if (purpose != 1 && purpose != 3) {
                            return;
                        }
                        var id = item.id != null ? String(item.id) : '';
                        var gwName = item.gwName || '';
                        var gwDesc = item.gwDesc || '';
                        var title = gwDesc || gwName || id;
                        var sub = (gwName && gwDesc && gwDesc !== gwName) ? gwName : '';
                        var text = sub ? (title + ' (' + sub + ')') : title;
                        $select.append(
                            $('<option></option>')
                                .attr('value', id)
                                .attr('data-gwname', gwName)
                                .attr('data-title', title)
                                .attr('data-sub', sub)
                                .text(text)
                        );
                    });
                }
                initGatewaySelect();
                toggleGatewaySelect();
            },
            error: function(xhr, status, error) {
                console.error('请求网关列表失败:', error);
                initGatewaySelect();
                toggleGatewaySelect();
            }
        });
    }

    $(document).ready(function() {
        loadBusiGroups();
        loadGateways();
    });
</script>
<script th:inline="javascript">
    function setLanguage(lang) {
        console.log('设置语言：' + lang)
        if (!lang) return;
        localStorage.setItem('lang', lang);
        var inFrame = false;
        try { inFrame = window.self !== window.top; } catch (e) { inFrame = true; }
        var params = new URLSearchParams(window.location.search || '');
        params.set('lang', lang);
        if (inFrame ||
            /(?:^|[?&])embed=1(?:&|$)/.test(window.location.search || '') ||
            document.documentElement.className.indexOf('his-ipcc-embed') >= 0) {
            params.set('embed', '1');
        }
        // iframe 内只用 replaceState，避免整页刷新丢掉登录桥 / 触发顶层跳转
        if (inFrame) {
            try {
                window.history.replaceState({}, document.title, window.location.pathname + '?' + params.toString());
            } catch (e) {
                window.location.href = window.location.pathname + '?' + params.toString();
            }
            return;
        }
        window.location.href = window.location.pathname + '?' + params.toString();
    }

    document.querySelectorAll('.lang-option').forEach(link => {
        link.addEventListener('click', function(event) {
            event.preventDefault();
            setLanguage(this.getAttribute('data-lang'));
        });
    });

    document.addEventListener('DOMContentLoaded', function() {
        var lang = new URLSearchParams(window.location.search).get('lang');
        if (!lang) {
            lang = localStorage.getItem('lang');
        }
        if (!lang) {
            lang = navigator.language || 'en_US';
        }
        console.log('当前语言：' + lang);
        localStorage.setItem('lang', lang);

        var inFrame = false;
        try { inFrame = window.self !== window.top; } catch (e) { inFrame = true; }
        var isEmbed = inFrame ||
            /(?:^|[?&])embed=1(?:&|$)/.test(window.location.search || '') ||
            document.documentElement.className.indexOf('his-ipcc-embed') >= 0;
        if (lang && !new URLSearchParams(window.location.search).has('lang')) {
            if (isEmbed) {
                var p = new URLSearchParams(window.location.search || '');
                p.set('lang', lang);
                p.set('embed', '1');
                try {
                    window.history.replaceState({}, document.title, window.location.pathname + '?' + p.toString());
                } catch (e) {}
            } else {
                setLanguage(lang);
            }
        }
    });

    // document.addEventListener('DOMContentLoaded', function() {
    //     var lang = new URLSearchParams(window.location.search).get('lang') || localStorage.getItem('lang') || 'en_US';
    //     console.log('当前语言：' + lang)
    //     localStorage.setItem('lang', lang); // 更新本地存储的语言设置
    //
    //     // 如果 URL 中没有 lang 参数，且本地存储中有 lang 设置，则更新 URL 参数
    //     if (lang && !new URLSearchParams(window.location.search).has('lang')) {
    //         setLanguage(lang)
    //         // window.history.replaceState({}, document.title, window.location.pathname + "?lang=" + lang);
    //     }
    // });
</script>
</body>
</html>
