<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('ViiTorTTS参数配置')" />
    <th:block th:include="include :: layout-latest-css" />
</head>
<body>
<div class="main-content">
    <div class="h4 form-header">ViiTorTTS 参数配置</div>
    <div class="alert alert-info">
        1. 本页面用于配置 `mod_vt_tts` 以及 `callcenter-private-master` 共用的云上曲率账号参数。
        2. 电话实时播报建议使用 `pcm + 8000`，语种默认可填写 `zh-CN`。
        3. 保存后会尝试 reload `mod_vt_tts`，如失败请检查 FreeSWITCH 编译部署是否已包含该模块。
    </div>
    <div id="baseConfigs"></div>
    <div class="row">
        <div class="col-sm-offset-5 col-sm-10">
            <button id="saveConfig" type="button" class="btn btn-sm btn-primary" onclick="submitHandler()">
                <i class="fa fa-check"></i>保存
            </button>
        </div>
    </div>
</div>

<th:block th:include="include :: footer" />
<th:block th:include="include :: layout-latest-js" />
<script>
    var prefix = ctx + "cc/fsconf";

    function escapeHtml(value) {
        return $('<div/>').text(value || '').html();
    }

    function renderInput(config) {
        var name = config.name;
        var value = config.value || '';
        var safeValue = escapeHtml(value);

        if (name === 'format') {
            return '' +
                '<select class="config-value form-control" id="' + name + '">' +
                '<option value="pcm"' + (value === 'pcm' ? ' selected' : '') + '>pcm</option>' +
                '</select>';
        }

        if (name === 'sample-rate') {
            return '' +
                '<select class="config-value form-control" id="' + name + '">' +
                '<option value="8000"' + (value === '8000' ? ' selected' : '') + '>8000</option>' +
                '<option value="16000"' + (value === '16000' ? ' selected' : '') + '>16000</option>' +
                '<option value="22050"' + (value === '22050' ? ' selected' : '') + '>22050</option>' +
                '<option value="24000"' + (value === '24000' ? ' selected' : '') + '>24000</option>' +
                '</select>';
        }

        if (name === 'verify-peer') {
            return '' +
                '<select class="config-value form-control" id="' + name + '">' +
                '<option value="false"' + (value === 'false' ? ' selected' : '') + '>false</option>' +
                '<option value="true"' + (value === 'true' ? ' selected' : '') + '>true</option>' +
                '</select>';
        }

        var inputType = name === 'secret-key' ? 'password' : 'text';
        return '<input class="config-value form-control" type="' + inputType + '" id="' + name + '" value="' + safeValue + '" />';
    }

    function validateConfigs(configs) {
        var configMap = {};
        $.each(configs, function(index, item) {
            configMap[item.name] = item.value;
        });
        if (!configMap['appid']) {
            $.modal.alertError('`appid` 不能为空');
            return false;
        }
        if (!configMap['secret-key']) {
            $.modal.alertError('`secret-key` 不能为空');
            return false;
        }
        if (!configMap['voice-name']) {
            $.modal.alertError('`voice-name` 不能为空');
            return false;
        }
        if (configMap['connect-timeout-ms']) {
            var timeout = parseInt(configMap['connect-timeout-ms'], 10);
            if (isNaN(timeout) || timeout <= 0 || timeout > 120000) {
                $.modal.alertError('`connect-timeout-ms` 必须是 1 到 120000 之间的整数');
                return false;
            }
        }
        return true;
    }

    $(function() {
        $.ajax({
            url: prefix + '/getVtTtsConf',
            type: 'GET',
            success: function(resp) {
                var html = '';
                var data = resp.data || [];
                $.each(data, function(index, config) {
                    html += '<div class="row">';
                    html += '<div class="col-sm-12">';
                    html += '<label class="col-sm-2 control-label">' + config.aliasName + '</label><div class="col-sm-10">' + renderInput(config) + '</div>';
                    html += '</div>';
                    html += '</div>';
                });
                $('#baseConfigs').html(html);
            },
            error: function(error) {
                console.error('Error fetching configuration:', error);
            }
        });
    });

    $('#saveConfig').click(function() {
        var configs = [];
        $('input.config-value').each(function() {
            configs.push({
                name: $(this).attr('id'),
                value: $(this).val().trim()
            });
        });
        $('select.config-value').each(function() {
            configs.push({
                name: $(this).attr('id'),
                value: ($(this).val() || '').trim()
            });
        });

        if (!validateConfigs(configs)) {
            return;
        }

        $.ajax({
            url: prefix + '/setVtTtsConf',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(configs),
            beforeSend: function () {
                $.modal.loading(i18n("common.tip.loading"));
                $.modal.disable();
            },
            success: function(response) {
                processAjaxReponseJson(response);
            }
        });
    });
</script>
</body>
</html>
