<template>
	<div class="panel">
		<div class="toolbar">
			<div class="toolbar-left">
				<el-input v-model="keyword" clearable placeholder="搜索提供者名称" class="search-input" @keyup.enter="loadList(1)">
					<template #prefix>
						<el-icon>
							<Search />
						</el-icon>
					</template>
				</el-input>
				<el-select v-model="provider" clearable placeholder="服务商" style="width: 180px" @change="loadList(1)">
					<el-option v-for="item in engineOptions" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
				<el-button @click="loadList(1)">查询</el-button>
				<el-button @click="handleReset">重置</el-button>
			</div>
			<div class="toolbar-right">
				<el-button type="primary" @click="openCreate">
					<el-icon>
						<Plus />
					</el-icon>
					新建网络搜索
				</el-button>
			</div>
		</div>

		<div v-loading="loading" class="grid">
			<el-empty v-if="!list.length && !loading" class="empty" description="暂无网络搜索配置" />
			<div v-for="row in list" :key="row.id" class="card">
				<div class="card-head">
					<div class="flex items-center justify-between">
						<div class="title">{{ row.name || '未命名网络搜索' }}</div>
						<div class="actions" @click.stop>
							<el-dropdown>
								<span class="actions-trigger">
									<el-icon>
										<MoreFilled />
									</el-icon>
								</span>
								<template #dropdown>
									<el-dropdown-menu>
										<el-dropdown-item @click="openEditById(row.id)">编辑</el-dropdown-item>
										<el-dropdown-item @click="removeItem(row.id)" divided>
											<span class="danger-text">删除</span>
										</el-dropdown-item>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
						</div>
					</div>

					<div class="subtitle">{{ getEngineName(row.provider) }}</div>
					<div class="badge-row">
						<span class="badge">{{ getEngineName(row.provider) }}</span>
						<span class="badge subtle">{{ row.is_default ? '默认配置' : '普通配置' }}</span>
					</div>
				</div>

				<div class="card-footer">
					<el-button link type="primary" @click="checkItem(row.id)">连接测试</el-button>
				</div>
			</div>
		</div>

		<div v-if="pagination.totalCount > 0" class="pagination">
			<el-pagination v-model:current-page="pagination.pageIndex" v-model:page-size="pagination.pageSize" background
				layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]" :total="pagination.totalCount"
				@current-change="handlePageChange" @size-change="handleSizeChange" />
		</div>

		<el-drawer v-model="drawerVisible" :title="currentId ? '编辑网络搜索' : '新建网络搜索'" direction="rtl" size="700px">
			<el-form ref="formRef" :model="form" :rules="rules" label-position="top">
				<el-form-item label="服务商" prop="provider">
					<el-select v-model="form.provider" style="width: 100%">
						<el-option v-for="item in engineOptions" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="名称" prop="name">
					<el-input v-model="form.name" />
				</el-form-item>
				<el-form-item label="描述" prop="description">
					<el-input v-model="form.description" type="textarea" :rows="2" />
				</el-form-item>
				<el-form-item label="API Key" prop="parameters.api_key">
					<el-input v-model="form.parameters.api_key" type="password" show-password />
				</el-form-item>
				<div class="grid-2">
					<el-form-item label="代理地址" prop="parameters.proxy_url">
						<el-input v-model="form.parameters.proxy_url" />
					</el-form-item>
					<el-form-item label="引擎 ID" prop="parameters.engine_id">
						<el-input v-model="form.parameters.engine_id" />
					</el-form-item>
				</div>
				<el-form-item label="设为默认" prop="is_default">
					<el-switch v-model="form.is_default" />
				</el-form-item>
				<el-form-item>
					<div class="check-box">
						<el-button :loading="checkLoading" @click="checkWithParameters">测试连接</el-button>
						<el-alert v-if="checkMessage" :title="checkMessage" :type="checkSuccess ? 'success' : 'error'"
							:closable="false" show-icon />
					</div>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="drawer-footer">
					<el-button @click="drawerVisible = false">取消</el-button>
					<el-button type="primary" :loading="submitLoading" @click="handleSubmit">保存</el-button>
				</div>
			</template>
		</el-drawer>
	</div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, MoreFilled } from '@element-plus/icons-vue'
import { resource } from '@repo/api-service'

type EngineResponse = Awaited<ReturnType<typeof resource.postWebSearchEngines>>
type EngineItem = NonNullable<EngineResponse['result']>[number]

const keyword = ref('')
const provider = ref('')
const loading = ref(false)
const submitLoading = ref(false)
const checkLoading = ref(false)
const drawerVisible = ref(false)
const currentId = ref('')
const checkMessage = ref('')
const checkSuccess = ref(false)
const formRef = ref()

const pagination = reactive({
	pageIndex: 1,
	pageSize: 20,
	totalCount: 0
})

const list = ref<any[]>([])
const engineOptions = ref<EngineItem[]>([])

const form = reactive({
	provider: '',
	name: '',
	description: '',
	is_default: false,
	parameters: {
		proxy_url: '',
		api_key: '',
		engine_id: ''
	}
})

const rules = {
	provider: [{ required: true, message: '请选择服务商', trigger: 'change' }],
	name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
}

function resetForm() {
	currentId.value = ''
	checkMessage.value = ''
	checkSuccess.value = false
	form.provider = ''
	form.name = ''
	form.description = ''
	form.is_default = false
	form.parameters.proxy_url = ''
	form.parameters.api_key = ''
	form.parameters.engine_id = ''
}

function getEngineName(id?: string) {
	return engineOptions.value.find((item) => item.id === id)?.name || id || '未设置服务商'
}

async function loadEngines() {
	const res = await resource.postWebSearchEngines({})
	if (res.isSuccess) {
		engineOptions.value = res.result || []
	}
}

async function loadList(pageIndex = 1) {
	loading.value = true
	try {
		const res = await resource.postWebSearchPageList({
			keyword: keyword.value,
			provider: provider.value,
			pageIndex,
			pageSize: pagination.pageSize
		})
		if (res.isSuccess && res.result) {
			list.value = (res.result.model || []) as any[]
			pagination.pageIndex = res.result.currentPage || pageIndex
			pagination.pageSize = res.result.pageSize || pagination.pageSize
			pagination.totalCount = res.result.totalCount || 0
		}
	} finally {
		loading.value = false
	}
}

function handlePageChange(page: number) {
	pagination.pageIndex = page
	loadList(page)
}

function handleSizeChange(size: number) {
	pagination.pageSize = size
	loadList(1)
}

function handleReset() {
	keyword.value = ''
	provider.value = ''
	loadList(1)
}

function openCreate() {
	resetForm()
	drawerVisible.value = true
}

async function openEditById(id: string) {
	const res = await resource.postWebSearchInfo({ id })
	if (!res.isSuccess || !res.result) {
		ElMessage.error('获取详情失败')
		return
	}
	resetForm()
	currentId.value = id
	form.provider = res.result.provider || ''
	form.name = res.result.name || ''
	form.description = res.result.description || ''
	form.is_default = !!res.result.is_default
	form.parameters.api_key = res.result.parameters?.api_key || ''
	drawerVisible.value = true
}

async function checkItem(id: string) {
	try {
		const res = await resource.postWebSearchCheckById({ id })
		if (res.isSuccess) {
			ElMessage.success('连通测试成功')
		} else {
			ElMessage.error(res?.error || '连通测试失败')
		}
	} catch {
		ElMessage.error('连通测试失败')
	}
}

async function checkWithParameters() {
	checkLoading.value = true
	checkMessage.value = ''
	try {
		const res = await resource.postWebSearchCheckWithParameters({
			provider: form.provider,
			parameters: {
				api_key: form.parameters.api_key,
				proxy_url: form.parameters.proxy_url,
				engine_id: form.parameters.engine_id
			}
		})
		checkSuccess.value = !!res.isSuccess
		checkMessage.value = res.isSuccess ? '连通测试成功' : '连通测试失败'
	} catch {
		checkSuccess.value = false
		checkMessage.value = '连通测试失败'
	} finally {
		checkLoading.value = false
	}
}

async function handleSubmit() {
	await formRef.value?.validate(async (valid: boolean) => {
		if (!valid) return
		submitLoading.value = true
		try {
			const payload = {
				provider: form.provider,
				name: form.name,
				description: form.description,
				is_default: form.is_default,
				parameters: {
					proxy_url: form.parameters.proxy_url,
					api_key: form.parameters.api_key,
					engine_id: form.parameters.engine_id
				}
			}
			if (currentId.value) {
				await resource.postWebSearchUpdate({ id: currentId.value, ...(payload as any) })
				ElMessage.success('更新成功')
			} else {
				await resource.postWebSearchCreate(payload as any)
				ElMessage.success('创建成功')
			}
			drawerVisible.value = false
			loadList(pagination.pageIndex)
		} catch {
			ElMessage.error('保存失败')
		} finally {
			submitLoading.value = false
		}
	})
}

async function removeItem(id: string) {
	try {
		await ElMessageBox.confirm('确定删除该网络搜索配置吗？', '提示', { type: 'warning' })
		await resource.postWebSearchOpenApiDelete({ id })
		ElMessage.success('删除成功')
		loadList(pagination.pageIndex)
	} catch {
		// ignore
	}
}

onMounted(async () => {
	await loadEngines()
	await loadList(1)
})
</script>

<style scoped lang="less">
.panel {
	display: flex;
	flex-direction: column;
	gap: 16px;
}

.toolbar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 12px;
	flex-wrap: wrap;
}

.toolbar-left,
.toolbar-right {
	display: flex;
	align-items: center;
	gap: 10px;
	flex-wrap: wrap;
}

.search-input {
	width: 280px;
}

.toolbar-meta {
	display: flex;
	align-items: center;
	gap: 10px;
	flex-wrap: wrap;
}

.pill {
	padding: 8px 12px;
	border-radius: 999px;
	border: 1px solid #e5e7eb;
	background: #f8fafc;
	font-size: 12px;
	color: #64748b;
}

.tip-box {
	padding: 14px 16px;
	border-radius: 16px;
	background: #f8fafc;
	border: 1px solid #e5e7eb;
}

.tip-title {
	font-weight: 700;
	color: #111827;
	margin-bottom: 10px;
}

.engine-tags {
	display: flex;
	flex-wrap: wrap;
	gap: 8px;
}

.grid {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
	gap: 16px;
	min-height: 200px;

	.empty {
		grid-column: span 4;
	}
}

.actions {
	display: flex;
	justify-content: flex-end;
}

.actions-trigger {
	width: 30px;
	height: 30px;
	border-radius: 999px;
	display: grid;
	place-items: center;
	color: #475569;
	background: rgba(255, 255, 255, 0.8);
	transition:
		background 0.2s ease,
		color 0.2s ease;
}

.actions-trigger:hover {
	background: rgba(15, 23, 42, 0.08);
	color: #0f172a;
}

.danger-text {
	color: var(--el-color-danger);
}

.card {
	overflow: hidden;
	border-radius: 20px;
	border: 1px solid #e5e7eb;
	background: #fff;
	box-shadow: 0 12px 28px rgba(15, 23, 42, 0.06);
	padding: 16px;
	display: flex;
	flex-direction: column;
	gap: 14px;
	transition:
		transform 0.22s ease,
		box-shadow 0.22s ease,
		border-color 0.22s ease;
}

.card:hover {
	transform: translateY(-3px);
	border-color: #d8dee9;
	box-shadow: 0 18px 36px rgba(15, 23, 42, 0.1);
}

.card-head {
	padding: 14px 16px;
	border-radius: 18px;
	background:
		radial-gradient(circle at top left, rgba(15, 23, 42, 0.06), transparent 38%),
		linear-gradient(135deg, #f8fafc, #eef2ff 58%, #fff7ed);
}

.title {
	font-size: 18px;
	font-weight: 700;
	line-height: 1.25;
	color: #0f172a;
	word-break: break-word;
}

.subtitle {
	margin-top: 6px;
	font-size: 13px;
	color: #64748b;
	word-break: break-word;
}

.badge-row {
	margin-top: 10px;
	display: flex;
	flex-wrap: wrap;
	gap: 8px;
}

.badge {
	padding: 5px 10px;
	border-radius: 999px;
	background: rgba(255, 255, 255, 0.92);
	font-size: 12px;
	color: #334155;
	border: 1px solid rgba(203, 213, 225, 0.9);
}

.badge.subtle {
	background: rgba(15, 23, 42, 0.82);
	color: #f8fafc;
	border-color: transparent;
}

.desc {
	min-height: 44px;
	color: #64748b;
	font-size: 14px;
	line-height: 1.65;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
}

.tags {
	display: flex;
	flex-wrap: wrap;
	gap: 8px;
}

.meta-list {
	display: grid;
	grid-template-columns: repeat(2, minmax(0, 1fr));
	gap: 10px;
}

.meta-item {
	padding: 10px 12px;
	border-radius: 14px;
	background: #f8fafc;
	border: 1px solid #e2e8f0;
	display: flex;
	flex-direction: column;
	gap: 4px;
	min-width: 0;
}

.meta-label {
	font-size: 12px;
	color: #94a3b8;
}

.meta-value {
	font-size: 13px;
	color: #334155;
	word-break: break-word;
}

.card-footer {
	display: flex;
	justify-content: flex-end;
	gap: 6px;
	margin-top: auto;
	flex-wrap: wrap;
}

.pagination {
	display: flex;
	justify-content: flex-end;
}

.grid-2 {
	display: grid;
	grid-template-columns: repeat(2, minmax(0, 1fr));
	gap: 12px;
}

.drawer-footer {
	display: flex;
	justify-content: flex-end;
	gap: 10px;
}

.check-box {
	width: 100%;
	display: flex;
	flex-direction: column;
	gap: 10px;
}

@media (max-width: 768px) {
	.search-input {
		width: 100%;
	}

	.grid-2,
	.meta-list {
		grid-template-columns: 1fr;
	}
}
</style>
