<script setup lang="ts">
import {useServerStore} from "../../store/modules/server";
import {useAuthStore} from "../../store/modules/auth";
import {EnumServerStatus, ServerRecord} from "../../types/Server";
import {computed, onMounted, ref, watch} from "vue";
import {Dialog} from "../../lib/dialog";
import {mapError} from "../../lib/error";
import { clearConfigCache, fetchSystemConfig } from "../../service/systemConfig";

const serverStore = useServerStore();
const authStore = useAuthStore();

const select = ref<any>(null);
const props = defineProps<{
    functionName?: string;
    version?: string;
    taskType?: string;
    modelValue?: string;
    showCloud?: boolean;
    showSelfServer?: boolean;
}>();
const emit = defineEmits({
    update: (config: any) => true,
    'update:modelValue': (value: string) => true,
});

const matchesFunctionName = (functions: string[] = [], functionName: string) => {
    const normalizedFunctions = functions.map(f => (f === 'speechRecognition' ? 'asr' : f));
    const normalizedFunctionName = functionName === 'speechRecognition' ? 'asr' : functionName;
    return normalizedFunctions.includes(normalizedFunctionName);
};

const effectiveFunctionName = computed(() => props.functionName || props.taskType || props.version || "");

const normalizeServerConfig = (config: any) => {
    if (!config?.functions) {
        return config;
    }
    const functions = {
        ...config.functions,
    };
    if (functions.speechRecognition && !functions.asr) {
        functions.asr = functions.speechRecognition;
    }
    return {
        ...config,
        functions,
    };
};

const recordsFilter = computed(() => {
    return serverStore.records.filter(s => matchesFunctionName(s.functions, effectiveFunctionName.value));
});

const cloudDisabled = computed(() => {
    return !!authStore.user?.cloud_digital_human_disabled;
});

const cloudBeautyEnabled = ref(false);

onMounted(async () => {
    try {
        clearConfigCache();
        const config = await fetchSystemConfig();
        console.log('[ServerSelector] cloud_beauty_enabled:', config.cloud_beauty_enabled);
        cloudBeautyEnabled.value = config.cloud_beauty_enabled === 'true';
    } catch (e) {
        console.warn('[ServerSelector] 获取配置失败:', e);
    }
});

const showCloudGroup = computed(() => {
    return props.showCloud !== false && !cloudDisabled.value;
});
const showSelfServerGroup = computed(() => {
    return props.showSelfServer && !cloudDisabled.value;
});
const valueAutoStart = computed(() => {
    const server = serverStore.records.find(s => s.key === props.modelValue);
    return server?.autoStart;
});
const valueAutoStartStatus = computed(() => {
    const server = serverStore.records.find(s => s.key === props.modelValue);
    return server?.runtime.autoStartStatus || EnumServerStatus.STOPPED;
});
const valueStatus = computed(() => {
    return serverStore.records.find(s => s.key === props.modelValue)?.status || EnumServerStatus.STOPPED;
});

watch(
    () => cloudDisabled.value,
    disabled => {
        if (disabled && (props.modelValue?.startsWith('__CLOUD') || props.modelValue === '__SELF_SERVER__')) {
            const firstLocal = recordsFilter.value[0];
            emit('update:modelValue', firstLocal ? firstLocal.key : '');
        }
    }
);

watch(
    () => cloudBeautyEnabled.value,
    (enabled, oldEnabled) => {
        if (!enabled && oldEnabled === true && props.modelValue === '__CLOUD_BEAUTY__') {
            const firstLocal = recordsFilter.value[0];
            emit('update:modelValue', firstLocal ? firstLocal.key : '');
        }
    }
);

watch(
    () => props.modelValue,
    async value => {
        if (!value) {
            return;
        }

        // 云端模式：跳过服务器配置获取
        if (value?.startsWith('__CLOUD')) {
            emit("update", {
                isCloud: true,
                functions: {}
            });
            return;
        }

        // 自主算力机模式
        if (value === '__SELF_SERVER__') {
            emit("update", {
                isSelfServer: true,
                functions: {}
            });
            return;
        }

        let config: any = null;
        if (!config) {
            const server = await serverStore.getByKey(value);
            if (server) {
                const res = await window.$mapi.server.config(await serverStore.serverInfo(server));
                if (res.code) {
                    Dialog.tipError(mapError(res.msg));
                    return;
                }
                config = normalizeServerConfig(res.data);
            }
        }
        if (!config) {
            return;
        }
        emit("update", config);
    }
);

</script>

<template>
    <a-select
        ref="select"
        :model-value="modelValue"
        @update:model-value="emit('update:modelValue', $event)"
        :placeholder="$t('选择模型')"
        size="small"
        :trigger-props="{ contentClass: 'dark-select-popup' }"
        class="min-w-64 dark-input-override"
        style="height:32px;"
    >
        <a-optgroup :label="$t('本地模型')">
            <a-option v-for="server in recordsFilter" :key="server.key" :value="server.key">
                <div class="flex items-center py-2 flex-nowrap truncate no-wrap">
                    <div
                        v-if="server.autoStart&&server.runtime.autoStartStatus === EnumServerStatus.RUNNING"
                        class="w-2 h-2 bg-green-500 rounded-full mr-1 flex-shrink-0"
                    ></div>
                    <div
                        v-else-if="server.autoStart&&server.runtime.autoStartStatus !== EnumServerStatus.RUNNING"
                        class="w-2 h-2 bg-blue-500 rounded-full mr-1 flex-shrink-0"
                    ></div>
                    <div
                        v-else-if="server.status === EnumServerStatus.RUNNING"
                        class="w-2 h-2 bg-blue-500 rounded-full mr-1 flex-shrink-0 animate-pulse"
                    ></div>
                    <div v-else class="w-2 h-2 bg-red-700 rounded-full mr-1 flex-shrink-0"></div>
                    <div class="text-xs flex-grow">
                        {{ server.title }}
                        v{{ server.version }}
                    </div>
                </div>
            </a-option>
            <a-option v-if="recordsFilter.length === 0" disabled>
                <div class="text-xs py-2">
                    {{ $t("没有可用本地模型") }}
                </div>
            </a-option>
        </a-optgroup>
        <a-optgroup v-if="showCloudGroup" :label="$t('云端模型')">
            <a-option v-if="cloudBeautyEnabled" value="__CLOUD_BEAUTY__">
                <div class="flex items-center py-2 flex-nowrap truncate no-wrap">
                    <div class="w-2 h-2 bg-pink-500 rounded-full mr-1 flex-shrink-0"></div>
                    <div class="text-xs flex-grow">
                        极速模型
                    </div>
                </div>
            </a-option>
            <a-option value="__CLOUD__">
                <div class="flex items-center py-2 flex-nowrap truncate no-wrap">
                    <div class="w-2 h-2 bg-purple-500 rounded-full mr-1 flex-shrink-0"></div>
                    <div class="text-xs flex-grow">
                        云端模型
                    </div>
                </div>
            </a-option>
            <a-option value="__CLOUD_1942022968606355458__">
                <div class="flex items-center py-2 flex-nowrap truncate no-wrap">
                    <div class="w-2 h-2 bg-purple-500 rounded-full mr-1 flex-shrink-0"></div>
                    <div class="text-xs flex-grow">
                        云端模型plus(更清晰)
                    </div>
                </div>
            </a-option>
        </a-optgroup>
        <a-optgroup v-if="showSelfServerGroup" :label="$t('自主算力')">
            <a-option value="__SELF_SERVER__">
                <div class="flex items-center py-2 flex-nowrap truncate no-wrap">
                    <div class="w-2 h-2 bg-orange-500 rounded-full mr-1 flex-shrink-0"></div>
                    <div class="text-xs flex-grow">
                        自主算力机
                    </div>
                </div>
            </a-option>
        </a-optgroup>
        <template #label="{data}">
            <div class="text-sm flex items-center flex-nowrap truncate no-wrap">
                <div
                    v-if="modelValue?.startsWith('__CLOUD')"
                    class="w-2 h-2 bg-purple-700 rounded-full mr-1 flex-shrink-0"
                ></div>
                <div
                    v-else-if="modelValue === '__SELF_SERVER__'"
                    class="w-2 h-2 bg-orange-500 rounded-full mr-1 flex-shrink-0"
                ></div>
                <div
                    v-else-if="valueStatus === EnumServerStatus.RUNNING"
                    class="w-2 h-2 bg-green-700 rounded-full mr-1 flex-shrink-0"
                ></div>
                <div v-else class="w-2 h-2 bg-red-700 rounded-full mr-1 flex-shrink-0"></div>

                <!-- 根据 modelValue 直接判断显示什么，不依赖 data.label -->
                <div v-if="modelValue === '__CLOUD__'" class="flex-grow">
                    云端模型
                </div>
                <div v-else-if="modelValue === '__CLOUD_1942022968606355458__'" class="flex-grow">
                    云端模型plus(更清晰)
                </div>
                <div v-else-if="modelValue === '__CLOUD_BEAUTY__'" class="flex-grow">
                    极速模型
                </div>
                <div v-else-if="modelValue === '__SELF_SERVER__'" class="flex-grow">
                    自主算力机
                </div>
                <div v-else>
                    <div v-if="recordsFilter.length > 0">
                        {{
                            serverStore.records.find(s => s.key === modelValue)?.title
                            ? `${serverStore.records.find(s => s.key === modelValue)?.title} v${serverStore.records.find(s => s.key === modelValue)?.version}`
                            : '选择模型'
                        }}
                    </div>
                    <div v-else>
                        {{ $t("没有可用模型") }}
                    </div>
                </div>
            </div>
        </template>
    </a-select>
</template>

<style scoped>
:deep(.arco-select-view-single) {
    background-color: #1a1a1a;
    border-color: #333;
    color: #e5e7eb;
}

:deep(.arco-select-view-single:hover) {
    border-color: #4b5563;
}
</style>
