<template>
	<div class="cid-datasource-container">
		<el-card shadow="hover">
			<div class="system-user-search mb15">
				<el-form :model="tableData.param" ref="queryRef" :inline="true" label-width="68px">
					<el-form-item label="关键字" prop="keyword">
						<el-input
							v-model="tableData.param.keyword"
							placeholder="请输入平台名称"
							clearable
							size="default"
							style="width: 240px"
							@keyup.enter.native="getList"
						/>
					</el-form-item>
					<el-form-item label="状态" prop="status">
						<el-select v-model="tableData.param.status" placeholder="平台状态" clearable size="default" style="width: 160px">
							<el-option label="启用" value="ACTIVE" />
							<el-option label="禁用" value="INACTIVE" />
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button size="default" type="primary" @click="getList">
							<el-icon><ele-Search /></el-icon>
							查询
						</el-button>
						<el-button size="default" @click="resetQuery(queryRef)">
							<el-icon><ele-Refresh /></el-icon>
							重置
						</el-button>
						<el-button size="default" type="success" @click="onOpenAdd">
							<el-icon><ele-FolderAdd /></el-icon>
							新增平台
						</el-button>
						<el-button size="default" type="danger" @click="onRowDel(null)">
							<el-icon><ele-Delete /></el-icon>
							删除
						</el-button>
					</el-form-item>
				</el-form>
			</div>
			<el-table :data="tableData.data" style="width: 100%" v-loading="tableData.loading" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="platformName" label="平台名称" show-overflow-tooltip />
				<el-table-column prop="platformCode" label="平台编码" show-overflow-tooltip />
				<el-table-column prop="apiBaseUrl" label="接口基础URL" show-overflow-tooltip />
				<el-table-column prop="authTypeName" label="认证方式" width="130" show-overflow-tooltip />
				<el-table-column prop="rateLimitPerMinute" label="限频(次/分)" width="110" align="center" />
				<el-table-column prop="statusName" label="状态" width="90" align="center">
					<template #default="scope">
						<el-tag :type="scope.row.status === 'ACTIVE' ? 'success' : 'danger'" size="small">
							{{ scope.row.status === 'ACTIVE' ? '启用' : '禁用' }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="description" label="描述" show-overflow-tooltip />
				<el-table-column label="创建时间" width="160">
					<template #default="scope">
						{{ scope.row.createdAt ? formatTime(scope.row.createdAt) : '' }}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="150" fixed="right">
					<template #default="scope">
						<el-button size="small" text type="primary" @click="onOpenEdit(scope.row)">修改</el-button>
						<el-button size="small" text type="danger" @click="onRowDel(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<pagination
				v-show="tableData.total > 0"
				:total="tableData.total"
				v-model:page="tableData.param.pageNum"
				v-model:limit="tableData.param.pageSize"
				@pagination="getList"
			/>
		</el-card>

		<el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" :close-on-click-modal="false">
			<el-form ref="formRef" :model="form" :rules="rules" label-width="110px" v-loading="dialog.loading">
				<el-form-item label="平台名称" prop="platformName">
					<el-input v-model="form.platformName" placeholder="请输入平台名称" />
				</el-form-item>
				<el-form-item label="平台编码" prop="platformCode">
					<el-input v-model="form.platformCode" placeholder="请输入平台编码，如 ALIYUN_API" />
				</el-form-item>
				<el-form-item label="接口基础URL" prop="apiBaseUrl">
					<el-input v-model="form.apiBaseUrl" placeholder="请输入接口基础URL" />
				</el-form-item>
				<el-form-item label="认证方式" prop="authType">
					<el-select v-model="form.authType" placeholder="请选择认证方式" style="width: 100%">
						<el-option label="API Key认证" value="API_KEY" />
						<el-option label="OAuth2" value="OAUTH2" />
						<el-option label="Bearer Token" value="BEARER_TOKEN" />
						<el-option label="无认证" value="NONE" />
					</el-select>
				</el-form-item>
				<el-form-item label="API Key" prop="apiKey" v-if="form.authType === 'API_KEY'">
					<el-input v-model="form.apiKey" placeholder="请输入 API Key" show-password />
				</el-form-item>
				<el-form-item label="Token" prop="token" v-if="form.authType === 'BEARER_TOKEN'">
					<el-input v-model="form.token" placeholder="请输入 Bearer Token" show-password />
				</el-form-item>
				<el-form-item label="Client ID" prop="clientId" v-if="form.authType === 'OAUTH2'">
					<el-input v-model="form.clientId" placeholder="请输入 Client ID" />
				</el-form-item>
				<el-form-item label="Client Secret" prop="clientSecret" v-if="form.authType === 'OAUTH2'">
					<el-input v-model="form.clientSecret" placeholder="请输入 Client Secret" show-password />
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-select v-model="form.status" style="width: 100%">
						<el-option label="启用" value="ACTIVE" />
						<el-option label="禁用" value="INACTIVE" />
					</el-select>
				</el-form-item>
				<el-row :gutter="16">
					<el-col :span="12">
						<el-form-item label="限频(次/分)" prop="rateLimitPerMinute">
							<el-input-number v-model="form.rateLimitPerMinute" :min="0" style="width: 100%" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="限频(次/时)" prop="rateLimitPerHour">
							<el-input-number v-model="form.rateLimitPerHour" :min="0" style="width: 100%" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="并发限制" prop="concurrencyLimit">
							<el-input-number v-model="form.concurrencyLimit" :min="0" style="width: 100%" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="超时(ms)" prop="requestTimeoutMs">
							<el-input-number v-model="form.requestTimeoutMs" :min="0" style="width: 100%" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="最大重试次数" prop="maxRetries">
							<el-input-number v-model="form.maxRetries" :min="0" style="width: 100%" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="重试延迟(ms)" prop="retryDelayMs">
							<el-input-number v-model="form.retryDelayMs" :min="0" style="width: 100%" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="描述" prop="description">
					<el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入描述" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="dialog.visible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit" :loading="dialog.saving">确定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
export default { name: 'cidDatasource' };
</script>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { listDatasourcePlatforms, createDatasourcePlatform, updateDatasourcePlatform, deleteDatasourcePlatform, getDatasourcePlatform } from '/@/api/cid/datasource';

const queryRef = ref<FormInstance>();
const formRef = ref<FormInstance>();
const ids = ref<string[]>([]);

const tableData = reactive({
	data: [] as any[],
	total: 0,
	loading: false,
	param: {
		pageNum: 1,
		pageSize: 10,
		keyword: '',
		status: '',
	},
});

const dialog = reactive({
	visible: false,
	title: '',
	saving: false,
	isEdit: false,
	loading: false,
});

const form = reactive({
	id: '',
	platformName: '',
	platformCode: '',
	apiBaseUrl: '',
	authType: 'API_KEY',
	status: 'ACTIVE',
	description: '',
	token: '',
	apiKey: '',
	clientId: '',
	clientSecret: '',
	rateLimitPerMinute: 200,
	rateLimitPerHour: 10000,
	concurrencyLimit: 50,
	requestTimeoutMs: 15000,
	maxRetries: 3,
	retryDelayMs: 300,
});

const rules = {
	platformName: [{ required: true, message: '请输入平台名称', trigger: 'blur' }],
	platformCode: [{ required: true, message: '请输入平台编码', trigger: 'blur' }],
	apiBaseUrl: [{ required: true, message: '请输入接口基础URL', trigger: 'blur' }],
	authType: [{ required: true, message: '请选择认证方式', trigger: 'change' }],
};

const formatTime = (ts: number) => {
	if (!ts) return '';
	const d = new Date(ts * 1000);
	return d.toLocaleString('zh-CN', { hour12: false });
};

const getList = async () => {
	tableData.loading = true;
	try {
		const res = await listDatasourcePlatforms({
			pageNum: tableData.param.pageNum,
			pageSize: tableData.param.pageSize,
			...(tableData.param.keyword ? { keyword: tableData.param.keyword } : {}),
			...(tableData.param.status ? { status: tableData.param.status } : {}),
		});
		tableData.data = res.data?.list || [];
		tableData.total = res.data?.total || 0;
	} catch (_e) {
		ElMessage.error('获取平台列表失败');
	} finally {
		tableData.loading = false;
	}
};

const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	getList();
};

const handleSelectionChange = (selection: any[]) => {
	ids.value = selection.map((item) => item.id);
};

const resetForm = () => {
	form.id = '';
	form.platformName = '';
	form.platformCode = '';
	form.apiBaseUrl = '';
	form.authType = 'API_KEY';
	form.status = 'ACTIVE';
	form.description = '';
	form.token = '';
	form.apiKey = '';
	form.clientId = '';
	form.clientSecret = '';
	form.rateLimitPerMinute = 200;
	form.rateLimitPerHour = 10000;
	form.concurrencyLimit = 50;
	form.requestTimeoutMs = 15000;
	form.maxRetries = 3;
	form.retryDelayMs = 300;
};

const onOpenAdd = () => {
	resetForm();
	dialog.title = '新增平台';
	dialog.isEdit = false;
	dialog.visible = true;
};

const onOpenEdit = async (row: any) => {
	resetForm();
	dialog.title = '修改平台';
	dialog.isEdit = true;
	dialog.visible = true;
	dialog.loading = true;
	try {
		const res = await getDatasourcePlatform(row.id);
		const detail = res.data || {};
		form.id = detail.id || row.id;
		form.platformName = detail.platformName || '';
		form.platformCode = detail.platformCode || '';
		form.apiBaseUrl = detail.apiBaseUrl || '';
		form.authType = detail.authType || 'API_KEY';
		form.status = detail.status || 'ACTIVE';
		form.description = detail.description || '';
		form.token = detail.token || '';
		form.apiKey = detail.apiKey || '';
		form.clientId = detail.clientId || '';
		form.clientSecret = detail.clientSecret || '';
		form.rateLimitPerMinute = detail.rateLimitPerMinute ?? 200;
		form.rateLimitPerHour = detail.rateLimitPerHour ?? 10000;
		form.concurrencyLimit = detail.concurrencyLimit ?? 50;
		form.requestTimeoutMs = detail.requestTimeoutMs ?? 15000;
		form.maxRetries = detail.maxRetries ?? 3;
		form.retryDelayMs = detail.retryDelayMs ?? 300;
	} catch (_e) {
		dialog.visible = false;
		ElMessage.error('获取平台详情失败');
	} finally {
		dialog.loading = false;
	}
};

const onSubmit = () => {
	if (!formRef.value) return;
	formRef.value.validate(async (valid) => {
		if (!valid) return;
		dialog.saving = true;
		try {
			if (dialog.isEdit) {
				await updateDatasourcePlatform({ ...form });
				ElMessage.success('修改成功');
			} else {
				const { id: _id, ...createParams } = form;
				await createDatasourcePlatform(createParams);
				ElMessage.success('创建成功');
			}
			dialog.visible = false;
			getList();
		} catch (_e) {
			ElMessage.error(dialog.isEdit ? '修改失败' : '创建失败');
		} finally {
			dialog.saving = false;
		}
	});
};

const onRowDel = (row: any) => {
	const delIds = row ? [row.id] : ids.value;
	if (delIds.length === 0) {
		ElMessage.error('请选择要删除的数据');
		return;
	}
	const msg = row ? `确定要删除平台「${row.platformName}」吗？` : `确定要删除选中的 ${delIds.length} 个平台吗？`;
	ElMessageBox.confirm(msg, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				for (const id of delIds) {
					await deleteDatasourcePlatform(id);
				}
				ElMessage.success('删除成功');
				getList();
			} catch (_e) {
				ElMessage.error('删除失败');
			}
		})
		.catch(() => {});
};

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