<script setup lang="ts">
import {onMounted, ref} from "vue";
import {StorageUtil} from "../../../lib/storage";
import SoundGenerateForm from "./SoundGenerateForm.vue";
import BatchTextareaInputAction from "../../../components/BatchTextareaInputAction.vue";
import {Dialog} from "../../../lib/dialog";
import {t} from "../../../lang";
import {TaskRecord, TaskService} from "../../../service/TaskService";
import { resolveRunningHubAudioFileName } from "../../../service/RunningHubVoiceService";

const soundGenerateForm = ref<InstanceType<typeof SoundGenerateForm>>();
const props = defineProps<{
    simpleMode?: boolean;
}>();
const formData = ref({
    text: "",
});

onMounted(async () => {
    const old = StorageUtil.getObject("SoundGenerateCreate.formData");
    formData.value.text = old.text || "";
});

const synthesizeVoice = async (text: string, value: SoundGenerateParamType) => {
    if (value.type === "RunningHubTts") {
        const audioFileName = await resolveRunningHubAudioFileName(value.promptId);
        return await window.$mapi.runninghub.ttsSynthesize({
            text,
            config: {
                ...(value.runninghubConfig || {}),
                audioFileName,
                version: "v2"
            }
        });
    }

    return await window.$mapi.aliyun.cosyvoice.synthesize({
        text,
        config: value.aliyunConfig
    });
};

const doSubmit = async () => {
    const value = await soundGenerateForm.value?.getValue();
    if (!value) {
        return;
    }
    if (!formData.value.text) {
        Dialog.tipError(t("请输入合成内容"));
        return;
    }
    
    Dialog.loadingOn(t("正在合成语音..."));
    try {
        // 统一调用 aliyun cosyvoice API（与VideoIPAgent一致）
        const result = await synthesizeVoice(formData.value.text, value);
        
        if (result.success) {
            Dialog.tipSuccess(t("语音合成成功"));
            if (result.audioPath) {
                const record: TaskRecord = {
                    biz: "SoundGenerate",
                    title: await window.$mapi.file.textToName(formData.value.text || "tts"),
                    serverName: value.serverName,
                    serverTitle: value.serverTitle,
                    serverVersion: value.serverVersion,
                    modelConfig: {
                        type: value.type,
                        text: formData.value.text,
                        aliyunConfig: value.aliyunConfig,
                        runninghubConfig: value.runninghubConfig,
                        audioPath: result.audioPath
                    },
                };
                await TaskService.submit(record);
            }
            formData.value.text = "";
            emit("submitted");
        } else {
            Dialog.tipError(t("合成失败") + ": " + (result.error || "未知错误"));
        }
    } catch (error: any) {
        Dialog.tipError(t("合成失败") + ": " + error.message);
    } finally {
        Dialog.loadingOff();
    }
};

const doSubmitBatch = async (records: { text: string }[]) => {
    const value = await soundGenerateForm.value?.getValue();
    if (!value) {
        return;
    }
    Dialog.loadingOn(t("正在批量合成语音..."));
    try {
        for (const r of records) {
            const result = await synthesizeVoice(r.text, value);
            if (result.success && result.audioPath) {
                const record: TaskRecord = {
                    biz: "SoundGenerate",
                    title: await window.$mapi.file.textToName(r.text || "tts"),
                    serverName: value.serverName,
                    serverTitle: value.serverTitle,
                    serverVersion: value.serverVersion,
                    modelConfig: {
                        type: value.type,
                        text: r.text,
                        aliyunConfig: value.aliyunConfig,
                        runninghubConfig: value.runninghubConfig,
                        audioPath: result.audioPath
                    },
                };
                await TaskService.submit(record);
            }
        }
        Dialog.tipSuccess(t("批量合成完成"));
        emit("submitted");
    } catch (error: any) {
        Dialog.tipError(t("合成失败") + ": " + error.message);
    } finally {
        Dialog.loadingOff();
    }
};

const emit = defineEmits({
    submitted: () => true,
});
</script>

<template>
    <div :class="simpleMode ? 'bg-[#141414] border border-[#333] rounded-xl' : 'glass-card rounded-lg overflow-hidden'">
        <div v-if="!simpleMode" class="glass-card-header flex items-center justify-between">
            <div class="flex items-center gap-2">
                <div class="w-5 h-5 rounded-full flex items-center justify-center text-xs font-bold" style="background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%); color: white;">01</div>
                <h3 class="text-base font-semibold" style="color: #e2e8f0;">{{ $t("声音合成") }}</h3>
            </div>
        </div>
        
        <div class="p-4">
            <div class="mb-3">
                <a-textarea
                    v-model="formData.text"
                    class="dark-input-override"
                    :auto-size="{minRows: 4, maxRows: 12}"
                    :placeholder="$t('输入语音内容开始合成')"
                ></a-textarea>
            </div>

            <SoundGenerateForm ref="soundGenerateForm"/>
            <div class="flex gap-1 mt-4">
                <a-button class="mr-2" type="primary" @click="doSubmit">
                    {{ $t("开始合成") }}
                </a-button>
                <BatchTextareaInputAction
                    :text="$t('批量文本合成')"
                    :confirm-text="$t('提交合成')"
                    @submit="doSubmitBatch"
                />
            </div>
        </div>
    </div>
</template>
