<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { t } from "../../../lang";
import { Dialog } from "../../../lib/dialog";
import { StorageUtil } from "../../../lib/storage";
import { StorageService } from "../../../service/StorageService";
import { useModelStore } from "../../../module/Model/store/model";
import { fetchSystemConfig, getSystemConfigSync } from "../../../service/systemConfig";
import SoundPromptDialog from "./SoundPromptDialog.vue";
import SoundPromptSelector from "./SoundPromptSelector.vue";

const systemVoiceMap: Record<string, string> = {
    sys_Cherry: "Cherry",
    sys_Serena: "Serena",
    sys_Ethan: "Ethan",
    sys_Chelsie: "Chelsie",
    sys_Momo: "Momo",
    sys_Vivian: "Vivian",
    sys_Moon: "Moon",
    sys_Maia: "Maia",
    sys_Kai: "Kai",
    sys_Nofish: "Nofish",
    sys_Bella: "Bella",
    sys_Jennifer: "Jennifer",
    sys_Ryan: "Ryan",
    sys_Katerina: "Katerina",
    sys_Aiden: "Aiden",
    sys_Arthur: "Arthur",
    sys_Bellona: "Bellona",
    sys_Bunny: "Bunny",
    sys_Mia: "Mia",
    sys_Mochi: "Mochi",
    sys_Neil: "Neil",
    sys_Nini: "Nini",
    sys_Ebona: "Ebona",
    sys_Seren: "Seren",
    sys_Pip: "Pip",
    sys_Stella: "Stella",
    sys_Vincent: "Vincent",
    sys_Radio_Gol: "Radio Gol",
    sys_Jada: "Jada",
    sys_Dylan: "Dylan",
    sys_Li: "Li",
    sys_Marcus: "Marcus",
    sys_Roy: "Roy",
    sys_Peter: "Peter",
    sys_Sunny: "Sunny",
    sys_Eric: "Eric",
    sys_Rocky: "Rocky",
    sys_Kiki: "Kiki",
    sys_Bodega: "Bodega",
    sys_Sonrisa: "Sonrisa",
    sys_Alek: "Alek",
    sys_Dolce: "Dolce",
    sys_Sohee: "Sohee",
    sys_Ono_Anna: "Ono Anna",
    sys_Lenn: "Lenn",
    sys_Emilien: "Emilien",
    sys_Andre: "Andre",
};

const modelStore = useModelStore();

const resolveAliyunTtsModelByVoiceId = (voiceId?: string) => {
    if (!voiceId || voiceId === "Cherry") {
        return "qwen3-tts-flash";
    }

    if (voiceId.startsWith("qwen-tts-vc-")) {
        return "qwen3-tts-vc-2026-01-22";
    }

    if (voiceId.startsWith("cosyvoice-v3-flash-")) {
        return "qwen3-tts-flash";
    }

    return "qwen3-tts-flash";
};

const formData = ref({
    type: "AliyunTts" as string,
    // 在线TTS模型选择（与VideoIPAgent设置一致）
    onlineTtsModel: "cosyvoice" as "cosyvoice" | "runninghub",
    aliyunPromptId: 0 as number | string,
});

// 阿里云API Key（从模型设置读取）
const aliyunApiKey = ref("");

// 加载阿里云API Key
const loadAliyunApiKey = async () => {
    await modelStore.refreshBuildIn();
    const dashscopeProvider = modelStore.providers.find(p => p.id === 'dashscope');
    if (dashscopeProvider && dashscopeProvider.data.apiKey) {
        aliyunApiKey.value = dashscopeProvider.data.apiKey;
    } else {
        aliyunApiKey.value = "";
    }
};

// 模型选项列表（与VideoIPAgent一致）
const modelOptions = [
    { value: "cosyvoice", label: "V1 多语言/方言" },
    { value: "runninghub", label: "V2 情感合成" },
];

// 模型说明映射
const modelDescriptions: Record<string, string> = {
    "cosyvoice": "V1说明：选择他国语言需要文案也对应他国，选择方言需对应匹配的音色或克隆音色本身是方言",
    "runninghub": "V2版本：中文效果更好，支持情绪表达",
};

onMounted(async () => {
    const old = StorageUtil.getObject("SoundGenerateForm.formData");
    formData.value.onlineTtsModel = old.onlineTtsModel || "cosyvoice";
    formData.value.aliyunPromptId = old.aliyunPromptId || 0;
    
    // 加载阿里云API Key
    await fetchSystemConfig();
    await loadAliyunApiKey();
});
watch(
    () => formData.value,
    async value => {
        StorageUtil.set("SoundGenerateForm.formData", value);
    },
    {
        deep: true,
    }
);

const getValue = async (): Promise<SoundGenerateParamType | undefined> => {
    const data: any = {};
    data.type = formData.value.onlineTtsModel === "runninghub" ? "RunningHubTts" : "AliyunTts";
    data.onlineTtsModel = formData.value.onlineTtsModel;

    // 获取选择的音色
    if (!formData.value.aliyunPromptId) {
        Dialog.tipError(t("请选择声音音色"));
        return;
    }
    
    data.promptId = formData.value.aliyunPromptId;
    
    // 所有模型统一使用 qwen3-tts-flash（与VideoIPAgent的CosyVoice路径一致）
    let voiceId = "Cherry";
    let promptTitle = "默认音色";
    // 默认使用 qwen3-tts-flash（与VideoIPAgent line 5101 一致）
    let model = "qwen3-tts-flash";

    if (typeof formData.value.aliyunPromptId === 'string' && formData.value.aliyunPromptId.startsWith('sys_')) {
        voiceId = systemVoiceMap[formData.value.aliyunPromptId] || "Cherry";
        promptTitle = `系统音色-${voiceId}`;
    } else {
        const prompt = await StorageService.get(formData.value.aliyunPromptId as number);
        if (!prompt) {
            Dialog.tipError(t("声音音色不存在"));
            return;
        }
        promptTitle = prompt.title;
        voiceId = prompt.content.aliyunVoiceId || "Cherry";
        // 自定义克隆音色使用 vc 模型（与VideoIPAgent line 5172 一致）
        model = resolveAliyunTtsModelByVoiceId(voiceId);
    }
    
    const modelOption = modelOptions.find(o => o.value === formData.value.onlineTtsModel);
    const modelLabel = modelOption ? modelOption.label : "V1 多语言/方言";
    
    data.serverName = "Aliyun";
    data.serverTitle = modelLabel;
    data.serverVersion = "1.0.0";
    data.promptTitle = promptTitle;
    data.aliyunConfig = {
        apiKey: aliyunApiKey.value || getSystemConfigSync().aliyun_bailian_api_key,
        model: model,
        voice: voiceId,
        format: "mp3",
        sampleRate: 22050
    };
    data.runninghubConfig = {
        apiKey: getSystemConfigSync().runninghub_api_key,
        promptId: formData.value.aliyunPromptId,
        version: "v2",
        speed: 1
    };
    return data;
};

const setValue = (data: Partial<SoundGenerateParamType>) => {
    if ((data as any).onlineTtsModel !== undefined) {
        formData.value.onlineTtsModel = (data as any).onlineTtsModel;
    }
    if ((data as any).aliyunPromptId !== undefined) {
        formData.value.aliyunPromptId = (data as any).aliyunPromptId;
    }
};

defineExpose({
    getValue,
    setValue,
});
</script>

<template>
    <div class="mb-4">
        <div class="font-bold mb-2 text-gray-200">
            <div class="inline-block w-5">
                <icon-settings />
            </div>
            {{ $t("声音合成配置") }}
        </div>
        <!-- 模型选择（下拉框） -->
        <div class="flex items-center min-h-8 gap-2 mb-2">
            <div class="pt-1 text-gray-200">
                <a-tooltip :content="$t('在线TTS模型')" mini>
                    <i class="iconfont icon-server"></i>
                </a-tooltip>
            </div>
            <div class="flex-1">
                <a-select 
                    v-model="formData.onlineTtsModel" 
                    class="dark-input-override"
                    size="small"
                    :trigger-props="{ contentClass: 'dark-select-popup' }"
                >
                    <a-option v-for="opt in modelOptions" :key="opt.value" :value="opt.value">
                        {{ opt.label }}
                    </a-option>
                </a-select>
            </div>
        </div>
        <!-- 模型说明 -->
        <div class="text-xs text-gray-500 mb-2 ml-6">
            {{ $t(modelDescriptions[formData.onlineTtsModel] || '') }}
        </div>
        <!-- 音色选择 -->
        <div class="flex items-center min-h-8 gap-2">
            <div class="pt-1 text-gray-200">
                <a-tooltip :content="$t('声音音色')" mini>
                    <i class="iconfont icon-sound-prompt"></i>
                </a-tooltip>
            </div>
            <div class="mr-2 flex items-center w-full">
                <SoundPromptSelector v-model="formData.aliyunPromptId" class="dark-input-override w-full" />
            </div>
        </div>
    </div>
    <SoundPromptDialog />
</template>

<style scoped>
:deep(.icon-settings), 
:deep(.icon-server),
:deep(.icon-sound-prompt) {
    color: #e5e7eb !important;
}
</style>
