<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('修改呼入大模型配置')"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-inboundllm-add" th:object="${ccInboundLlmAccount}">
        <input name="id" th:field="*{id}" type="hidden">

        <!-- 1. 别名 -->
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{inboundllm.form.inboundAlias}"></label>
                <div class="col-sm-8">
                    <input name="inboundAlias" th:field="*{inboundAlias}" class="form-control" type="text" required>
                </div>
            </div>
        </div>

        <!-- 1. 被叫号码 -->
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{inboundllm.form.callee}"></label>
                <div class="col-sm-8">
                    <input name="callee" th:field="*{callee}" class="form-control" type="text" required>
                </div>
            </div>
        </div>

        <!-- 2. 服务类型 -->
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{inboundllm.form.serviceType}"></label>
                <div class="col-sm-8">
                    <select name="serviceType" th:field="*{serviceType}" class="form-control" id="serviceTypeSelect" required>
                        <option value="ai"   th:text="#{inboundllm.form.serviceTypeAI}"></option>
                        <option value="acd"  th:text="#{inboundllm.form.serviceTypeACD}"></option>
                        <option value="ivr"  th:text="#{inboundllm.form.serviceTypeIVR}"></option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 3. 大模型底座 （仅 AI 可见）-->
        <div class="col-xs-12 ai-only">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{inboundllm.form.llmAccountId}"></label>
                <div class="col-sm-8">
                    <select name="llmAccountId" id="llmAccountId" th:field="*{llmAccountId}" class="form-control" required>
                        <option value="" th:text="#{inboundllm.form.llmAccountId.empty}"></option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 4. ASR 提供商（仅 AI 可见） -->
        <div class="col-xs-12 ai-only">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{inboundllm.form.asrProvider}"></label>
                <div class="col-sm-8">
                    <select name="asrProvider" id="asrProvider" th:field="*{asrProvider}" class="form-control" required>
                        <option value="" th:text="#{inboundllm.form.asrProvider.empty}"></option>
                    </select>
                </div>
            </div>
        </div>

        <!-- ASR语言选择（仅 AI 可见） -->
        <div class="col-xs-12 ai-only" id="asrLanguageCodeDiv" style="display:none;">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{inboundllm.form.asrLanguageCode}">ASR语言</label>
                <div class="col-sm-8">
                    <select name="asrLanguageCode" id="asrLanguageCode" th:field="*{asrLanguageCode}" class="form-control" required>
                        <option value="" th:text="#{inboundllm.form.asrLanguageCode.empty}">请选择ASR语言</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 新增：ASR模型选择（仅 AI 可见） -->
        <div class="col-xs-12 ai-only" id="asrModelsDiv" style="display:none;">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{inboundllm.form.asrModels}">ASR模型</label>
                <div class="col-sm-8">
                    <select name="asrModels" id="asrModels" th:field="*{asrModels}" class="form-control" required>
                        <option value="" th:text="#{inboundllm.form.asrModels.empty}">请选择ASR模型</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 5. 音色来源（仅 AI 可见，LocalWavFile 时隐藏） -->
        <div class="col-xs-12 ai-only voice-config">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{inboundllm.form.voiceSource}"></label>
                <div class="col-sm-8">
                    <select name="voiceSource" id="voiceSource" th:field="*{voiceSource}" class="form-control" required>
                        <option value="" th:text="#{inboundllm.form.voiceSource.empty}"></option>
                    </select>
                </div>
            </div>
        </div>

        <!-- TTS语言选择（仅 AI 可见，LocalWavFile 时隐藏） -->
        <div class="col-xs-12 ai-only voice-config" id="ttsLanguageCodeDiv" style="display:none;">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{inboundllm.form.ttsLanguageCode}">TTS语言</label>
                <div class="col-sm-8">
                    <select name="ttsLanguageCode" id="ttsLanguageCode" th:field="*{ttsLanguageCode}" class="form-control" required>
                        <option value="" th:text="#{inboundllm.form.ttsLanguageCode.empty}">请选择TTS语言</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 新增：TTS模型选择（仅 AI 可见，LocalWavFile 时隐藏） -->
        <div class="col-xs-12 ai-only voice-config" id="ttsModelsDiv" style="display:none;">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{inboundllm.form.ttsModels}">TTS模型</label>
                <div class="col-sm-8">
                    <select name="ttsModels" id="ttsModels" th:field="*{ttsModels}" class="form-control" required>
                        <option value="" th:text="#{inboundllm.form.ttsModels.empty}">请选择TTS模型</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 6. 音色编码（仅 AI 可见，LocalWavFile 时隐藏） -->
        <div class="col-xs-12 ai-only voice-config">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{inboundllm.form.voiceCode}"></label>
                <div class="col-sm-8">
                    <select name="voiceCode" id="voiceCode" th:field="*{voiceCode}" class="form-control" required>
                        <option value="" th:text="#{inboundllm.form.voiceCode.empty}"></option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 7. AI 转接类型（仅 AI 可见） -->
        <div class="col-xs-12 ai-only" id="aiTransferTypeDiv">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{inboundllm.form.aiTransferType}"></label>
                <div class="col-sm-8">
                    <select name="aiTransferType" th:field="*{aiTransferType}" id="aiTransferTypeSelect" class="form-control" required>
                        <option value="acd"      th:text="#{inboundllm.form.aiTransferTypeACD}"></option>
                        <option value="extension" th:text="#{inboundllm.form.aiTransferTypeExtension}"></option>
                        <option value="gateway"  th:text="#{inboundllm.form.aiTransferTypeGateway}"></option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 8. IVR 下拉（仅 IVR 可见） -->
        <div class="col-xs-12 ivr-only">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{inboundllm.form.ivrId}"></label>
                <div class="col-sm-8">
                    <select name="ivrId" th:field="*{ivrId}" class="form-control" required>
                        <option value="" th:text="#{inboundllm.form.ivrId.empty}"></option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 9. 业务组（ACD / AI+ACD 可见） -->
        <div class="col-xs-12 transfer-field acd-only acd-transfer">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{inboundllm.form.aiTransferGroupId}"></label>
                <div class="col-sm-8">
                    <select name="aiTransferGroupId" th:field="*{aiTransferGroupId}" class="form-control" required>
                        <option value="" th:text="#{inboundllm.form.aiTransferGroupId.empty}"></option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 10. 网关（AI+Gateway 可见） -->
        <div class="col-xs-12 transfer-field gateway-transfer">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{inboundllm.form.aiTransferGatewayId}"></label>
                <div class="col-sm-8">
                    <select name="aiTransferGatewayId" th:field="*{aiTransferGatewayId}" class="form-control" required>
                        <option value="" th:text="#{inboundllm.form.aiTransferGatewayId.empty}"></option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 11. 网关目标号码（AI+Gateway 可见） -->
        <div class="col-xs-12 transfer-field gateway-transfer">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{inboundllm.form.aiTransferGatewayDestNumber}"></label>
                <div class="col-sm-8">
                    <input name="aiTransferGatewayDestNumber" th:field="*{aiTransferGatewayDestNumber}" class="form-control" type="text" required>
                </div>
            </div>
        </div>

        <!-- 12. 分机号（AI+Extension 可见） -->
        <div class="col-xs-12 transfer-field extension-transfer">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{inboundllm.form.aiTransferExtNumber}"></label>
                <div class="col-sm-8">
                    <input name="aiTransferExtNumber" th:field="*{aiTransferExtNumber}" class="form-control" type="text" required>
                </div>
            </div>
        </div>


        <!-- 13. 服务评价 下拉 -->
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label " th:text="#{inboundllm.form.satisfSurveyIvrId}"></label>
                <div class="col-sm-8">
                    <select name="satisfSurveyIvrId" th:field="*{satisfSurveyIvrId}" class="form-control" >
                        <option value="" th:text="#{inboundllm.form.satisfSurveyIvrId.empty}"></option>
                    </select>
                </div>
            </div>
        </div>

    </form>
</div>
<th:block th:include="include :: footer"/>
<script th:inline="javascript">
    var prefix = ctx + "aicall/inboundllm";
    // 存储llmAccount数据，用于判断providerClassName
    var llmAccountMap = {};

    $(function(){

        /* ---------- 通用下拉数据加载 ---------- */

        // 大模型底座
        $.ajax({
            url: ctx + "aicall/account/all",
            success: function(rsp) {
                var llmAccountSelect = $('select[name="llmAccountId"]');
                llmAccountSelect.empty();
                llmAccountSelect.append('<option value="">' + i18n('inboundllm.form.llmAccountId.empty') + '</option>');
                rsp.data.forEach(function(llmAccount) {
                    llmAccountSelect.append($("<option>")
                        .attr("value", llmAccount.id)
                        .attr("data-provider", llmAccount.providerClassName)
                        .text(llmAccount.name));
                    llmAccountMap[llmAccount.id] = llmAccount;
                });
                var llmAccountId = /*[[${ccInboundLlmAccount.llmAccountId}]]*/ '';
                if (llmAccountId) {
                    llmAccountSelect.val(llmAccountId);
                    checkAndToggleVoiceFields(llmAccountId);
                }
            }
        });

        // ASR 提供商
        $.ajax({
            url: ctx + "aicall/ttsAliyun/asr/provider/all",
            success: function(rsp) {
                var providerSelect = $('#asrProvider');
                providerSelect.empty();
                providerSelect.append('<option value="">' + i18n('inboundllm.form.asrProvider.empty') + '</option>');
                Object.entries(rsp.data).forEach(function([key, value]) {
                    providerSelect.append($("<option>").attr("value", key).text(value));
                });
                var savedProvider = /*[[${ccInboundLlmAccount.asrProvider}]]*/ '';
                if (savedProvider) {
                    providerSelect.val(savedProvider);
                    loadAsrLanguages(savedProvider, function() {
                        var savedAsrLanguageCode = /*[[${ccInboundLlmAccount.asrLanguageCode}]]*/ '';
                        if (savedAsrLanguageCode) {
                            $('#asrLanguageCode').val(savedAsrLanguageCode);
                            loadAsrModels(savedProvider, savedAsrLanguageCode, function() {
                                var savedAsrModels = /*[[${ccInboundLlmAccount.asrModels}]]*/ '';
                                if (savedAsrModels) {
                                    $('#asrModels').val(savedAsrModels);
                                }
                            });
                        }
                    });
                }
            }
        });

        // 音色来源
        $.ajax({
            url: ctx + "aicall/ttsAliyun/tts/voiceSource/all",
            success: function(rsp) {
                var voiceSourceSelect = $('#voiceSource');
                voiceSourceSelect.empty();
                voiceSourceSelect.append('<option value="">' + i18n('inboundllm.form.voiceSource.empty') + '</option>');
                Object.entries(rsp.data).forEach(function([key, value]) {
                    voiceSourceSelect.append($("<option>").attr("value", key).text(value));
                });
                var savedVoiceSource = /*[[${ccInboundLlmAccount.voiceSource}]]*/ '';
                if (savedVoiceSource) {
                    voiceSourceSelect.val(savedVoiceSource);
                    loadTtsLanguages(savedVoiceSource, function() {
                        var savedTtsLanguageCode = /*[[${ccInboundLlmAccount.ttsLanguageCode}]]*/ '';
                        if (savedTtsLanguageCode) {
                            $('#ttsLanguageCode').val(savedTtsLanguageCode);
                            loadTtsModels(savedVoiceSource, savedTtsLanguageCode, function() {
                                var savedTtsModels = /*[[${ccInboundLlmAccount.ttsModels}]]*/ '';
                                if (savedTtsModels) {
                                    $('#ttsModels').val(savedTtsModels);
                                    loadVoicesByVoiceSourceAndLanguage(savedVoiceSource, savedTtsLanguageCode, savedTtsModels);
                                } else {
                                    loadVoicesByVoiceSourceAndLanguage(savedVoiceSource, savedTtsLanguageCode, '');
                                }
                            });
                        }
                    });
                }
            }
        });

        // 业务组
        $.ajax({
            url: ctx + "cc/bizgroup/all",
            success: function(rsp) {
                var groupSelect = $('select[name="aiTransferGroupId"]');
                groupSelect.empty();
                groupSelect.append('<option value="">' + i18n('inboundllm.form.aiTransferGroupId.empty') + '</option>');
                rsp.data.forEach(function(bizGroup) {
                    groupSelect.append($("<option>").attr("value", bizGroup.groupId).text(bizGroup.bizGroupName));
                });
                var groupId = /*[[${ccInboundLlmAccount.aiTransferGroupId}]]*/ '';
                if (groupId) groupSelect.val(groupId);
            }
        });

        // 出局网关
        $.ajax({
            url: ctx + "cc/gateways/outbound",
            success: function(rsp) {
                var gatewaySelect = $('select[name="aiTransferGatewayId"]');
                gatewaySelect.empty();
                gatewaySelect.append('<option value="">' + i18n('inboundllm.form.aiTransferGatewayId.empty') + '</option>');
                rsp.data.forEach(function(gateway) {
                    gatewaySelect.append($("<option>").attr("value", gateway.id).text(gateway.gwDesc));
                });
                var aiTransferGatewayId = /*[[${ccInboundLlmAccount.aiTransferGatewayId}]]*/ '';
                if (aiTransferGatewayId) gatewaySelect.val(aiTransferGatewayId);
            }
        });

        // IVR 下拉
        $.ajax({
            url: ctx + "cc/ivr/all",
            success: function(rsp) {
                var ivrIdSelect = $('select[name="ivrId"]');
                ivrIdSelect.empty();
                ivrIdSelect.append('<option value="">' + i18n('inboundllm.form.ivrId.empty') + '</option>');
                rsp.data.forEach(function(ccIvr) {
                    ivrIdSelect.append($("<option>").attr("value", ccIvr.id).text(ccIvr.ivrNodeName));
                });
                var ivrId = /*[[${ccInboundLlmAccount.ivrId}]]*/ '';
                if (ivrId) ivrIdSelect.val(ivrId);
            }
        });

        // satisfSurveyIvrId 下拉
        $.ajax({
            url: ctx + "cc/ivr/all",
            success: function(rsp) {
                var satisfSurveyIvrIdSelect = $('select[name="satisfSurveyIvrId"]');
                satisfSurveyIvrIdSelect.empty();
                satisfSurveyIvrIdSelect.append('<option value="">' + i18n('inboundllm.form.satisfSurveyIvrId.empty') + '</option>');
                rsp.data.forEach(function(ccIvr) {
                    satisfSurveyIvrIdSelect.append($("<option>").attr("value", ccIvr.id).text(ccIvr.ivrNodeName));
                });
                var satisfSurveyIvrId = /*[[${ccInboundLlmAccount.satisfSurveyIvrId}]]*/ '';
                if (satisfSurveyIvrId) satisfSurveyIvrIdSelect.val(satisfSurveyIvrId);
            }
        });

        /* ---------- 事件绑定 ---------- */
        $(document).on('change', '#voiceSource', function() {
            var voiceSource = $(this).val();
            // 清空并隐藏模型下拉框
            $('#ttsModels').empty().append('<option value="">' + i18n('inboundllm.form.ttsModels.empty') + '</option>');
            $('#ttsModelsDiv').hide();

            loadTtsLanguages(voiceSource, function() {
                var ttsLanguageCode = $('#ttsLanguageCode').val();
                if (ttsLanguageCode) {
                    loadTtsModels(voiceSource, ttsLanguageCode, function() {
                        var ttsModels = $('#ttsModels').val();
                        loadVoicesByVoiceSourceAndLanguage(voiceSource, ttsLanguageCode, ttsModels);
                    });
                } else {
                    $('#voiceCode').empty().append('<option value="">' + i18n('inboundllm.form.voiceCode.empty') + '</option>');
                }
            });
        });

        $(document).on('change', '#ttsLanguageCode', function() {
            var voiceSource = $('#voiceSource').val();
            var ttsLanguageCode = $(this).val();
            loadTtsModels(voiceSource, ttsLanguageCode, function() {
                var ttsModels = $('#ttsModels').val();
                loadVoicesByVoiceSourceAndLanguage(voiceSource, ttsLanguageCode, ttsModels);
            });
        });

        $(document).on('change', '#ttsModels', function() {
            var voiceSource = $('#voiceSource').val();
            var ttsLanguageCode = $('#ttsLanguageCode').val();
            var ttsModels = $(this).val();
            if (!ttsModels) {
                $('#voiceCode').empty().append('<option value="">' + i18n('inboundllm.form.voiceCode.empty') + '</option>');
            } else {
                loadVoicesByVoiceSourceAndLanguage(voiceSource, ttsLanguageCode, ttsModels);
            }
        });

        $(document).on('change', '#asrProvider', function() {
            var asrProvider = $(this).val();
            // 清空并隐藏模型下拉框
            $('#asrModels').empty().append('<option value="">' + i18n('inboundllm.form.asrModels.empty') + '</option>');
            $('#asrModelsDiv').hide();

            loadAsrLanguages(asrProvider, function() {
                var asrLanguageCode = $('#asrLanguageCode').val();
                if (asrLanguageCode) {
                    loadAsrModels(asrProvider, asrLanguageCode);
                }
            });
        });

        $(document).on('change', '#asrLanguageCode', function() {
            var asrProvider = $('#asrProvider').val();
            var asrLanguageCode = $(this).val();
            loadAsrModels(asrProvider, asrLanguageCode);
        });

        $(document).on('change', '#serviceTypeSelect', function() {
            toggleFields();
            // 清空satisfSurveyIvrId
            $('select[name="satisfSurveyIvrId"]').val("");
        });
        $(document).on('change', '#aiTransferTypeSelect', function() {
            toggleFields();
        });

        // 监听大模型底座变更
        $(document).on('change', '#llmAccountId', function() {
            checkAndToggleVoiceFields($(this).val());
        });

        /* ---------- 校验 ---------- */
        $('input[name="callee"]').rules('add', {
            remote: {
                url: prefix + '/checkCallee',
                type: 'get',
                data: {
                    id: function () { return $('input[name="id"]').val(); },
                    callee: function () { return $('input[name="callee"]').val(); }
                },
                dataFilter: function (resp) {
                    return JSON.parse(resp).data ? 'true' : '"该号码不可用"';
                }
            },
            messages: { remote: '该号码不可用' }
        });

        /* ---------- 初始化 ---------- */
        toggleFields();
    });

    $("#form-inboundllm-add").validate({ focusCleanup: true });

    function submitHandler() {
        if ($.validate.form()) {
            $.operate.save(prefix + "/add", $('#form-inboundllm-add').serialize());
        }
    }

    /* ========== 工具函数 ========== */

    // 根据TTS厂商加载语言列表
    function loadTtsLanguages(voiceSource, callback) {
        var languageSelect = $('#ttsLanguageCode');
        var languageDiv = $('#ttsLanguageCodeDiv');
        var modelsSelect = $('#ttsModels');
        var modelsDiv = $('#ttsModelsDiv');

        if (!voiceSource) {
            languageSelect.empty().append('<option value="">' + i18n('inboundllm.form.ttsLanguageCode.empty') + '</option>');
            languageDiv.hide();
            // 清空并隐藏模型下拉框
            modelsSelect.empty().append('<option value="">' + i18n('inboundllm.form.ttsModels.empty') + '</option>');
            modelsDiv.hide();
            if (callback) callback();
            return;
        }

        $.ajax({
            url: ctx + "aicall/ttsAliyun/tts/language",
            data: { voiceSource: voiceSource },
            success: function(rsp) {
                languageSelect.empty();

                if (rsp.data && rsp.data.length > 0) {
                    // 如果只有一个选项，直接选中且不显示下拉框，但仍需调用models接口
                    if (rsp.data.length === 1) {
                        var item = rsp.data[0];
                        var langCode = item.code || item.key || item.value;
                        languageSelect.append($("<option>").attr("value", langCode).text(item.name || item.label || item.text || item.value));
                        languageSelect.val(langCode);
                        languageDiv.hide();
                        // 单条数据默认选中时也要加载models
                        loadTtsModels(voiceSource, langCode, callback);
                    } else {
                        languageSelect.append('<option value="">' + i18n('inboundllm.form.ttsLanguageCode.empty') + '</option>');
                        rsp.data.forEach(function(item) {
                            languageSelect.append($("<option>").attr("value", item.code || item.key || item.value).text(item.name || item.label || item.text || item.value));
                        });
                        languageDiv.show();
                        // 多语言时，先清空并隐藏模型下拉框，等待语言选择后再加载
                        modelsSelect.empty().append('<option value="">' + i18n('inboundllm.form.ttsModels.empty') + '</option>');
                        modelsDiv.hide();
                        if (callback) callback();
                    }
                } else {
                    languageSelect.append('<option value="">' + i18n('inboundllm.form.ttsLanguageCode.empty') + '</option>');
                    languageDiv.show();
                    // 无数据时隐藏模型下拉框
                    modelsSelect.empty().append('<option value="">' + i18n('inboundllm.form.ttsModels.empty') + '</option>');
                    modelsDiv.hide();
                    if (callback) callback();
                }
            }
        });
    }

    // 根据ASR厂商加载语言列表
    function loadAsrLanguages(asrProvider, callback) {
        var languageSelect = $('#asrLanguageCode');
        var languageDiv = $('#asrLanguageCodeDiv');
        var modelsSelect = $('#asrModels');
        var modelsDiv = $('#asrModelsDiv');

        if (!asrProvider) {
            languageSelect.empty().append('<option value="">' + i18n('inboundllm.form.asrLanguageCode.empty') + '</option>');
            languageDiv.hide();
            // 清空并隐藏模型下拉框
            modelsSelect.empty().append('<option value="">' + i18n('inboundllm.form.asrModels.empty') + '</option>');
            modelsDiv.hide();
            if (callback) callback();
            return;
        }

        $.ajax({
            url: ctx + "aicall/ttsAliyun/asr/language",
            data: { asrProvider: asrProvider },
            success: function(rsp) {
                languageSelect.empty();

                if (rsp.data && rsp.data.length > 0) {
                    // 如果只有一个选项，直接选中且不显示下拉框，但仍需调用models接口
                    if (rsp.data.length === 1) {
                        var item = rsp.data[0];
                        var langCode = item.code || item.key || item.value;
                        languageSelect.append($("<option>").attr("value", langCode).text(item.name || item.label || item.text || item.value));
                        languageSelect.val(langCode);
                        languageDiv.hide();
                        // 单条数据默认选中时也要加载models
                        loadAsrModels(asrProvider, langCode, callback);
                    } else {
                        languageSelect.append('<option value="">' + i18n('inboundllm.form.asrLanguageCode.empty') + '</option>');
                        rsp.data.forEach(function(item) {
                            languageSelect.append($("<option>").attr("value", item.code || item.key || item.value).text(item.name || item.label || item.text || item.value));
                        });
                        languageDiv.show();
                        // 多语言时，先清空并隐藏模型下拉框，等待语言选择后再加载
                        modelsSelect.empty().append('<option value="">' + i18n('inboundllm.form.asrModels.empty') + '</option>');
                        modelsDiv.hide();
                        if (callback) callback();
                    }
                } else {
                    languageSelect.append('<option value="">' + i18n('inboundllm.form.asrLanguageCode.empty') + '</option>');
                    languageDiv.show();
                    // 无数据时隐藏模型下拉框
                    modelsSelect.empty().append('<option value="">' + i18n('inboundllm.form.asrModels.empty') + '</option>');
                    modelsDiv.hide();
                    if (callback) callback();
                }
            }
        });
    }

    // 根据TTS厂商和语言加载模型列表
    function loadTtsModels(voiceSource, ttsLanguageCode, callback) {
        var modelsSelect = $('#ttsModels');
        var modelsDiv = $('#ttsModelsDiv');

        if (!voiceSource || !ttsLanguageCode) {
            modelsSelect.empty().append('<option value="">' + i18n('inboundllm.form.ttsModels.empty') + '</option>');
            modelsDiv.hide();
            if (callback) callback();
            return;
        }

        $.ajax({
            url: ctx + "aicall/ttsAliyun/tts/models",
            data: {
                voiceSource: voiceSource,
                ttsLanguageCode: ttsLanguageCode
            },
            success: function(rsp) {
                modelsSelect.empty();

                if (rsp.data && rsp.data.length > 0) {
                    // 如果只有一个选项，直接选中且不显示下拉框
                    if (rsp.data.length === 1) {
                        var item = rsp.data[0];
                        var modelValue = item.code || item.key || item.value;
                        modelsSelect.append($("<option>").attr("value", modelValue).text(item.name || item.label || item.text || item.value));
                        modelsSelect.val(modelValue);
                        modelsDiv.hide(); // 单值时隐藏
                    } else {
                        modelsSelect.append('<option value="">' + i18n('inboundllm.form.ttsModels.empty') + '</option>');
                        rsp.data.forEach(function(item) {
                            modelsSelect.append($("<option>").attr("value", item.code || item.key || item.value).text(item.name || item.label || item.text || item.value));
                        });
                        modelsDiv.show(); // 多值时显示
                    }
                } else {
                    modelsSelect.append('<option value="">' + i18n('inboundllm.form.ttsModels.empty') + '</option>');
                    modelsDiv.hide(); // 无数据时隐藏
                }

                if (callback) callback();
            }
        });
    }

    // 根据ASR厂商和语言加载模型列表
    function loadAsrModels(asrProvider, asrLanguageCode, callback) {
        var modelsSelect = $('#asrModels');
        var modelsDiv = $('#asrModelsDiv');

        if (!asrProvider || !asrLanguageCode) {
            modelsSelect.empty().append('<option value="">' + i18n('inboundllm.form.asrModels.empty') + '</option>');
            modelsDiv.hide();
            if (callback) callback();
            return;
        }

        $.ajax({
            url: ctx + "aicall/ttsAliyun/asr/models",
            data: {
                asrProvider: asrProvider,
                asrLanguageCode: asrLanguageCode
            },
            success: function(rsp) {
                modelsSelect.empty();

                if (rsp.data && rsp.data.length > 0) {
                    // 如果只有一个选项，直接选中且不显示下拉框
                    if (rsp.data.length === 1) {
                        var item = rsp.data[0];
                        var modelValue = item.code || item.key || item.value;
                        modelsSelect.append($("<option>").attr("value", modelValue).text(item.name || item.label || item.text || item.value));
                        modelsSelect.val(modelValue);
                        modelsDiv.hide(); // 单值时隐藏
                    } else {
                        modelsSelect.append('<option value="">' + i18n('inboundllm.form.asrModels.empty') + '</option>');
                        rsp.data.forEach(function(item) {
                            modelsSelect.append($("<option>").attr("value", item.code || item.key || item.value).text(item.name || item.label || item.text || item.value));
                        });
                        modelsDiv.show(); // 多值时显示
                    }
                } else {
                    modelsSelect.append('<option value="">' + i18n('inboundllm.form.asrModels.empty') + '</option>');
                    modelsDiv.hide(); // 无数据时隐藏
                }

                if (callback) callback();
            }
        });
    }

    // 根据TTS厂商、语言和模型加载音色
    function loadVoicesByVoiceSourceAndLanguage(voiceSource, ttsLanguageCode, ttsModels) {
        var voiceSelect = $('#voiceCode');
        if (!voiceSource || !ttsLanguageCode) {
            voiceSelect.empty().append('<option value="">' + i18n('inboundllm.form.voiceCode.empty') + '</option>');
            return;
        }
        $.ajax({
            url: ctx + "aicall/ttsAliyun/getByLanguageCode",
            data: {
                voiceSource: voiceSource,
                ttsLanguageCode: ttsLanguageCode,
                ttsModels: ttsModels
            },
            success: function(rsp) {
                voiceSelect.empty().append('<option value="">' + i18n('inboundllm.form.voiceCode.empty') + '</option>');
                rsp.data.forEach(function(voice) {
                    voiceSelect.append($("<option>")
                        .attr("value", voice.voiceCode)
                        .attr("data-source", voice.voiceSource)
                        .text(voice.voiceName));
                });
                var voiceCode = /*[[${ccInboundLlmAccount.voiceCode}]]*/ '';
                if (voiceCode) voiceSelect.val(voiceCode);
            }
        });
    }

    function toggleFields() {
        var serviceType = $('#serviceTypeSelect').val();
        var aiTransferType = $('#aiTransferTypeSelect').val();

        // 先全部隐藏
        $('.ai-only,.acd-only,.ivr-only,.transfer-field').hide();

        if (serviceType === 'ai') {
            $('.ai-only').show();
            // 根据当前值重新判断语言下拉框是否显示
            var ttsLanguageCount = $('#ttsLanguageCode option').length;
            var asrLanguageCount = $('#asrLanguageCode option').length;
            var ttsModelsCount = $('#ttsModels option').length;
            var asrModelsCount = $('#asrModels option').length;
            if (ttsLanguageCount <= 1) $('#ttsLanguageCodeDiv').hide();
            if (asrLanguageCount <= 1) $('#asrLanguageCodeDiv').hide();
            if (ttsModelsCount <= 1) $('#ttsModelsDiv').hide();
            if (asrModelsCount <= 1) $('#asrModelsDiv').hide();

            // 检查是否需要隐藏TTS相关字段
            var llmAccountId = $('#llmAccountId').val();
            if (llmAccountId) {
                checkAndToggleVoiceFields(llmAccountId);
            }

            if (aiTransferType === 'acd')      $('.acd-transfer').show();
            if (aiTransferType === 'gateway')  $('.gateway-transfer').show();
            if (aiTransferType === 'extension')$('.extension-transfer').show();
        } else if (serviceType === 'acd') {
            $('.acd-only').show();
        } else if (serviceType === 'ivr') {
            $('.ivr-only').show();
        }
    }

    function checkAndToggleVoiceFields(llmAccountId) {
        var llmAccount = llmAccountMap[llmAccountId];
        if (llmAccount && llmAccount.providerClassName === 'LocalWavFile') {
            // LocalWavFile时隐藏TTS相关字段（voiceSource、ttsLanguageCode、ttsModels、voiceCode），保留ASR
            $('.voice-config').hide();
            $('.voice-config select').prop('required', false);
            // 清空TTS相关值
            $('#voiceSource').val('');
            $('#ttsLanguageCode').val('');
            $('#ttsModels').val('');
            $('#voiceCode').val('');
        } else {
            // 非LocalWavFile时显示TTS相关字段
            var serviceType = $('#serviceTypeSelect').val();
            if (serviceType === 'ai') {
                $('.voice-config').show();
                $('.voice-config select').prop('required', true);
                // 根据当前值重新判断语言下拉框是否显示
                var ttsLanguageCount = $('#ttsLanguageCode option').length;
                var ttsModelsCount = $('#ttsModels option').length;
                if (ttsLanguageCount <= 1) {
                    $('#ttsLanguageCodeDiv').hide();
                }
                if (ttsModelsCount <= 1) {
                    $('#ttsModelsDiv').hide();
                }
            }
        }
    }
</script>
</body>
</html>