<template>
	<div class="model-channel-selector">
		<el-form label-width="100px" label-position="left">
			<!-- 渠道选择 -->
			<el-form-item label="选择渠道">
				<el-select
					v-model="selectedChannelId"
					placeholder="从已配置的渠道中选择"
					clearable
					style="width: 100%"
					@change="onChannelChange"
				>
					<el-option
						v-for="ch in filteredChannels"
						:key="ch.channelId"
						:label="`${ch.channelName}（${ch.count}个模型）`"
						:value="ch.channelId"
					/>
					<el-option :value="0" label="自定义配置（手动输入）" />
				</el-select>
			</el-form-item>

			<!-- 模型选择（渠道选中后显示） -->
			<el-form-item v-if="selectedChannelId && selectedChannelId !== 0" label="选择模型">
				<el-select
					v-model="selectedModelId"
					placeholder="选择模型"
					filterable
					style="width: 100%"
					@change="onModelChange"
				>
					<el-option
						v-for="m in currentModels"
						:key="m.name"
						:label="m.name"
						:value="m.name"
					>
						<span>{{ m.name }}</span>
						<el-tag
							size="small"
							:type="m.capability === 'vision' ? 'success' : m.capability === 'multimodal' ? 'warning' : 'info'"
							style="margin-left: 8px"
						>
							{{ m.capability === 'text' ? '纯文本' : m.capability === 'multimodal' ? '多模态' : m.capability === 'vision' ? '视觉' : m.capability }}
						</el-tag>
					</el-option>
				</el-select>
			</el-form-item>

			<!-- 自定义配置（channelId=0） -->
			<template v-if="selectedChannelId === 0">
				<el-form-item label="API 地址">
					<el-input v-model="customConfig.apiUrl" placeholder="https://api.openai.com/v1" />
				</el-form-item>
				<el-form-item label="API Key">
					<el-input v-model="customConfig.apiKey" placeholder="输入 API Key" show-password />
				</el-form-item>
				<el-form-item label="模型 ID">
					<el-input v-model="customConfig.modelId" placeholder="如: gpt-4o" @change="onCustomChange" />
				</el-form-item>
			</template>

			<!-- 无渠道提示 -->
			<el-alert
				v-if="loaded && channels.length === 0"
				type="info"
				show-icon
				:closable="false"
				style="margin-bottom: 12px"
			>
				<template #title>
					暂无已配置渠道，请先在
					<router-link to="/agent/model-channel" style="color: var(--el-color-primary)">模型管理</router-link>
					中添加
				</template>
			</el-alert>
		</el-form>
	</div>
</template>

<script lang="ts" setup>
defineOptions({ name: 'model-channel-selector' });

import { ref, computed, watch, onMounted } from 'vue';
import { useBase } from '/$/base';
import { config } from '/@/config';

interface ModelItem {
	name: string;
	capability: string;
}

interface ChannelInfo {
	channelId: number;
	channelName: string;
	supplier: string;
	baseUrl: string;
	apiKey: string;
	models: ModelItem[];
}

interface ModelValue {
	channelId?: number | null;
	modelId?: string;
	apiUrl?: string;
	apiKey?: string;
	contextWindow?: number | null;
}

const props = defineProps<{
	modelValue?: ModelValue;
	capabilityFilter?: string;
}>();
const emit = defineEmits<{
	(e: 'update:modelValue', val: ModelValue): void;
	(e: 'change', val: ModelValue): void;
}>();

const { user } = useBase();
const loaded = ref(false);
const channels = ref<ChannelInfo[]>([]);
const selectedChannelId = ref<number | null>(null);
const selectedModelId = ref<string>('');
const customConfig = ref({ apiUrl: '', apiKey: '', modelId: '' });

// 按能力过滤后的渠道列表
const filteredChannels = computed(() => {
	return channels.value
		.map(ch => {
			const count = props.capabilityFilter
				? ch.models.filter(m => m.capability === props.capabilityFilter).length
				: ch.models.length;
			return { ...ch, count };
		})
		.filter(ch => ch.count > 0);
});

const currentModels = computed(() => {
	const ch = channels.value.find(c => c.channelId === selectedChannelId.value);
	let models = ch?.models || [];
	if (props.capabilityFilter) {
		models = models.filter(m => m.capability === props.capabilityFilter);
	}
	return models;
});

async function loadChannels() {
	try {
		const resp = await fetch(
			`${config.baseUrl}/admin/netaclaw/model_channel/allModels`,
			{ headers: { Authorization: user.token || '' } }
		);
		const data = await resp.json();
		if (data.code === 1000 && Array.isArray(data.data)) {
			channels.value = data.data;
		}
	} catch {
		// 静默
	} finally {
		loaded.value = true;
		if (props.modelValue?.channelId) {
			selectedChannelId.value = props.modelValue.channelId;
			selectedModelId.value = props.modelValue.modelId || '';
			if (props.modelValue.channelId === 0) {
				customConfig.value = {
					apiUrl: props.modelValue.apiUrl || '',
					apiKey: props.modelValue.apiKey || '',
					modelId: props.modelValue.modelId || '',
				};
			}
		}
	}
}

function onChannelChange(channelId: number) {
	selectedModelId.value = '';
	if (channelId === 0) {
		if (props.modelValue?.channelId === 0) {
			customConfig.value = {
				apiUrl: props.modelValue.apiUrl || '',
				apiKey: props.modelValue.apiKey || '',
				modelId: props.modelValue.modelId || '',
			};
		}
		emit('update:modelValue', { channelId: 0, ...customConfig.value });
		emit('change', { channelId: 0, ...customConfig.value });
	}
}

function onModelChange(modelId: string) {
	const ch = channels.value.find(c => c.channelId === selectedChannelId.value);
	if (!ch) return;
	const val: ModelValue = {
		channelId: ch.channelId,
		modelId,
		apiUrl: ch.baseUrl,
		apiKey: ch.apiKey
	};
	emit('update:modelValue', val);
	emit('change', val);
}

function onCustomChange() {
	const val: ModelValue = {
		channelId: 0,
		modelId: customConfig.value.modelId,
		apiUrl: customConfig.value.apiUrl,
		apiKey: customConfig.value.apiKey,
	};
	emit('update:modelValue', val);
	emit('change', val);
}

watch(
	() => props.modelValue,
	val => {
		if (val?.channelId) {
			selectedChannelId.value = val.channelId;
			selectedModelId.value = val.modelId || '';
			if (val.channelId === 0) {
				customConfig.value = {
					apiUrl: val.apiUrl || '',
					apiKey: val.apiKey || '',
					modelId: val.modelId || '',
				};
			}
		} else {
			selectedChannelId.value = null;
			selectedModelId.value = '';
		}
	},
	{ immediate: true, deep: true }
);

onMounted(() => {
	loadChannels();
});
</script>

<style lang="scss" scoped>
.model-channel-selector {
	padding: 4px 0;
}
</style>
