<script setup lang="ts">
// @ts-nocheck
import {onMounted, ref, computed, onBeforeUnmount} from "vue";
import {StorageRecord, StorageService} from "../../../service/StorageService";
import SoundPromptDialog from "./SoundPromptDialog.vue";
import {GlobalEvent} from "../../../lib/event";

const soundPromptDialog = ref<InstanceType<typeof SoundPromptDialog>>();
const records = ref<StorageRecord[]>([]);
const isListenerRegistered = ref(false);  // 🔧 追踪是否已注册监听器

// 🎯 系统默认音色列表（与Dialog保持一致）
const systemVoices = [
    { id: 'sys_Cherry', title: '芊悦（普通话女声｜适合：普通话）', aliyunVoiceId: 'Cherry' },
    { id: 'sys_Serena', title: '苏瑶（普通话女声｜适合：普通话）', aliyunVoiceId: 'Serena' },
    { id: 'sys_Ethan', title: '晨煦（普通话男声｜适合：普通话）', aliyunVoiceId: 'Ethan' },
    { id: 'sys_Chelsie', title: '千雪（二次元女声｜适合：普通话）', aliyunVoiceId: 'Chelsie' },
    { id: 'sys_Momo', title: '茉兔（活泼女声｜适合：普通话）', aliyunVoiceId: 'Momo' },
    { id: 'sys_Vivian', title: '十三（个性女声｜适合：普通话）', aliyunVoiceId: 'Vivian' },
    { id: 'sys_Moon', title: '月白（率性男声｜适合：普通话）', aliyunVoiceId: 'Moon' },
    { id: 'sys_Maia', title: '四月（知性女声｜适合：普通话）', aliyunVoiceId: 'Maia' },
    { id: 'sys_Kai', title: '凯（沉浸男声｜适合：普通话）', aliyunVoiceId: 'Kai' },
    { id: 'sys_Nofish', title: '不吃鱼（特色男声｜适合：普通话）', aliyunVoiceId: 'Nofish' },
    { id: 'sys_Bella', title: '萌宝（萝莉女声｜适合：普通话）', aliyunVoiceId: 'Bella' },
    { id: 'sys_Jennifer', title: '詹妮弗（美语女声｜适合：英语）', aliyunVoiceId: 'Jennifer' },
    { id: 'sys_Ryan', title: '甜茶（张力男声｜适合：普通话）', aliyunVoiceId: 'Ryan' },
    { id: 'sys_Katerina', title: '卡捷琳娜（御姐女声｜适合：普通话）', aliyunVoiceId: 'Katerina' },
    { id: 'sys_Aiden', title: '艾登（美语男声｜适合：英语）', aliyunVoiceId: 'Aiden' },
    { id: 'sys_Arthur', title: '徐大爷（故事男声｜适合：普通话）', aliyunVoiceId: 'Arthur' },
    { id: 'sys_Bellona', title: '燕铮莺（洪亮女声｜适合：普通话）', aliyunVoiceId: 'Bellona' },
    { id: 'sys_Bunny', title: '萌小姬（萌系女声｜适合：普通话）', aliyunVoiceId: 'Bunny' },
    { id: 'sys_Mia', title: '乖小妹（温顺女声｜适合：普通话）', aliyunVoiceId: 'Mia' },
    { id: 'sys_Mochi', title: '沙小弥（早慧童声｜适合：普通话）', aliyunVoiceId: 'Mochi' },
    { id: 'sys_Neil', title: '阿闻（新闻男声｜适合：普通话）', aliyunVoiceId: 'Neil' },
    { id: 'sys_Nini', title: '邻家妹妹（甜美女声｜适合：普通话）', aliyunVoiceId: 'Nini' },
    { id: 'sys_Ebona', title: '诡婆婆（惊悚女声｜适合：普通话）', aliyunVoiceId: 'Ebona' },
    { id: 'sys_Seren', title: '小婉（助眠女声｜适合：普通话）', aliyunVoiceId: 'Seren' },
    { id: 'sys_Pip', title: '顽屁小孩（淘气童声｜适合：普通话）', aliyunVoiceId: 'Pip' },
    { id: 'sys_Stella', title: '少女阿月（元气女声｜适合：普通话）', aliyunVoiceId: 'Stella' },
    { id: 'sys_Vincent', title: '田叔（烟嗓男声｜适合：普通话）', aliyunVoiceId: 'Vincent' },
    { id: 'sys_Radio_Gol', title: '拉迪奥·戈尔（足球解说｜适合：普通话）', aliyunVoiceId: 'Radio Gol' },
    { id: 'sys_Jada', title: '上海-阿珍（上海话女声｜适合：上海话）', aliyunVoiceId: 'Jada' },
    { id: 'sys_Dylan', title: '北京-晓东（北京话男声｜适合：北京话）', aliyunVoiceId: 'Dylan' },
    { id: 'sys_Li', title: '南京-老李（南京话男声｜适合：南京话）', aliyunVoiceId: 'Li' },
    { id: 'sys_Marcus', title: '陕西-秦川（陕西话男声｜适合：陕西话）', aliyunVoiceId: 'Marcus' },
    { id: 'sys_Roy', title: '闽南-阿杰（闽南语男声｜适合：闽南语）', aliyunVoiceId: 'Roy' },
    { id: 'sys_Peter', title: '天津-李彼得（天津话男声｜适合：天津话）', aliyunVoiceId: 'Peter' },
    { id: 'sys_Sunny', title: '四川-晴儿（四川话女声｜适合：四川话）', aliyunVoiceId: 'Sunny' },
    { id: 'sys_Eric', title: '四川-程川（四川话男声｜适合：四川话）', aliyunVoiceId: 'Eric' },
    { id: 'sys_Rocky', title: '粤语-阿强（粤语男声｜适合：粤语）', aliyunVoiceId: 'Rocky' },
    { id: 'sys_Kiki', title: '粤语-阿清（粤语女声｜适合：粤语）', aliyunVoiceId: 'Kiki' },
    { id: 'sys_Bodega', title: '博德加（西语男声｜适合：西班牙语）', aliyunVoiceId: 'Bodega' },
    { id: 'sys_Sonrisa', title: '索尼莎（西语女声｜适合：西班牙语）', aliyunVoiceId: 'Sonrisa' },
    { id: 'sys_Alek', title: '阿列克（俄语男声｜适合：俄语）', aliyunVoiceId: 'Alek' },
    { id: 'sys_Dolce', title: '多尔切（意语男声｜适合：意大利语）', aliyunVoiceId: 'Dolce' },
    { id: 'sys_Sohee', title: '素熙（韩语女声｜适合：韩语）', aliyunVoiceId: 'Sohee' },
    { id: 'sys_Ono_Anna', title: '小野杏（日语女声｜适合：日语）', aliyunVoiceId: 'Ono Anna' },
    { id: 'sys_Lenn', title: '莱恩（德语男声｜适合：德语）', aliyunVoiceId: 'Lenn' },
    { id: 'sys_Emilien', title: '埃米尔安（法语男声｜适合：法语）', aliyunVoiceId: 'Emilien' },
    { id: 'sys_Andre', title: '安德雷（磁性男声｜适合：普通话）', aliyunVoiceId: 'Andre' },
];

// 🔧 监听全局事件,实现跨页面音色同步
const handleSoundPromptUpdate = async () => {
    await doRefresh();
};

onMounted(async () => {
    await doRefresh();

    // 🔧 监听全局音色更新事件（防止重复注册）
    if (!isListenerRegistered.value) {
        GlobalEvent.on('soundPromptUpdated', handleSoundPromptUpdate);
        isListenerRegistered.value = true;
    }
});

onBeforeUnmount(() => {
    // 清理事件监听（只在已注册时清理）
    if (isListenerRegistered.value) {
        GlobalEvent.off('soundPromptUpdated', handleSoundPromptUpdate);
        isListenerRegistered.value = false;
    }
});

const doRefresh = async () => {
    records.value = await StorageService.list("SoundPrompt");
};

const props = defineProps({
    modelValue: {
        type: [Number, String],  // 🔧 支持数字和字符串类型
        required: true,
        default: 0,
    },
    disabled: {
        type: Boolean,
        default: false,
    },
});

const emit = defineEmits(["update:modelValue"]);

const onSelect = (id: number | string) => {
    emit("update:modelValue", id);
};

const doSelect = () => {
    if (props.disabled) {
        return;
    }
    soundPromptDialog.value?.show();
};

// 🔧 计算显示的音色名称
const displayTitle = computed(() => {
    if (!props.modelValue) {
        return "选择音色";
    }
    
    // 检查是否为系统音色
    if (typeof props.modelValue === 'string' && props.modelValue.startsWith('sys_')) {
        const systemVoice = systemVoices.find(v => v.id === props.modelValue);
        return systemVoice ? systemVoice.title : "选择音色";
    }
    
    // 用户自定义音色
    const record = records.value.find(s => s.id === props.modelValue);
    return record ? record.title : "选择音色";
});
</script>

<template>
    <div class="flex items-center">
        <div
            @click="doSelect()"
            class="sound-prompt-trigger mr-1 h-8 leading-8 px-3 rounded-lg cursor-pointer truncate w-full transition-colors"
            :class="[
                disabled ? 'cursor-not-allowed opacity-50' : '',
                $attrs.class?.includes('dark-input-override') ? 'sound-prompt-trigger--embedded' : 'sound-prompt-trigger--default'
            ]"
        >
            {{ displayTitle }}
        </div>
    </div>
    <SoundPromptDialog ref="soundPromptDialog" @update="doRefresh" @select="onSelect"/>
</template>

<style scoped>
.sound-prompt-trigger--default {
  background: #f3f4f6;
  color: #1f2937;
}

.sound-prompt-trigger--default:hover {
  background: #e5e7eb;
}

.sound-prompt-trigger--embedded {
  background: #2a2a2a;
  color: #e5e7eb;
  border: 1px solid #374151;
}

:global(body[data-theme="soft-light"]) .sound-prompt-trigger--embedded {
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.96) 0%, rgba(244, 245, 255, 0.98) 100%) !important;
  color: #1f2749 !important;
  border: 1px solid rgba(132, 142, 220, 0.26) !important;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.92), 0 10px 24px rgba(104, 110, 170, 0.08) !important;
}

:global(body[data-theme="soft-light"]) .sound-prompt-trigger--embedded:hover {
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.98) 0%, rgba(247, 248, 255, 0.995) 100%) !important;
  border-color: rgba(106, 116, 247, 0.34) !important;
}
</style>
