<template>
	<div class="model-channel">
		<!-- 顶部筛选栏 -->
		<div class="model-channel__header">
			<el-button type="primary" @click="handleAdd">新增渠道</el-button>
			<el-select v-model="filters.supplier" placeholder="供应商" clearable style="width: 140px">
				<el-option v-for="s in supplierOptions" :key="s.value" :label="s.label" :value="s.value" />
			</el-select>
			<el-select v-model="filters.isAuxiliary" placeholder="类型" clearable style="width: 130px">
				<el-option :value="true" label="辅助渠道" />
				<el-option :value="false" label="主力渠道" />
			</el-select>
			<el-input
				v-model="filters.keyword"
				placeholder="搜索渠道名称"
				clearable
				style="width: 200px"
				@keyup.enter="loadData"
			>
				<template #prefix>
					<el-icon><Search /></el-icon>
				</template>
			</el-input>
			<el-button type="primary" :icon="Search" @click="loadData">查询</el-button>
			<el-button :icon="Refresh" @click="handleReset">重置</el-button>
		</div>

		<!-- 数据表格 -->
		<el-table v-loading="loading" :data="tableData" border stripe style="width: 100%" class="model-channel__table">
			<el-table-column prop="name" label="渠道名称" min-width="140" show-overflow-tooltip />
			<el-table-column prop="supplier" label="供应商" width="130">
				<template #default="{ row }">
					<el-tag :type="supplierTagType(row.supplier)" size="small">
						{{ supplierLabel(row.supplier) }}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="baseUrl" label="Base URL" min-width="240" show-overflow-tooltip />
			<el-table-column label="类型" width="100" align="center">
				<template #default="{ row }">
					<el-tag v-if="row.isAuxiliary" type="info" size="small">辅助</el-tag>
					<el-tag v-else size="small">主力</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="模型" min-width="200">
				<template #default="{ row }">
					<span v-for="(cap, idx) in modelCapSummary(row.models)" :key="idx">
						<el-tag :type="capTagType(cap.capability)" size="small" style="margin-right: 4px">
							{{ cap.label }} {{ cap.count }}
						</el-tag>
					</span>
					<span v-if="normalizeModels(row.models).length === 0" style="color: var(--el-text-color-placeholder)">未配置</span>
				</template>
			</el-table-column>
			<el-table-column label="状态" width="90" align="center">
				<template #default="{ row }">
					<el-switch
						:model-value="row.status === 1"
						@change="(val) => handleToggleStatus(row, val)"
						inline-prompt
						active-text="启用"
						inactive-text="禁用"
					/>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="200" fixed="right" align="center">
				<template #default="{ row }">
					<el-button size="small" link type="primary" @click="handleEdit(row)">编辑</el-button>
					<el-button size="small" link type="success" @click="handleTest(row)" :loading="testingId === row.id">测试</el-button>
					<el-popconfirm title="确定删除该渠道？" @confirm="handleDelete(row)">
						<template #reference>
							<el-button size="small" link type="danger">删除</el-button>
						</template>
					</el-popconfirm>
				</template>
			</el-table-column>
		</el-table>

		<!-- 分页 -->
		<div class="model-channel__footer">
			<el-pagination
				v-model:current-page="pagination.page"
				v-model:page-size="pagination.size"
				:total="pagination.total"
				:page-sizes="[20, 50, 100]"
				layout="total, sizes, prev, pager, next, jumper"
				@size-change="loadData"
				@current-change="loadData"
			/>
		</div>

		<!-- 编辑抽屉 -->
		<el-drawer v-model="drawer.visible" :title="drawer.isEdit ? '编辑渠道' : '新增渠道'" size="600px">
			<el-form ref="formRef" :model="drawer.form" :rules="formRules" label-width="100px" label-position="left">
				<el-form-item label="渠道名称" prop="name">
					<el-input v-model="drawer.form.name" placeholder="如：火山引擎、智谱AI" />
				</el-form-item>
				<el-form-item label="供应商" prop="supplier">
					<el-select v-model="drawer.form.supplier" placeholder="选择供应商" style="width: 100%">
						<el-option v-for="s in supplierOptions" :key="s.value" :label="s.label" :value="s.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="Base URL" prop="baseUrl">
					<el-input v-model="drawer.form.baseUrl" placeholder="https://ark.cn-beijing.volces.com/api/v3" />
					<div class="form-tip">API 基础地址，一般需要带 /v1 或 /api/v3</div>
				</el-form-item>
				<el-form-item label="API Key" prop="apiKey">
					<el-input v-model="drawer.form.apiKey" placeholder="输入 API Key" show-password />
				</el-form-item>
				<el-form-item label="描述">
					<el-input v-model="drawer.form.description" type="textarea" :rows="2" placeholder="渠道描述（可选）" />
				</el-form-item>
				<el-form-item label="可作为辅助模型">
					<el-switch v-model="drawer.form.isAuxiliary" />
					<div class="form-tip">勾选后，此渠道可用于 Agent 的上下文压缩等辅助任务。</div>
				</el-form-item>
			</el-form>

			<!-- 模型列表表格 -->
			<div class="model-list-section">
				<div class="model-list-header">
					<span class="model-list-title">模型列表</span>
					<div>
						<el-button size="small" @click="addModelRow">+ 添加</el-button>
						<el-button size="small" type="primary" @click="batchImport.visible = true">批量导入</el-button>
					</div>
				</div>
				<el-table :data="drawer.form.modelRows" border size="small" v-if="drawer.form.modelRows.length > 0">
					<el-table-column label="模型名称" min-width="200">
						<template #default="{ row }">
							<el-input v-model="row.name" size="small" placeholder="模型ID" />
						</template>
					</el-table-column>
					<el-table-column label="能力类型" width="140">
						<template #default="{ row }">
							<el-select v-model="row.capability" size="small" style="width: 100%">
								<el-option v-for="c in capabilityOptions" :key="c.value" :label="c.label" :value="c.value" />
							</el-select>
						</template>
					</el-table-column>
					<el-table-column label="支持思考" width="90" align="center">
						<template #default="{ row }">
							<el-switch v-model="row.supportThinking" size="small" />
						</template>
					</el-table-column>
					<el-table-column label="可调级别" width="90" align="center">
						<template #default="{ row }">
							<el-switch v-model="row.supportThinkingLevel" size="small" :disabled="!row.supportThinking" />
						</template>
					</el-table-column>
					<el-table-column label="" width="60" align="center">
						<template #default="{ $index }">
							<el-button size="small" link type="danger" @click="drawer.form.modelRows.splice($index, 1)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<el-empty v-else description="暂无模型，点击添加或批量导入" :image-size="40" />
			</div>

			<template #footer>
				<el-button @click="drawer.visible = false">取消</el-button>
				<el-button type="primary" @click="handleSubmit" :loading="submitting">保存</el-button>
			</template>
		</el-drawer>

		<!-- 批量导入弹窗 -->
		<el-dialog v-model="batchImport.visible" title="批量导入模型" width="480px">
			<el-form label-width="100px">
				<el-form-item label="默认能力类型">
					<el-select v-model="batchImport.capability" style="width: 100%">
						<el-option v-for="c in capabilityOptions" :key="c.value" :label="c.label" :value="c.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="模型名称">
					<el-input
						v-model="batchImport.text"
						type="textarea"
						:rows="6"
						placeholder="逗号或换行分隔，如：&#10;doubao-pro, doubao-lite&#10;doubao-seed"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="batchImport.visible = false">取消</el-button>
				<el-button type="primary" @click="handleBatchImport">导入</el-button>
			</template>
		</el-dialog>
	</div>
</template>

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

import { ref, reactive, onMounted } from 'vue';
import { Search, Refresh } from '@element-plus/icons-vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { useBase } from '/$/base';
import { config } from '/@/config';

const { user } = useBase();

const loading = ref(false);
const submitting = ref(false);
const testingId = ref<number | null>(null);
const tableData = ref<any[]>([]);
const formRef = ref<FormInstance>();

const supplierOptions = ref<{ value: string; label: string; tagType?: string }[]>([]);
const capabilityOptions = ref<{ value: string; label: string }[]>([
	{ value: 'text', label: '纯文本' },
	{ value: 'multimodal', label: '多模态' },
	{ value: 'vision', label: '视觉' },
	{ value: 'image_aigc', label: '文生图&图生图' }
]);

function supplierLabel(val: string) {
	return supplierOptions.value.find(s => s.value === val)?.label || val;
}

function supplierTagType(val: string): 'primary' | 'success' | 'warning' | 'danger' | 'info' {
	const tagType = supplierOptions.value.find(s => s.value === val)?.tagType;
	return tagType === 'success' || tagType === 'warning' || tagType === 'danger' || tagType === 'primary'
		? tagType
		: 'info';
}

async function loadOptions() {
	try {
		const data = await apiGet('/admin/netaclaw/model_channel/options');
		if (data.code === 1000 && data.data) {
			if (Array.isArray(data.data.suppliers)) {
				supplierOptions.value = data.data.suppliers;
			}
			if (Array.isArray(data.data.capabilities)) {
				capabilityOptions.value = data.data.capabilities;
			}
		}
	} catch {
		// 降级使用默认列表
	}
}

function capLabel(val: string) {
	return capabilityOptions.value.find(c => c.value === val)?.label || val;
}

function capTagType(val: string): 'primary' | 'success' | 'warning' | 'danger' | 'info' {
	const map: Record<string, 'primary' | 'success' | 'warning' | 'danger' | 'info'> = {
		text: 'info',
		multimodal: 'warning',
		vision: 'success'
	};
	return map[val] || 'info';
}

const filters = reactive({ supplier: '' as string, keyword: '', isAuxiliary: undefined as boolean | undefined });
const pagination = reactive({ page: 1, size: 20, total: 0 });

interface ModelRow { name: string; capability: string; supportThinking: boolean; supportThinkingLevel: boolean }

const drawer = reactive({
	visible: false,
	isEdit: false,
	form: {
		id: null as number | null,
		name: '',
		supplier: '',
		baseUrl: '',
		apiKey: '',
		modelRows: [] as ModelRow[],
		description: '',
		isAuxiliary: false
	}
});

const batchImport = reactive({
	visible: false,
	capability: 'text',
	text: ''
});

const formRules: FormRules = {
	name: [{ required: true, message: '请输入渠道名称', trigger: 'blur' }],
	supplier: [{ required: true, message: '请选择供应商', trigger: 'change' }],
	baseUrl: [{ required: true, message: '请输入 Base URL', trigger: 'blur' }]
};

async function apiGet(url: string) {
	const resp = await fetch(`${config.baseUrl}${url}`, {
		headers: { Authorization: user.token || '' }
	});
	return resp.json();
}

async function apiPost(url: string, body: any) {
	const resp = await fetch(`${config.baseUrl}${url}`, {
		method: 'POST',
		headers: { 'Content-Type': 'application/json', Authorization: user.token || '' },
		body: JSON.stringify(body)
	});
	return resp.json();
}

function normalizeModels(models: any): ModelRow[] {
	let arr = models;
	if (typeof arr === 'string') {
		try { arr = JSON.parse(arr); } catch { return []; }
	}
	if (!Array.isArray(arr)) return [];
	return arr.map((m: any) => {
		if (typeof m === 'string') return { name: m, capability: 'text', supportThinking: false, supportThinkingLevel: false };
		return { name: m.name || '', capability: m.capability || 'text', supportThinking: !!m.supportThinking, supportThinkingLevel: !!m.supportThinkingLevel };
	});
}

function modelCapSummary(models: any): { capability: string; label: string; count: number }[] {
	const rows = normalizeModels(models);
	const map: Record<string, number> = {};
	for (const r of rows) {
		map[r.capability] = (map[r.capability] || 0) + 1;
	}
	return Object.entries(map).map(([cap, count]) => ({
		capability: cap,
		label: capLabel(cap),
		count
	}));
}

function addModelRow() {
	drawer.form.modelRows.push({ name: '', capability: 'text', supportThinking: false, supportThinkingLevel: false });
}

function handleBatchImport() {
	const names = batchImport.text
		.split(/[,\n，]/)
		.map(s => s.trim())
		.filter(Boolean);
	if (names.length === 0) {
		ElMessage.warning('请输入模型名称');
		return;
	}
	for (const name of names) {
		drawer.form.modelRows.push({
			name,
			capability: batchImport.capability,
			supportThinking: false,
			supportThinkingLevel: false
		});
	}
	batchImport.visible = false;
	batchImport.text = '';
	ElMessage.success(`已导入 ${names.length} 个模型`);
}

async function loadData() {
	loading.value = true;
	try {
		const body: any = {
			page: pagination.page,
			size: pagination.size
		};
		if (filters.keyword) body.keyWord = filters.keyword;
		if (filters.supplier) body.supplier = filters.supplier;
		if (filters.isAuxiliary !== undefined) body.isAuxiliary = filters.isAuxiliary;

		const data = await apiPost('/admin/netaclaw/model_channel/page', body);
		if (data.code === 1000 && data.data) {
			tableData.value = data.data.list || [];
			pagination.total = data.data.pagination?.total || 0;
		}
	} catch {
		ElMessage.error('加载数据失败');
	} finally {
		loading.value = false;
	}
}

function handleReset() {
	filters.supplier = '';
	filters.keyword = '';
	filters.isAuxiliary = undefined;
	pagination.page = 1;
	loadData();
}

function handleAdd() {
	drawer.isEdit = false;
	drawer.form = { id: null, name: '', supplier: '', baseUrl: '', apiKey: '', modelRows: [], description: '', isAuxiliary: false };
	drawer.visible = true;
}

function handleEdit(row: any) {
	drawer.isEdit = true;
	drawer.form = {
		id: row.id,
		name: row.name || '',
		supplier: row.supplier || '',
		baseUrl: row.baseUrl || '',
		apiKey: row.apiKey || '',
		modelRows: normalizeModels(row.models),
		description: row.description || '',
		isAuxiliary: !!row.isAuxiliary
	};
	drawer.visible = true;
}

async function handleSubmit() {
	const valid = await formRef.value?.validate().catch(() => false);
	if (!valid) return;

	const models = drawer.form.modelRows.filter(r => r.name.trim());
	if (models.length === 0) {
		ElMessage.warning('请添加至少一个模型');
		return;
	}

	submitting.value = true;
	try {
		const body: any = {
			name: drawer.form.name,
			supplier: drawer.form.supplier,
			baseUrl: drawer.form.baseUrl,
			apiKey: drawer.form.apiKey,
			models: models.map(r => ({ name: r.name.trim(), capability: r.capability, supportThinking: r.supportThinking, supportThinkingLevel: r.supportThinkingLevel })),
			description: drawer.form.description,
			isAuxiliary: drawer.form.isAuxiliary
		};
		if (drawer.isEdit) body.id = drawer.form.id;

		const url = drawer.isEdit
			? '/admin/netaclaw/model_channel/update'
			: '/admin/netaclaw/model_channel/add';
		const data = await apiPost(url, body);
		if (data.code === 1000) {
			ElMessage.success(drawer.isEdit ? '更新成功' : '新增成功');
			drawer.visible = false;
			loadData();
		} else {
			ElMessage.error(data.message || '操作失败');
		}
	} catch {
		ElMessage.error('操作失败');
	} finally {
		submitting.value = false;
	}
}

async function handleDelete(row: any) {
	try {
		const data = await apiPost('/admin/netaclaw/model_channel/delete', { ids: [row.id] });
		if (data.code === 1000) {
			ElMessage.success('删除成功');
			loadData();
		} else {
			ElMessage.error(data.message || '删除失败');
		}
	} catch {
		ElMessage.error('删除失败');
	}
}

async function handleToggleStatus(row: any, val: string | number | boolean) {
	const enabled = val === true;
	try {
		const data = await apiPost('/admin/netaclaw/model_channel/update', {
			id: row.id,
			status: enabled ? 1 : 0
		});
		if (data.code === 1000) {
			row.status = enabled ? 1 : 0;
			ElMessage.success(enabled ? '已启用' : '已禁用');
		}
	} catch {
		ElMessage.error('操作失败');
	}
}

async function handleTest(row: any) {
	testingId.value = row.id;
	try {
		const data = await apiPost('/admin/netaclaw/model_channel/testConnection', { id: row.id });
		if (data.code === 1000 && data.data?.success) {
			ElMessage.success(data.data.message || '连接成功');
		} else {
			ElMessage.error(data.data?.message || data.message || '连接失败');
		}
	} catch {
		ElMessage.error('测试请求失败');
	} finally {
		testingId.value = null;
	}
}

onMounted(() => {
	loadOptions();
	loadData();
});
</script>

<style lang="scss" scoped>
.model-channel {
	height: 100%;
	display: flex;
	flex-direction: column;
	padding: 15px;
	box-sizing: border-box;

	&__header {
		display: flex;
		align-items: center;
		gap: 10px;
		padding: 15px;
		background-color: var(--el-bg-color);
		border-radius: 6px;
		margin-bottom: 12px;
		flex-wrap: wrap;
	}

	&__table {
		flex: 1;
	}

	&__footer {
		display: flex;
		justify-content: flex-end;
		padding: 12px 0;
	}
}

.form-tip {
	font-size: 12px;
	color: var(--el-text-color-secondary);
	margin-top: 4px;
	line-height: 1.5;
}

.model-list-section {
	padding: 0 20px;
}

.model-list-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10px;
}

.model-list-title {
	font-size: 14px;
	font-weight: 600;
	color: var(--el-text-color-primary);
}
</style>
