<!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-callTask-edit" th:object="${ccCallTask}">
        <input name="batchId" th:field="*{batchId}" type="hidden">
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.form.batchName}"></label>
                <div class="col-sm-8">
                    <input name="batchName" th:field="*{batchName}" class="form-control" type="text" required>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.form.threadNum}"></label>
                <div class="col-sm-8">
                    <input name="threadNum" th:field="*{threadNum}" class="form-control" type="text" required>
                </div>
            </div>
        </div>

        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.form.taskType}"></label>
                <div class="col-sm-6">
                    <select name="taskType" id="taskType"  th:field="*{taskType}" class="form-control" required>
                        <option value="1" th:text="#{callTask.form.taskType1}"></option>
                        <option value="0" th:text="#{callTask.form.taskType0}"></option>
                        <option value="2" th:text="#{callTask.form.taskType2}"></option>
                        <option value="3" th:text="#{callTask.form.taskType3}"></option>
                    </select>
                </div>
                <div class="col-sm-2">
                    <!-- 添加下载模板的链接 -->
                    <a href="javascript:void(0);" onclick="downloadTemplate()">
                        <span th:text="#{callTask.form.downloadTemplate}">下载模板</span>
                    </a>
                </div>
            </div>
        </div>

        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.form.autoStop}"></label>
                <div class="col-sm-8">
                    <select name="autoStop" th:field="*{autoStop}" class="form-control" required>
                        <option value="1" th:text="#{callTask.form.autoStop1}"></option>
                        <option value="0" th:text="#{callTask.form.autoStop0}"></option>
                    </select>
                </div>
            </div>
        </div>

        <div class="col-xs-12">
            <div class="form-group" style="display:none;">
                <label class="col-sm-3 control-label is-required"  th:text="#{callTask.form.conntectRate}"></label>
                <div class="col-sm-8">
                    <input name="conntectRate" th:field="*{conntectRate}" class="form-control" type="number" min="0" max="100" step="1" required>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group" style="display:none;">
                <label class="col-sm-3 control-label is-required"  th:text="#{callTask.form.avgRingTimeLen}"></label>
                <div class="col-sm-8">
                    <input name="avgRingTimeLen" th:field="*{avgRingTimeLen}" class="form-control" type="text" required>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group" style="display:none;">
                <label class="col-sm-3 control-label is-required"  th:text="#{callTask.form.avgCallTalkTimeLen}"></label>
                <div class="col-sm-8">
                    <input name="avgCallTalkTimeLen" th:field="*{avgCallTalkTimeLen}" class="form-control" type="text" required>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group" style="display:none;">
                <label class="col-sm-3 control-label is-required"  th:text="#{callTask.form.avgCallEndProcessTimeLen}"></label>
                <div class="col-sm-8">
                    <input name="avgCallEndProcessTimeLen" th:field="*{avgCallEndProcessTimeLen}" class="form-control" type="text" required>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group" style="display:none;">
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.form.gatewayId}"></label>
                <div class="col-sm-8">
                    <select name="gatewayId" th:field="*{gatewayId}" class="form-control" required>
                        <option value="" th:text="#{callTask.form.gatewayId.empty}"></option>
                        <!-- 网关选项将通过接口动态加载 -->
                    </select>
                </div>
            </div>
        </div>

        <div class="col-xs-12">
            <div class="form-group" style="display:none;">
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.form.llmAccountId}"></label>
                <div class="col-sm-8">
                    <select name="llmAccountId" id="llmAccountId" th:field="*{llmAccountId}" class="form-control" required>
                        <option value="" th:text="#{callTask.form.llmAccountId.empty}"></option>
                        <!-- 大模型底座选项将通过接口动态加载 -->
                    </select>
                </div>
            </div>
        </div>

        <div class="col-xs-12 voice-config">
            <div class="form-group" style="display:none;">
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.form.voiceSource}"></label>
                <div class="col-sm-8">
                    <select name="voiceSource" id="voiceSource" th:field="*{voiceSource}" class="form-control" required>
                        <option value="" th:text="#{callTask.form.voiceSource.empty}"></option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 新增：TTS语言选择 -->
        <div class="col-xs-12 voice-config" id="ttsLanguageCodeDiv" style="display:none;">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.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="#{callTask.form.ttsLanguageCode.empty}">请选择TTS语言</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 新增：TTS模型选择 -->
        <div class="col-xs-12 voice-config" id="ttsModelsDiv" style="display:none;">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.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="#{callTask.form.ttsModels.empty}">请选择TTS模型</option>
                    </select>
                </div>
            </div>
        </div>

        <div class="col-xs-12 voice-config">
            <div class="form-group" style="display:none;">
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.form.voiceCode}"></label>
                <div class="col-sm-8">
                    <select name="voiceCode" id="voiceCode" th:field="*{voiceCode}" class="form-control" required>
                        <option value="" th:text="#{callTask.form.voiceCode.empty}"></option>
                        <!-- 音色选项将通过接口动态加载 -->
                    </select>
                </div>
            </div>
        </div>

        <div class="col-xs-12">
            <div class="form-group" style="display:none;">
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.form.asrProvider}"></label>
                <div class="col-sm-8">
                    <select name="asrProvider" id="asrProvider" th:field="*{asrProvider}" class="form-control" required>
                        <option value="" th:text="#{callTask.form.asrProvider.empty}"></option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 新增：ASR语言选择 -->
        <div class="col-xs-12" id="asrLanguageCodeDiv" style="display:none;">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.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="#{callTask.form.asrLanguageCode.empty}">请选择ASR语言</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 新增：ASR模型选择 -->
        <div class="col-xs-12" id="asrModelsDiv" style="display:none;">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.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="#{callTask.form.asrModels.empty}">请选择ASR模型</option>
                    </select>
                </div>
            </div>
        </div>

        <div class="col-xs-12">
            <div class="form-group" style="display:none;">
                <label class="col-sm-3 control-label is-required"  th:text="#{callTask.form.playTimes}"></label>
                <div class="col-sm-8">
                    <input name="playTimes" th:field="*{playTimes}" class="form-control" type="text" required>
                </div>
            </div>
        </div>

        <div class="col-xs-12" id="aiTransferTypeDiv" >
            <div class="form-group" style="display:none;">
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.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="#{callTask.form.aiTransferTypeACD}"></option>
                        <option value="extension" th:text="#{callTask.form.aiTransferTypeExtension}"></option>
                        <option value="gateway" th:text="#{callTask.form.aiTransferTypeGateway}"></option>
                    </select>
                </div>
            </div>
        </div>
        <div class="col-xs-12 transfer-field acd-transfer" style="display: none;">
            <div class="form-group" >
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.form.aiTransferGroupId}"></label>
                <div class="col-sm-8">
                    <select name="aiTransferGroupId" th:field="*{aiTransferGroupId}" class="form-control" required>
                        <option value="" th:text="#{callTask.form.aiTransferGroupId.empty}"></option>
                        <!-- 业务组选项将通过接口动态加载 -->
                    </select>
                </div>
            </div>
        </div>
        <div class="col-xs-12 transfer-field gateway-transfer" style="display: none;">
            <div class="form-group" >
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.form.aiTransferGatewayId}"></label>
                <div class="col-sm-8">
                    <select name="aiTransferGatewayId" th:field="*{aiTransferGatewayId}" class="form-control" required>
                        <option value="" th:text="#{callTask.form.aiTransferGatewayId.empty}"></option>
                        <!-- 业务组选项将通过接口动态加载 -->
                    </select>
                </div>
            </div>
        </div>
        <div class="col-xs-12 transfer-field gateway-transfer" style="display: none;">
            <div class="form-group" >
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.form.aiTransferGatewayDestNumber}"></label>
                <div class="col-sm-8">
                    <input name="aiTransferGatewayDestNumber" th:field="*{aiTransferGatewayDestNumber}" class="form-control" type="text" required>
                </div>
            </div>
        </div>
        <div class="col-xs-12 transfer-field extension-transfer" style="display: none;">
            <div class="form-group" >
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.form.aiTransferExtNumber}"></label>
                <div class="col-sm-8">
                    <input name="aiTransferExtNumber" th:field="*{aiTransferExtNumber}" class="form-control" type="text" required>
                </div>
            </div>
        </div>


        <div class="col-xs-12">
            <div class="form-group" style="display:none;">
                <label class="col-sm-3 control-label is-required" th:text="#{callTask.form.ivrId}"></label>
                <div class="col-sm-8">
                    <select name="ivrId" th:field="*{ivrId}" class="form-control" required>
                        <option value="" th:text="#{callTask.form.ivrId.empty}"></option>
                        <!-- IVR选项将通过接口动态加载 -->
                    </select>
                </div>
            </div>
        </div>

    </form>
</div>
<th:block th:include="include :: footer" />
<script th:inline="javascript">

    var prefix = ctx + "aicall/callTask";
    // 存储llmAccount数据，用于判断providerClassName
    var llmAccountMap = {};

    $(function() {
        // 加载网关下拉框数据
        $.ajax({
            url: ctx + "cc/gateways/outbound",
            success: function(rsp) {
                var gatewaySelect = $('select[name="gatewayId"]');
                gatewaySelect.empty();
                gatewaySelect.append('<option value="">' + i18n('callTask.form.gatewayId.empty') + '</option>');
                rsp.data.forEach(function(gateway) {
                    gatewaySelect.append($("<option>").attr("value", gateway.id).text(gateway.gwDesc));
                });
                // 设置网关下拉框的选中项
                var gatewayId = /*[[${ccCallTask.gatewayId}]]*/ '';
                if (gatewayId) {
                    gatewaySelect.val(gatewayId);
                }
                var gatewaySelect = $('select[name="aiTransferGatewayId"]');
                gatewaySelect.empty();
                gatewaySelect.append('<option value="">' + i18n('callTask.form.aiTransferGatewayId.empty') + '</option>');
                rsp.data.forEach(function(gateway) {
                    gatewaySelect.append($("<option>").attr("value", gateway.id).text(gateway.gwDesc));
                });
                // 回显已保存的aiTransferGatewayId
                var aiTransferGatewayId = /*[[${ccCallTask.aiTransferGatewayId}]]*/ '';
                if (aiTransferGatewayId) {
                    gatewaySelect.val(aiTransferGatewayId);
                }
            }
        });

        // 加载TTS提供商下拉框数据
        $.ajax({
            url: ctx + "aicall/ttsAliyun/tts/voiceSource/all",
            success: function(rsp) {
                var voiceSourceSelect = $('#voiceSource');
                voiceSourceSelect.empty();
                voiceSourceSelect.append('<option value="">' + i18n('callTask.form.voiceSource.empty') + '</option>');
                // 遍历 map 对象，key 作为 value，value 作为显示文本
                Object.entries(rsp.data).forEach(function([key, value]) {
                    voiceSourceSelect.append($("<option>").attr("value", key).text(value));
                });
                // 回显已保存的voiceSource并加载对应语言和音色
                var savedVoiceSource = /*[[${ccCallTask.voiceSource}]]*/ '';
                if (savedVoiceSource) {
                    voiceSourceSelect.val(savedVoiceSource);
                    loadTtsLanguages(savedVoiceSource, function() {
                        var savedTtsLanguageCode = /*[[${ccCallTask.ttsLanguageCode}]]*/ '';
                        if (savedTtsLanguageCode) {
                            $('#ttsLanguageCode').val(savedTtsLanguageCode);
                            loadTtsModels(savedVoiceSource, savedTtsLanguageCode, function() {
                                var savedTtsModels = /*[[${ccCallTask.ttsModels}]]*/ '';
                                if (savedTtsModels) {
                                    $('#ttsModels').val(savedTtsModels);
                                }
                                loadVoicesByVoiceSourceAndLanguage(savedVoiceSource, savedTtsLanguageCode, savedTtsModels);
                            });
                        }
                    });
                }
            }
        });


        // 加载ASR提供商下拉框数据
        $.ajax({
            url: ctx + "aicall/ttsAliyun/asr/provider/all",
            success: function(rsp) {
                var providerSelect = $('#asrProvider');
                providerSelect.empty();
                providerSelect.append('<option value="">' + i18n('callTask.form.asrProvider.empty') + '</option>');
                // 遍历 map 对象，key 作为 value，value 作为显示文本
                Object.entries(rsp.data).forEach(function([key, value]) {
                    providerSelect.append($("<option>").attr("value", key).text(value));
                });
                // 回显已保存的asrprovider并加载对应语言
                var savedProvider = /*[[${ccCallTask.asrProvider}]]*/ '';
                if (savedProvider) {
                    providerSelect.val(savedProvider);
                    loadAsrLanguages(savedProvider, function() {
                        var savedAsrLanguageCode = /*[[${ccCallTask.asrLanguageCode}]]*/ '';
                        if (savedAsrLanguageCode) {
                            $('#asrLanguageCode').val(savedAsrLanguageCode);
                            loadAsrModels(savedProvider, savedAsrLanguageCode, function() {
                                var savedAsrModels = /*[[${ccCallTask.asrModels}]]*/ '';
                                if (savedAsrModels) {
                                    $('#asrModels').val(savedAsrModels);
                                }
                            });
                        }
                    });
                }
            }
        });


        // 根据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('callTask.form.ttsLanguageCode.empty') + '</option>');
                languageDiv.hide();
                // 清空并隐藏模型下拉框
                modelsSelect.empty().append('<option value="">' + i18n('callTask.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('callTask.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('callTask.form.ttsModels.empty') + '</option>');
                            modelsDiv.hide();
                            if (callback) callback();
                        }
                    } else {
                        languageSelect.append('<option value="">' + i18n('callTask.form.ttsLanguageCode.empty') + '</option>');
                        languageDiv.show();
                        // 无数据时隐藏模型下拉框
                        modelsSelect.empty().append('<option value="">' + i18n('callTask.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('callTask.form.asrLanguageCode.empty') + '</option>');
                languageDiv.hide();
                // 清空并隐藏模型下拉框
                modelsSelect.empty().append('<option value="">' + i18n('callTask.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('callTask.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('callTask.form.asrModels.empty') + '</option>');
                            modelsDiv.hide();
                            if (callback) callback();
                        }
                    } else {
                        languageSelect.append('<option value="">' + i18n('callTask.form.asrLanguageCode.empty') + '</option>');
                        languageDiv.show();
                        // 无数据时隐藏模型下拉框
                        modelsSelect.empty().append('<option value="">' + i18n('callTask.form.asrModels.empty') + '</option>');
                        modelsDiv.hide();
                        if (callback) callback();
                    }
                }
            });
        }

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

            if (!voiceSource || !ttsLanguageCode) {
                modelsSelect.empty().append('<option value="">' + i18n('callTask.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('callTask.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('callTask.form.ttsModels.empty') + '</option>');
                        modelsDiv.hide(); // 无数据时隐藏
                    }

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

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

            if (!asrProvider || !asrLanguageCode) {
                modelsSelect.empty().append('<option value="">' + i18n('callTask.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('callTask.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('callTask.form.asrModels.empty') + '</option>');
                        modelsDiv.hide(); // 无数据时隐藏
                    }

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

        // 根据TTS厂商、语言和模型加载音色
        function loadVoicesByVoiceSourceAndLanguage(voiceSource, ttsLanguageCode, ttsModels) {
            var voiceSelect = $('select[name="voiceCode"]');
            if (!voiceSource || !ttsLanguageCode) {
                voiceSelect.empty().append('<option value="">' + i18n('callTask.form.voiceCode.empty') + '</option>');
                return;
            }
            var requestData = {
                voiceSource: voiceSource,
                ttsLanguageCode: ttsLanguageCode
            };
            if (ttsModels) {
                requestData.ttsModels = ttsModels;
            }
            $.ajax({
                url: ctx + "aicall/ttsAliyun/getByLanguageCode",
                data: requestData,
                success: function(rsp) {
                    voiceSelect.empty().append('<option value="">' + i18n('callTask.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 = /*[[${ccCallTask.voiceCode}]]*/ '';
                    if (voiceCode) {
                        voiceSelect.val(voiceCode);
                    }
                }
            });
        }

        // TTS厂商变更事件
        $(document).on('change', '#voiceSource', function() {
            var voiceSource = $(this).val();
            // 清空并隐藏模型下拉框
            $('#ttsModels').empty().append('<option value="">' + i18n('callTask.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 {
                    $('select[name="voiceCode"]').empty().append('<option value="">' + i18n('callTask.form.voiceCode.empty') + '</option>');
                }
            });
        });

        // TTS语言变更事件
        $(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);
            });
        });

        // TTS模型变更事件
        $(document).on('change', '#ttsModels', function() {
            var voiceSource = $('#voiceSource').val();
            var ttsLanguageCode = $('#ttsLanguageCode').val();
            var ttsModels = $(this).val();
            if (!ttsModels) {
                $('select[name="voiceCode"]').empty().append('<option value="">' + i18n('callTask.form.voiceCode.empty') + '</option>');
            } else {
                loadVoicesByVoiceSourceAndLanguage(voiceSource, ttsLanguageCode, ttsModels);
            }
        });

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

            loadAsrLanguages(asrProvider, function() {
                // 语言加载完成后，自动加载模型（如果只有一个语言选项）
                var asrLanguageCode = $('#asrLanguageCode').val();
                if (asrLanguageCode) {
                    loadAsrModels(asrProvider, asrLanguageCode);
                }
            });
        });

        // ASR语言变更事件
        $(document).on('change', '#asrLanguageCode', function() {
            var asrProvider = $('#asrProvider').val();
            var asrLanguageCode = $(this).val();
            loadAsrModels(asrProvider, asrLanguageCode);
        });

        // 加载大模型底座下拉框数据
        $.ajax({
            url: ctx + "aicall/account/all",
            success: function(rsp) {
                var llmAccountSelect = $('select[name="llmAccountId"]');
                llmAccountSelect.empty();
                llmAccountSelect.append('<option value="">' + i18n('callTask.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 = /*[[${ccCallTask.llmAccountId}]]*/ '';
                if (llmAccountId) {
                    llmAccountSelect.val(llmAccountId);
                    checkAndToggleVoiceFields(llmAccountId);
                }
            }
        });

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

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

        // 加载业务组下拉框数据
        $.ajax({
            url: ctx + "cc/bizgroup/all",
            success: function(rsp) {
                var groupSelect = $('select[name="aiTransferGroupId"]');
                groupSelect.empty();
                groupSelect.append('<option value="">' + i18n('callTask.form.aiTransferGroupId.empty') + '</option>');
                rsp.data.forEach(function(bizGroup) {
                    groupSelect.append($("<option>").attr("value", bizGroup.groupId).text(bizGroup.bizGroupName));
                });
                // 设置音色下拉框的选中项
                var groupId = /*[[${ccCallTask.aiTransferGroupId}]]*/ '';
                if (groupId) {
                    groupSelect.val(groupId);
                }
            }
        });

        // 监听 taskType 的变化
        $('select[name="taskType"]').change(function() {
            var taskType = $(this).val();
            changeTaskType(taskType);
            toggleTransferFields();
        });

        // 初始化时根据默认值显示字段
        $('select[name="taskType"]').trigger('change');



        // 绑定AI转接类型改变事件
        $(document).on('change', '#aiTransferTypeSelect', function() {
            toggleTransferFields();
        });


        // 初始化转接字段显示状态
        toggleTransferFields();

    });

    $("#form-callTask-edit").validate({
        focusCleanup: true
    });

    function changeTaskType(taskType) {

        console.log("=========taskType:" + taskType);

        // 隐藏所有字段
        $('select[name="groupId"], input[name="conntectRate"], input[name="avgRingTimeLen"], input[name="avgCallTalkTimeLen"], input[name="avgCallEndProcessTimeLen"], input[name="threadNum"], select[name="gatewayId"], select[name="llmAccountId"], select[name="voiceCode"], select[name="voiceSource"], select[name="asrProvider"], input[name="playTimes"], select[name="aiTransferType"], select[name="ivrId"], #ttsLanguageCode, #asrLanguageCode, #ttsModels, #asrModels').parent().parent().hide();

        // 根据 taskType 显示对应的字段
        if (taskType === "0") {
            $('input[name="threadNum"], select[name="gatewayId"], select[name="groupId"], input[name="conntectRate"], input[name="avgRingTimeLen"], input[name="avgCallTalkTimeLen"], input[name="avgCallEndProcessTimeLen"], select[name="aiTransferType"]').parent().parent().show();
        } else if (taskType === "1") {
            $('input[name="threadNum"], select[name="gatewayId"], select[name="llmAccountId"], select[name="voiceCode"], select[name="voiceSource"], #ttsLanguageCode, #ttsModels, select[name="asrProvider"], #asrLanguageCode, #asrModels, select[name="aiTransferType"]').parent().parent().show();
            checkAndToggleVoiceFields($('#llmAccountId').val());
        } else if (taskType === "2") {
            $('input[name="threadNum"], select[name="gatewayId"], input[name="playTimes"], select[name="voiceCode"], select[name="voiceSource"], #ttsLanguageCode, #ttsModels, select[name="asrProvider"], #asrLanguageCode, #asrModels, select[name="aiTransferType"]').parent().parent().show();
        } else if (taskType === "3") {
            $('input[name="threadNum"], select[name="gatewayId"], select[name="ivrId"]').parent().parent().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();
        }
    }

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

    // 下载模板
    function downloadTemplate () {
        var taskType = $("select[name='taskType']").val();
        var templateUrl = prefix + "/downloadTemplate?taskType=" + taskType; // 假设模板文件放在静态资源目录下
        window.location.href = templateUrl;
    };

    function toggleTransferFields() {
        var taskType = $("select[name='taskType']").val();
        var aiTransferType = $('#aiTransferTypeSelect').val();

        // 先隐藏所有转接相关字段
        $('#aiTransferTypeDiv').hide();
        $('.transfer-field').hide();

        // 显示AI转接类型
        if (taskType === "1") {
            $('#aiTransferTypeDiv').show();

            // 根据转接类型显示对应字段
            if (aiTransferType === 'acd') {
                $('.acd-transfer').show();
            } else if (aiTransferType === 'gateway') {
                $('.gateway-transfer').show();
            } else if (aiTransferType === 'extension') {
                $('.extension-transfer').show();
            }
        }
    }

    function checkAndToggleVoiceFields(llmAccountId) {
        var llmAccount = llmAccountMap[llmAccountId];
        if (llmAccount && llmAccount.providerClassName === 'LocalWavFile') {
            // LocalWavFile时隐藏TTS相关字段，保留ASR
            $('.voice-config').hide();
            $('.voice-config select').prop('required', false);
            // 清空TTS相关值
            $('#voiceSource').val('');
            $('#ttsLanguageCode').val('');
            $('#ttsModels').val('');
            $('#voiceCode').val('');
        } else {
            // 非LocalWavFile时显示TTS相关字段
            var taskType = $('#taskType').val();
            if (taskType === "1" || taskType === "2") {
                $('.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>