<script setup lang="ts">
import {computed, ref, watch} from "vue";
import {useModelStore} from "./store/model";
import ProviderAddDialog from "./components/ProviderAddDialog.vue";
import ProviderEditDialog from "./components/ProviderEditDialog.vue";
import {getProviderUrl} from "./providers";
import ModelAddDialog from "./components/ModelAddDialog.vue";
import ModelEditDialog from "./components/ModelEditDialog.vue";
import ProviderTestDialog from "./components/ProviderTestDialog.vue";
import {getModelLogo} from "./models";
import {useUserStore} from "../../store/modules/user";
import {useSettingStore} from "../../store/modules/setting";
import {Dialog} from "../../lib/dialog";

const userStore = useUserStore();
const setting = useSettingStore();
const modelStore = useModelStore();
const providerAdd = ref<InstanceType<typeof ProviderAddDialog> | null>(null);
const providerEdit = ref<InstanceType<typeof ProviderEditDialog> | null>(null);
const modelAdd = ref<InstanceType<typeof ModelAddDialog> | null>(null);
const modelEdit = ref<InstanceType<typeof ModelEditDialog> | null>(null);
const providerTest = ref<InstanceType<typeof ProviderTestDialog> | null>(null);
const doUser = async () => {
    if (!setting.basic.userEnable) {
        return;
    }
    await window.$mapi.user.open({
        readyParam: {
            page: "ChargeLmApi",
        },
    });
};

const keywords = ref("");
const currentProviderId = ref("");
const builtinCustomModel = ref({
    id: "",
    name: "",
});

const doSelectProvider = (id: string) => {
    currentProviderId.value = id;
};
const provider = computed(() => {
    return modelStore.providers.find(p => p.id === currentProviderId.value);
});
const providerUrl = computed(() => {
    return getProviderUrl(provider.value as any);
});
const canAddBuiltinCustomModel = computed(() => {
    return provider.value?.id === "builtInDoubao";
});
const providerModelGroups = computed(() => {
    if (!provider.value) {
        return [];
    }
    const models = provider.value.data.models;
    const groups = models.map(m => m.group).filter((v, i, a) => a.indexOf(v) === i);
    return groups.map(g => {
        return {
            group: g,
            models: models.filter(m => m.group === g),
        };
    });
});
const providersFilter = computed(() => {
    return modelStore.providers.filter(p => {
        if (keywords.value) {
            return p.title.toLowerCase().includes(keywords.value.toLowerCase());
        }
        return true;
    });
});

// 分组显示：内置提供商和自定义提供商
const builtInProviders = computed(() => {
    // 只显示火山引擎（内置），隐藏其他所有内置提供商
    return providersFilter.value.filter(p => p.isBuiltIn && p.id === 'builtInDoubao');
});

const customProviders = computed(() => {
    // 只显示用户真正自己添加的提供商，过滤掉所有预设的
    return providersFilter.value.filter(p => {
        // 排除系统内置
        if (p.id === 'buildIn') return false;
        // 排除所有内置提供商
        if (p.isBuiltIn) return false;
        // 排除所有系统预设的提供商（OpenAI, O3, PPIO等）
        if (p.isSystem) return false;
        // 只保留用户自己添加的
        return true;
    });
});

const buildInProvider = computed(() => {
    return providersFilter.value.find(p => p.id === 'buildIn');
});
watch(
    () => modelStore.providers,
    () => {
        if (!currentProviderId.value && modelStore.providers.length > 0) {
            // 🔧 自动选择第一个provider时，跳过 builtInAliyun
            const firstProvider = modelStore.providers.find(p => p.id !== 'builtInAliyun');
            if (firstProvider) {
                doSelectProvider(firstProvider.id);
            }
        }
    },
    {immediate: true}
);
const addBuiltinCustomModel = async () => {
    const id = builtinCustomModel.value.id.trim();
    const name = builtinCustomModel.value.name.trim();
    if (!canAddBuiltinCustomModel.value) {
        return;
    }
    if (!id || !name) {
        Dialog.tipError("请填写模型Key和模型名称");
        return;
    }
    const added = await modelStore.modelAdd("builtInDoubao", {
        id,
        name,
        group: "自定义模型",
        types: ["text"],
        editable: true,
    });
    if (added) {
        builtinCustomModel.value.id = "";
        builtinCustomModel.value.name = "";
        Dialog.tipSuccess("模型已添加，可在智能体设置中直接选择");
    }
};
</script>

<template>
    <div class="model-setting-shell flex h-full bg-[#0a0a0a]">
        <div class="model-setting-sidebar w-56 border-r border-[#333] flex flex-col flex-shrink-0 bg-[#141414]">
            <div class="p-2">
                <a-input :placeholder="$t('搜索模型平台')" v-model="keywords" class="dark-input">
                    <template #suffix>
                        <icon-search/>
                    </template>
                </a-input>
            </div>
            <div class="flex-grow p-2 overflow-x-hidden overflow-y-auto">
                <div v-if="!providersFilter.length && modelStore.providers.length">
                    <a-empty :description="$t('没有找到相关模型平台')"/>
                </div>

                <!-- 系统内置模型部分 -->
                <div v-if="buildInProvider">
                    <div class="text-xs font-bold text-gray-400 px-3 py-2 mb-1">{{ $t("系统模型") }}</div>
                    <div
                        class="provider-nav-item flex hover:bg-[#1a1a1a] cursor-pointer border border-transparent rounded-full mb-3 px-3 py-1 items-center"
                        :class="currentProviderId === buildInProvider.id ? 'provider-nav-item-active bg-[#1a1a1a] border-[#444]' : ''"
                        @click="doSelectProvider(buildInProvider.id)"
                    >
                        <div class="mr-2">
                            <img v-if="buildInProvider.logo"
                                 class="w-[20px] h-[20px] rounded"
                                 style="background:#333;border:1px solid #444;"
                                 :src="buildInProvider.logo"/>
                            <a-avatar v-else :size="20" shape="square"
                                      :style="{backgroundColor: '#3370ff'}">
                                {{ buildInProvider.title }}
                            </a-avatar>
                        </div>
                        <div class="flex-grow text-gray-200">
                            {{ buildInProvider.title }}
                        </div>
                        <div v-if="buildInProvider.data.enabled">
                            <icon-check-circle class="text-green-600"/>
                        </div>
                    </div>
                </div>

                <!-- 内置提供商部分 -->
                <div v-if="builtInProviders.length > 0">
                    <div class="text-xs font-bold text-gray-400 px-3 py-2 mb-1">{{ $t("内置模型") }}</div>
                    <div v-for="p in builtInProviders" :key="p.id">
                        <div
                            class="provider-nav-item flex hover:bg-[#1a1a1a] cursor-pointer border border-transparent rounded-full mb-3 px-3 py-1 items-center"
                            :class="currentProviderId === p.id ? 'provider-nav-item-active bg-[#1a1a1a] border-[#444]' : ''"
                            @click="doSelectProvider(p.id)"
                        >
                            <div class="mr-2">
                                <img v-if="p.logo"
                                     class="w-[20px] h-[20px] rounded"
                                     style="background:#333;border:1px solid #444;"
                                     :src="p.logo"/>
                                <a-avatar v-else :size="20" shape="square"
                                          :style="{backgroundColor: '#3370ff'}">
                                    {{ p.title }}
                                </a-avatar>
                            </div>
                            <div class="flex-grow text-gray-200">
                                {{ p.title }}
                            </div>
                            <div v-if="p.data.enabled">
                                <icon-check-circle class="text-green-600"/>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 自定义提供商部分 -->
                <div v-if="customProviders.length > 0">
                    <div class="text-xs font-bold text-gray-400 px-3 py-2 mb-1">{{ $t("自定义") }}</div>
                    <div v-for="p in customProviders" :key="p.id">
                        <div
                            class="provider-nav-item flex hover:bg-[#1a1a1a] cursor-pointer border border-transparent rounded-full mb-3 px-3 py-1 items-center"
                            :class="currentProviderId === p.id ? 'provider-nav-item-active bg-[#1a1a1a] border-[#444]' : ''"
                            @click="doSelectProvider(p.id)"
                        >
                            <div class="mr-2">
                                <img v-if="p.logo"
                                     class="w-[20px] h-[20px] rounded"
                                     style="background:#333;border:1px solid #444;"
                                     :src="p.logo"/>
                                <a-avatar v-else :size="20" shape="square"
                                          :style="{backgroundColor: '#3370ff'}">
                                    {{ p.title }}
                                </a-avatar>
                            </div>
                            <div class="flex-grow text-gray-200">
                                {{ p.title }}
                            </div>
                            <div v-if="p.data.enabled">
                                <icon-check-circle class="text-green-600"/>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="p-2">
                <a-button class="w-full" @click="providerAdd?.show()">
                    {{ $t("添加") }}
                    <template #icon>
                        <icon-plus/>
                    </template>
                </a-button>
            </div>
        </div>
        <div class="model-setting-content flex-grow overflow-y-auto overflow-x-hidden bg-[#0a0a0a]">
            <div class="py-20" v-if="!provider">
                <a-empty :description="$t('请选择模型平台')"/>
            </div>
            <div v-else class="p-3">
                <div class="provider-header flex items-center border-b border-[#333] pb-3 mb-3">
                    <div class="font-bold mr-2 text-gray-200">
                        {{ provider.title }}
                    </div>
                    <div class="flex-grow">
                        <!-- 只有非系统且非内置的提供商才能编辑 -->
                        <a
                            v-if="!provider.isSystem && !provider.isBuiltIn"
                            href="javascript:;"
                            class="mr-2"
                            @click="providerEdit?.show(provider)"
                        >
                            <icon-edit/>
                        </a>
                        <a
                            v-if="provider?.websites.official"
                            class="mr-2"
                            target="_blank"
                            :href="provider?.websites.official"
                        >
                            <icon-desktop/>
                        </a>
                    </div>
                    <div>
                        <a-switch
                            :model-value="provider.data.enabled"
                            @change="modelStore.change(provider.id, 'data.enabled', $event)"
                        />
                    </div>
                </div>
                <!-- 内置提供商提示 -->
                <div class="builtin-provider-tip mb-3 flex border rounded p-3 items-center bg-green-900/20 border-green-700" v-if="provider.isBuiltIn">
                    <div class="flex-grow">
                        <icon-check class="text-green-500 inline mr-2" />
                        <span class="text-gray-300">{{ $t("内置模型无需配置可直接使用") }}</span>
                    </div>
                </div>

                <!-- API密钥（非内置提供商显示，排除dashscope） -->
                <div v-if="canAddBuiltinCustomModel" class="builtin-model-add-panel mb-4">
                    <div class="builtin-model-add-title">添加自定义模型</div>
                    <div class="builtin-model-add-grid">
                        <a-input
                            v-model:model-value="builtinCustomModel.id"
                            placeholder="模型 Key，例如 doubao-seed-1-6-thinking"
                        />
                        <a-input
                            v-model:model-value="builtinCustomModel.name"
                            placeholder="模型名称，例如 豆包推理版"
                        />
                        <a-button type="primary" @click="addBuiltinCustomModel">
                            <template #icon>
                                <icon-plus/>
                            </template>
                            添加模型
                        </a-button>
                    </div>
                    <div class="builtin-model-add-tip">
                        添加后会直接出现在“智能体设置 -> 模型设置”的文本模型选择中。
                    </div>
                </div>
                <div class="mb-3" v-if="provider.id !== 'buildIn' && !provider.isBuiltIn && provider.id !== 'dashscope'">
                    <div class="mb-2 font-bold text-gray-200">{{ $t("API密钥") }}</div>
                    <div>
                        <a-input-password
                            :model-value="provider.data.apiKey"
                            @input="modelStore.change(provider.id, 'data.apiKey', $event)"
                            class="w-full"
                        >
                            <template #suffix>
                                <a href="javascript:;" @click="providerTest?.show()" class="ml-2">
                                    {{ $t("检查") }}
                                </a>
                            </template>
                        </a-input-password>
                    </div>
                </div>

                <!-- API地址（非内置提供商显示，排除dashscope） -->
                <div class="mb-3" v-if="provider.id !== 'buildIn' && !provider.isBuiltIn && provider.id !== 'dashscope'">
                    <div class="mb-2 font-bold text-gray-200">{{ $t("API地址") }}</div>
                    <div>
                        <a-input
                            :model-value="provider.data.apiHost"
                            @input="modelStore.change(provider.id, 'data.apiHost', $event)"
                            class="w-full dark-input"
                        >
                        </a-input>
                    </div>
                    <div class="flex">
                        <div class="text-gray-500">
                            {{ providerUrl }}
                        </div>
                    </div>
                </div>
                <!-- OSS配置（排除dashscope，已删除） -->
                <div class="mb-3 border rounded p-3" v-if="false">
                    <div class="mb-2 font-bold flex items-center">
                        {{ $t("OSS配置") }}
                        <span class="text-gray-400 text-sm font-normal ml-2">{{ $t("（可选，用于加速语音识别）") }}</span>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <div class="mb-1 text-sm">AccessKey ID</div>
                            <a-input
                                :model-value="provider.data.ossAccessKeyId"
                                @input="modelStore.change(provider.id, 'data.ossAccessKeyId', $event)"
                                :placeholder="$t('OSS访问密钥ID')"
                            />
                        </div>
                        <div>
                            <div class="mb-1 text-sm">AccessKey Secret</div>
                            <a-input-password
                                :model-value="provider.data.ossAccessKeySecret"
                                @input="modelStore.change(provider.id, 'data.ossAccessKeySecret', $event)"
                                :placeholder="$t('OSS访问密钥Secret')"
                            />
                        </div>
                        <div>
                            <div class="mb-1 text-sm">Bucket {{ $t("名称") }}</div>
                            <a-input
                                :model-value="provider.data.ossBucket"
                                @input="modelStore.change(provider.id, 'data.ossBucket', $event)"
                                placeholder="jianhualinshi"
                            />
                        </div>
                        <div>
                            <div class="mb-1 text-sm">Region {{ $t("地域") }}</div>
                            <a-select
                                :model-value="provider.data.ossRegion || 'oss-cn-beijing'"
                                @change="modelStore.change(provider.id, 'data.ossRegion', $event)"
                            >
                                <a-option value="oss-cn-beijing">华北2（北京）</a-option>
                                <a-option value="oss-cn-hangzhou">华东1（杭州）</a-option>
                                <a-option value="oss-cn-shanghai">华东2（上海）</a-option>
                                <a-option value="oss-cn-shenzhen">华南1（深圳）</a-option>
                                <a-option value="oss-cn-chengdu">西南1（成都）</a-option>
                                <a-option value="oss-cn-hongkong">中国香港</a-option>
                            </a-select>
                        </div>
                    </div>
                    <div class="mt-2 text-xs text-gray-400">
                        {{ $t("配置OSS后，语音识别将使用快速录音识别模式（约5-10秒完成）") }}
                    </div>
                </div>
                <div class="mb-3 flex border border-[#333] rounded p-3 items-center bg-[#141414]" v-if="provider.id === 'buildIn'">
                    <div class="flex-grow text-gray-200">
                        {{ $t("能量") }}
                        <span class="font-bold">{{ ((userStore.data.lmApi?.quota || 0) / 1000).toFixed(2) }}K</span>
                    </div>
                    <div class="text-gray-400">
                        <icon-check class="text-green-500" />
                        {{ $t("内置模型无需配置可直接使用") }}
                    </div>
                    <div>
                        <a-button class="ml-2" @click="doUser">
                            {{ $t("充值") }}
                        </a-button>
                    </div>
                </div>
                <div class="mb-3">
                    <div class="mb-2 font-bold text-gray-200">{{ $t("模型") }}</div>
                    <div class="mb-2 text-sm text-gray-400" v-if="provider.id !== 'buildIn' && provider.id !== 'builtInAliyun'">
                        {{ $t("查看") }}
                        <a :href="provider?.websites.docs" target="_blank" class="text-blue-400">
                            {{ provider.title }}
                            {{ $t("文档") }}
                        </a>
                        {{ $t("和") }}
                        <a :href="provider?.websites.models" target="_blank" class="text-blue-400">
                            {{ provider.title }}
                            {{ $t("模型列表") }}
                        </a>
                        {{ $t("获取更多详情") }}
                    </div>

                    <!-- 其他提供商 - 正常显示 -->
                    <div v-for="g in providerModelGroups" :key="provider.id + g.group" class="model-group mb-2">
                        <a-collapse :default-active-key="[g.group]">
                            <a-collapse-item :header="g.group" :key="g.group">
                                <div class="-ml-6 -mr-1">
                                    <div
                                        v-for="m in g.models"
                                        class="model-card border border-[#333] mb-3 rounded-lg bg-[#141414] flex p-2 items-center"
                                    >
                                        <div class="mr-2">
                                            <a-avatar
                                                :image-url="getModelLogo(m.id)"
                                                :size="20"
                                                shape="square"
                                                style="border: 1px solid #444"
                                            />
                                        </div>
                                        <div class="flex-grow text-gray-200">
                                            {{ m.name }}
                                        </div>
                                        <div class="flex items-center">
                                            <!-- 所有提供商都可以启用/禁用模型，除了buildIn -->
                                            <a-switch
                                                v-if="provider.id !== 'buildIn'"
                                                :model-value="m.enabled"
                                                @change="modelStore.changeModel(provider.id, m.id, 'enabled', $event)"
                                                class="mr-2"
                                            ></a-switch>
                                            <!-- 只有非内置且可编辑的模型才显示编辑和删除按钮 -->
                                            <a-button
                                                @click="modelEdit?.show(m)"
                                                v-if="provider.id !== 'buildIn' && m.editable !== false"
                                                class="mr-2"
                                                title="编辑模型"
                                            >
                                                <template #icon>
                                                    <icon-settings/>
                                                </template>
                                            </a-button>
                                            <a-button
                                                @click="modelStore.modelDelete(provider.id, m.id)"
                                                v-if="provider.id !== 'buildIn' && m.editable !== false"
                                                title="删除模型"
                                            >
                                                <template #icon>
                                                    <icon-delete/>
                                                </template>
                                            </a-button>
                                        </div>
                                    </div>
                                </div>
                            </a-collapse-item>
                        </a-collapse>
                    </div>
                    <!-- 只有非内置的自定义提供商可以添加新模型 -->
                    <div class="mb-2" v-if="!provider.isBuiltIn && provider.id !== 'buildIn'">
                        <a-button @click="modelAdd?.show()">
                            <template #icon>
                                <icon-plus/>
                            </template>
                            {{ $t("添加") }}
                        </a-button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <ProviderAddDialog ref="providerAdd"/>
    <ProviderEditDialog ref="providerEdit"/>
    <ModelAddDialog ref="modelAdd" :provider="provider"/>
    <ModelEditDialog ref="modelEdit" :provider="provider"/>
    <ProviderTestDialog ref="providerTest" :provider="provider"/>
</template>

<style scoped>
.model-setting-shell {
    background: #f5f7fb;
    color: #111827;
}

.model-setting-sidebar {
    background: #f8fafc;
    border-color: #e5e7eb;
}

.model-setting-content {
    background: #ffffff;
}

.provider-nav-item {
    border-color: transparent;
    background: transparent;
    transition: all 0.2s ease;
}

.provider-nav-item:hover {
    background: #eef4ff !important;
    border-color: #c7d2fe !important;
}

.provider-nav-item-active {
    background: #e0e7ff !important;
    border-color: #a5b4fc !important;
}

.provider-header {
    border-color: #e5e7eb;
}

.builtin-provider-tip {
    background: #ecfdf3 !important;
    border-color: #86efac !important;
}

.builtin-model-add-panel {
    border: 1px solid #c7d2fe;
    background: #eef4ff;
    border-radius: 14px;
    padding: 16px;
}

.builtin-model-add-title {
    font-size: 14px;
    font-weight: 700;
    color: #1e3a8a;
    margin-bottom: 10px;
}

.builtin-model-add-grid {
    display: grid;
    grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr) auto;
    gap: 12px;
    align-items: center;
}

.builtin-model-add-tip {
    margin-top: 10px;
    font-size: 12px;
    color: #475569;
}

.model-card {
    border-color: #e5e7eb !important;
    background: #ffffff !important;
    box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
}

.model-group :deep(.arco-collapse),
.model-group :deep(.arco-collapse-item),
.model-group :deep(.arco-collapse-item-content) {
    background: transparent;
}

.model-setting-shell :deep(.arco-input-wrapper),
.model-setting-shell :deep(.arco-input-number),
.model-setting-shell :deep(.arco-select-view),
.model-setting-shell :deep(.arco-btn-secondary),
.model-setting-shell :deep(.arco-textarea-wrapper) {
    background: #ffffff;
    border-color: #d1d5db;
}

.model-setting-shell :deep(.arco-input-wrapper:hover),
.model-setting-shell :deep(.arco-select-view:hover),
.model-setting-shell :deep(.arco-input-number:hover) {
    border-color: #94a3b8;
}

.model-setting-shell :deep(.arco-input),
.model-setting-shell :deep(.arco-select-view-value),
.model-setting-shell :deep(.arco-btn),
.model-setting-shell :deep(.arco-collapse-item-header-title) {
    color: #111827;
}

.model-setting-shell :deep(.arco-collapse-item-header) {
    background: #f8fafc;
    border-radius: 10px;
}

.model-setting-shell :deep(.arco-empty-description),
.model-setting-shell .text-gray-500 {
    color: #64748b !important;
}

.model-setting-shell .text-gray-400 {
    color: #475569 !important;
}

.model-setting-shell .text-gray-300,
.model-setting-shell .text-gray-200 {
    color: #111827 !important;
}
</style>
