<template>
	<cl-crud ref="Crud">
		<cl-row>
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<!-- 新增按钮 -->
			<cl-add-btn />
			<!-- 批量删除 -->
			<cl-multi-delete-btn />
			<cl-flex1 />
			<!-- 关键字搜索 -->
			<cl-search-key placeholder="搜索接口地址" />
		</cl-row>

		<cl-row>
			<!-- 数据表格 -->
			<cl-table ref="Table" />
		</cl-row>

		<cl-row>
			<cl-flex1 />
			<!-- 分页 -->
			<cl-pagination />
		</cl-row>

		<!-- 新增、编辑 -->
		<cl-upsert ref="Upsert" />
	</cl-crud>
</template>

<script lang="ts" setup>
defineOptions({
	name: 'aiconfig-api-config'
});

import { useCrud, useTable, useUpsert } from '@cool-vue/crud';
import { useCool } from '/@/cool';
import { ElMessage } from 'element-plus';
import { reactive } from 'vue';

const { service } = useCool();

// 模型列表
const modelList = reactive<any[]>([]);

// 获取模型列表
async function loadModels() {
	try {
		const res = await service.aiconfig.model.list();
		modelList.length = 0;
		modelList.push(...res.map((item: any) => ({ label: item.modelName, value: item.id })));
	} catch (err) {
		console.error('加载模型列表失败:', err);
	}
}

// 测试接口连通性
async function testConnection(row: any) {
	try {
		ElMessage.info('正在测试接口连通性...');
		const res = await service.aiconfig.apiConfig.testConnection({ id: row.id });
		if (res) {
			ElMessage.success('接口连接测试成功');
		} else {
			ElMessage.error('接口连接测试失败，请检查配置');
		}
	} catch (err: any) {
		ElMessage.error(err.message || '接口连接测试失败');
	}
}

// cl-table 表格配置
const Table = useTable({
	columns: [
		{
			type: 'selection',
			width: 60
		},
		{
			label: '关联模型',
			prop: 'modelId',
			minWidth: 120,
			dict: modelList
		},
		{
			label: '接口地址',
			prop: 'apiUrl',
			minWidth: 250,
			showOverflowTooltip: true
		},
		{
			label: '请求方法',
			prop: 'requestMethod',
			width: 100
		},
		{
			label: 'API密钥名称',
			prop: 'apiKeyName',
			minWidth: 150
		},
		{
			label: '超时时间(秒)',
			prop: 'timeout',
			width: 120
		},
		{
			label: '状态',
			prop: 'status',
			width: 100,
			dict: [
				{
					label: '禁用',
					value: 0,
					type: 'danger'
				},
				{
					label: '启用',
					value: 1,
					type: 'success'
				}
			]
		},
		{
			label: '创建时间',
			prop: 'createTime',
			minWidth: 160,
			sortable: 'custom'
		},
		{
			type: 'op',
			width: 250,
			buttons: [
				{
					label: '测试连接',
					type: 'warning',
					onClick({ scope }) {
						testConnection(scope.row);
					}
				},
				'edit',
				'delete'
			]
		}
	]
});

// cl-upsert 新增、编辑配置
const Upsert = useUpsert({
	dialog: {
		width: '800px'
	},
	props: {
		labelWidth: '140px'
	},
	items: [
		{
			label: '关联模型',
			prop: 'modelId',
			required: true,
			component: {
				name: 'el-select',
				options: modelList,
				props: {
					placeholder: '请选择关联的AI模型'
				}
			}
		},
		{
			label: '接口地址',
			prop: 'apiUrl',
			required: true,
			component: {
				name: 'el-input',
				props: {
					placeholder: '请输入完整的API接口地址，如：https://api.openai.com/v1/chat/completions'
				}
			}
		},
		{
			label: '请求方法',
			prop: 'requestMethod',
			value: 'POST',
			component: {
				name: 'el-select',
				options: [
					{ label: 'GET', value: 'GET' },
					{ label: 'POST', value: 'POST' },
					{ label: 'PUT', value: 'PUT' }
				],
				props: {
					placeholder: '请选择HTTP请求方法'
				}
			}
		},
		{
			label: 'API密钥',
			prop: 'apiKey',
			component: {
				name: 'el-input',
				props: {
					type: 'textarea',
					rows: 2,
					placeholder: '请输入API密钥（如有）'
				}
			}
		},
		{
			label: 'API密钥名称',
			prop: 'apiKeyName',
			component: {
				name: 'el-input',
				props: {
					placeholder: '请输入密钥在请求头中的名称，如：Authorization、api-key'
				}
			}
		},
		{
			label: '请求头配置',
			prop: 'requestHeaders',
			component: {
				name: 'el-input',
				props: {
					type: 'textarea',
					rows: 3,
					placeholder: '请输入JSON格式的请求头配置，如：{"Content-Type":"application/json"}'
				}
			}
		},
		{
			label: '请求体格式',
			prop: 'requestBodyFormat',
			component: {
				name: 'el-input',
				props: {
					type: 'textarea',
					rows: 4,
					placeholder: '请输入JSON格式的请求体模板'
				}
			}
		},
		{
			label: '响应解析路径',
			prop: 'responseDataPath',
			component: {
				name: 'el-input',
				props: {
					placeholder: '响应数据的JSONPath，如：$.data.content'
				}
			}
		},
		{
			label: '超时时间(秒)',
			prop: 'timeout',
			value: 60,
			component: {
				name: 'el-input-number',
				props: {
					min: 1,
					max: 300,
					step: 10
				}
			}
		},
		{
			label: '状态',
			prop: 'status',
			value: 1,
			component: {
				name: 'el-radio-group',
				options: [
					{
						label: '禁用',
						value: 0
					},
					{
						label: '启用',
						value: 1
					}
				]
			}
		},
		{
			label: '备注',
			prop: 'remark',
			component: {
				name: 'el-input',
				props: {
					type: 'textarea',
					rows: 2,
					placeholder: '请输入备注信息'
				}
			}
		}
	],
	onOpen() {
		// 打开弹窗时加载模型列表
		loadModels();
	}
});

// cl-crud 配置
const Crud = useCrud(
	{
		service: service.aiconfig.apiConfig
	},
	app => {
		app.refresh();
	}
);

// 初始化加载模型列表
loadModels();
</script>
