<template>
	<div class="audit-config">
		<div class="audit-config__header">
			<div class="audit-config__title">
				<h2>审核规则配置</h2>
				<p>按主机厂、车辆类型、动力类型和产品匹配审核 Agent。</p>
			</div>
			<div class="audit-config__actions">
				<el-input
					v-model="filters.keyWord"
					clearable
					placeholder="搜索规则/主机厂/产品/Agent"
					class="search-input"
					@keyup.enter="loadData"
				>
					<template #prefix>
						<el-icon><Search /></el-icon>
					</template>
				</el-input>
				<el-select v-model="filters.status" clearable placeholder="状态" class="status-select">
					<el-option label="启用" :value="1" />
					<el-option label="禁用" :value="0" />
				</el-select>
				<el-button :icon="Search" type="primary" @click="loadData">查询</el-button>
				<el-button :icon="Refresh" @click="handleResetFilters">重置</el-button>
				<el-button type="primary" @click="openDialog()">新增规则</el-button>
				<el-button @click="handleTestMatch">测试匹配</el-button>
			</div>
		</div>

		<el-table
			v-loading="loading"
			:data="tableData"
			border
			stripe
			class="audit-config__table"
			style="width: 100%"
		>
			<el-table-column prop="priority" label="优先级" width="86" align="center" sortable />
			<el-table-column prop="name" label="规则名称" min-width="150" show-overflow-tooltip />
			<el-table-column prop="orderType" label="订单类型" width="96" align="center">
				<template #default="{ row }">
					<el-tag v-if="row.orderType === 'insure'" size="small">投保</el-tag>
					<el-tag v-else-if="row.orderType === 'claim'" type="warning" size="small">理赔</el-tag>
					<span v-else class="text-muted">全部</span>
				</template>
			</el-table-column>
			<el-table-column prop="oemName" label="主机厂" width="120" show-overflow-tooltip>
				<template #default="{ row }">{{ row.oemName || '全部' }}</template>
			</el-table-column>
			<el-table-column prop="carType" label="车辆类型" width="102" align="center">
				<template #default="{ row }">
					<el-tag v-if="row.carType === '0'" size="small">新车</el-tag>
					<el-tag v-else-if="row.carType === '1'" type="success" size="small">在用车</el-tag>
					<span v-else class="text-muted">全部</span>
				</template>
			</el-table-column>
			<el-table-column prop="carPower" label="动力" width="92" align="center">
				<template #default="{ row }">
					<el-tag v-if="row.carPower === '1'" type="info" size="small">燃油</el-tag>
					<el-tag v-else-if="row.carPower === '2'" type="success" size="small">新能源</el-tag>
					<span v-else class="text-muted">全部</span>
				</template>
			</el-table-column>
			<el-table-column prop="productName" label="产品" min-width="220" show-overflow-tooltip>
				<template #default="{ row }">
					<div v-if="row.productName || row.productNo" class="product-cell">
						<span>{{ row.productName || '-' }}</span>
						<code v-if="row.productNo">{{ row.productNo }}</code>
					</div>
					<span v-else class="text-muted">全部</span>
				</template>
			</el-table-column>
			<el-table-column prop="agentName" label="审核 Agent" min-width="220" show-overflow-tooltip>
				<template #default="{ row }">
					<div class="agent-cell">
						<span>{{ row.agentName || '-' }}</span>
						<span class="text-muted">ID: {{ displayAgentIds(row).join(', ') || '-' }}</span>
					</div>
				</template>
			</el-table-column>
			<el-table-column prop="status" label="状态" width="82" align="center">
				<template #default="{ row }">
					<el-switch
						:model-value="row.status === 1"
						size="small"
						@change="(val) => handleToggleStatus(row, Boolean(val))"
					/>
				</template>
			</el-table-column>
			<el-table-column prop="remark" label="备注" width="150" show-overflow-tooltip />
			<el-table-column prop="updateTime" label="更新时间" width="170" />
			<el-table-column label="操作" width="150" fixed="right" align="center">
				<template #default="{ row }">
					<el-button size="small" link type="primary" @click="openDialog(row)">编辑</el-button>
					<el-button size="small" link type="danger" @click="handleDelete(row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<div class="audit-config__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-dialog
			v-model="dialog.visible"
			:title="dialog.isEdit ? '编辑审核规则' : '新增审核规则'"
			width="840px"
			@closed="resetForm"
		>
			<el-form
				ref="formRef"
				:model="dialog.form"
				:rules="formRules"
				label-width="104px"
				class="rule-form"
			>
				<el-form-item label="规则名称" prop="name">
					<el-input v-model="dialog.form.name" placeholder="如：长安新能源出行无忧审核" />
				</el-form-item>

				<div class="form-grid">
					<el-form-item label="订单类型" prop="orderType">
						<el-select
							v-model="dialog.form.orderType"
							clearable
							placeholder="全部订单类型"
							style="width: 100%"
						>
							<el-option label="投保" value="insure" />
							<el-option label="理赔" value="claim" />
						</el-select>
					</el-form-item>
					<el-form-item label="优先级" prop="priority">
						<el-input-number
							v-model="dialog.form.priority"
							:min="0"
							:max="9999"
							controls-position="right"
							style="width: 100%"
						/>
					</el-form-item>
				</div>

				<el-form-item label="主机厂" prop="oemId">
					<el-select
						v-model="dialog.form.oemId"
						clearable
						filterable
						remote
						:remote-method="searchOems"
						:loading="oemLoading"
						placeholder="请选择主机厂"
						style="width: 100%"
						@change="onOemChange"
						@clear="onOemClear"
					>
						<el-option
							v-for="item in oemOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>
				</el-form-item>

				<div class="condition-grid">
					<el-form-item label="车辆类型" prop="carType">
						<el-segmented
							v-model="dialog.form.carType"
							:options="carTypeOptions"
							block
							class="route-segmented"
							@change="onRouteConditionChange"
						/>
					</el-form-item>
					<el-form-item v-if="showCarPowerSelector" label="动力类型" prop="carPower">
						<el-segmented
							v-model="dialog.form.carPower"
							:options="carPowerOptions"
							block
							class="route-segmented"
							@change="onRouteConditionChange"
						/>
					</el-form-item>
				</div>

				<el-form-item label="产品" prop="productKey">
					<el-select
						:key="productSelectKey"
						v-model="dialog.form.productKey"
						clearable
						filterable
						:reserve-keyword="false"
						:filter-method="filterProducts"
						:loading="productLoading"
						:disabled="!canSelectProduct"
						placeholder="请选择父产品"
						style="width: 100%"
						@visible-change="handleProductVisible"
						@change="onProductChange"
						@clear="onProductClear"
					>
						<el-option
							v-for="item in visibleProductOptions"
							:key="item.key"
							:label="item.label"
							:value="item.key"
						>
							<div class="product-option">
								<span>{{ item.displayName }}</span>
							</div>
						</el-option>
					</el-select>
					<div class="form-tip">
						初始展示 15 个父产品，输入产品展示名称可在本地模糊搜索。
					</div>
				</el-form-item>

				<el-form-item label="审核 Agent" prop="agentIds">
					<el-select
						v-model="dialog.form.agentIds"
						multiple
						filterable
						collapse-tags
						collapse-tags-tooltip
						placeholder="可选择多个 Agent"
						style="width: 100%"
						@change="onAgentChange"
					>
						<el-option
							v-for="agent in agentList"
							:key="agent.id"
							:label="`${agent.label || agent.name} (${agent.name})`"
							:value="agent.id"
						/>
					</el-select>
					<div class="form-tip">
						同一规则选择多个 Agent 时，系统会并发执行并按驳回优先、转人工其次、通过最后的策略聚合结果。
					</div>
				</el-form-item>

				<el-form-item label="状态">
					<el-switch v-model="dialog.form.statusBool" active-text="启用" inactive-text="禁用" />
				</el-form-item>
				<el-form-item label="备注">
					<el-input v-model="dialog.form.remark" type="textarea" :rows="2" placeholder="可选" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="dialog.visible = false">取消</el-button>
				<el-button type="primary" :loading="submitting" @click="handleSubmit">确认</el-button>
			</template>
		</el-dialog>

		<el-dialog v-model="testDialog.visible" title="测试规则匹配" width="620px">
			<el-form label-width="96px">
				<el-form-item label="订单类型">
					<el-select v-model="testDialog.orderType" placeholder="选择类型" style="width: 100%">
						<el-option label="投保" value="insure" />
						<el-option label="理赔" value="claim" />
					</el-select>
				</el-form-item>
				<el-form-item label="主机厂">
					<el-select
						v-model="testDialog.oemId"
						clearable
						filterable
						remote
						:remote-method="searchOems"
						:loading="oemLoading"
						placeholder="请选择主机厂"
						style="width: 100%"
						@change="onTestOemChange"
					>
						<el-option
							v-for="item in oemOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>
				</el-form-item>
				<div class="form-grid">
					<el-form-item label="车辆类型">
						<el-select v-model="testDialog.carType" clearable placeholder="不限" style="width: 100%">
							<el-option label="新车" value="0" />
							<el-option label="在用车" value="1" />
						</el-select>
					</el-form-item>
					<el-form-item v-if="showTestCarPowerSelector" label="动力类型">
						<el-select v-model="testDialog.carPower" clearable placeholder="不限" style="width: 100%">
							<el-option label="燃油" value="1" />
							<el-option label="新能源" value="2" />
						</el-select>
					</el-form-item>
					<el-form-item v-else label="动力类型">
						<el-input
							:model-value="testDialog.oemId && FIXED_NEW_ENERGY_OEMS.has(testDialog.oemId) ? '新能源' : '跳过'"
							disabled
						/>
					</el-form-item>
				</div>
				<el-form-item label="产品编号">
					<el-input v-model="testDialog.productNo" clearable placeholder="可选，优先精确匹配" />
				</el-form-item>
				<el-form-item label="产品名称">
					<el-input v-model="testDialog.productName" clearable placeholder="输入产品名称" />
				</el-form-item>
			</el-form>

			<div v-if="testDialog.result !== null" class="test-result">
				<template v-if="testDialog.result">
					<el-result icon="success" title="命中规则">
						<template #sub-title>
							<el-descriptions :column="1" border size="small">
								<el-descriptions-item label="规则名称">
									{{ testDialog.result.name }}
								</el-descriptions-item>
								<el-descriptions-item label="产品">
									{{ testDialog.result.productName || '全部产品' }}
								</el-descriptions-item>
								<el-descriptions-item label="优先级">
									{{ testDialog.result.priority }}
								</el-descriptions-item>
								<el-descriptions-item label="Agent">
									{{ testDialog.result.agentName || '-' }}
								</el-descriptions-item>
							</el-descriptions>
						</template>
					</el-result>
				</template>
				<template v-else>
					<el-result
						icon="warning"
						title="未命中任何规则"
						sub-title="该订单将以待处理状态等待，不会自动审核"
					/>
				</template>
			</div>
			<template #footer>
				<el-button @click="testDialog.visible = false">关闭</el-button>
				<el-button type="primary" @click="doTestMatch">开始匹配</el-button>
			</template>
		</el-dialog>
	</div>
</template>

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

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

type AgentOption = { id: number; name: string; label: string };
type OemOption = { value: number; label: string; id: number; name: string };
type ProductOption = {
	key: string;
	value: string;
	label: string;
	displayName: string;
	id: string;
	oemId: number;
	productNo: string;
	productName: string;
	productOemName?: string;
	insuranceCompany?: string;
	fuelType?: string;
	productType?: string;
};

const CHANGAN_OEM_ID = 2;
const SERES_OEM_ID = 11;
const AVATR_OEM_ID = 16;
const FIXED_NEW_ENERGY_OEMS = new Set([SERES_OEM_ID, AVATR_OEM_ID]);
const INITIAL_PRODUCT_LIMIT = 15;

const { user } = useBase();
const loading = ref(false);
const submitting = ref(false);
const oemLoading = ref(false);
const productLoading = ref(false);
const tableData = ref<any[]>([]);
const agentList = ref<AgentOption[]>([]);
const oemOptions = ref<OemOption[]>([]);
const productOptions = ref<ProductOption[]>([]);
const productKeyword = ref('');
const productReloadVersion = ref(0);
const productSelectKey = ref(0);
const formRef = ref<FormInstance>();

const pagination = reactive({
	page: 1,
	size: 20,
	total: 0
});

const filters = reactive({
	keyWord: '',
	status: undefined as number | undefined
});

const defaultForm = () => ({
	id: null as number | null,
	name: '',
	orderType: '' as string,
	oemId: undefined as number | undefined,
	oemName: '',
	productKey: '',
	productNo: '',
	productName: '',
	carType: '' as string,
	carPower: '' as string,
	agentId: undefined as number | undefined,
	agentIds: [] as number[],
	agentName: '',
	priority: 0,
	statusBool: true,
	remark: ''
});

const dialog = reactive({
	visible: false,
	isEdit: false,
	form: defaultForm()
});

const testDialog = reactive({
	visible: false,
	orderType: 'insure',
	oemId: undefined as number | undefined,
	productNo: '',
	productName: '',
	carType: '' as string,
	carPower: '' as string,
	result: null as any
});

const carTypeOptions = [
	{ label: '新车', value: '0' },
	{ label: '在用车', value: '1' }
];

const carPowerOptions = [
	{ label: '燃油', value: '1' },
	{ label: '新能源', value: '2' }
];

const formRules: FormRules = {
	name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
	oemId: [{ required: true, message: '请选择主机厂', trigger: 'change' }],
	carType: [{ required: true, message: '请选择新车或在用车', trigger: 'change' }],
	carPower: [
		{
			validator: (_rule, value, callback) => {
				if (showCarPowerSelector.value && !value) {
					callback(new Error('请选择燃油或新能源'));
					return;
				}
				callback();
			},
			trigger: 'change'
		}
	],
	agentIds: [
		{
			validator: (_rule, value, callback) => {
				if (!Array.isArray(value) || value.length === 0) {
					callback(new Error('请至少选择一个审核 Agent'));
					return;
				}
				callback();
			},
			trigger: 'change'
		}
	]
};

const showCarPowerSelector = computed(() => dialog.form.oemId === CHANGAN_OEM_ID);
const showTestCarPowerSelector = computed(() => testDialog.oemId === CHANGAN_OEM_ID);

const canSelectProduct = computed(() => {
	if (!dialog.form.oemId || !dialog.form.carType) return false;
	if (showCarPowerSelector.value && !dialog.form.carPower) return false;
	return true;
});

const visibleProductOptions = computed(() => {
	const kw = normalizeKeyword(productKeyword.value);
	const list = kw ? productOptions.value.filter(item => matchProduct(item, kw)) : productOptions.value;
	const visible = list.slice(0, INITIAL_PRODUCT_LIMIT);
	const selected = productOptions.value.find(item => item.key === dialog.form.productKey);
	if (selected && !visible.some(item => item.key === selected.key)) {
		return [selected, ...visible].slice(0, INITIAL_PRODUCT_LIMIT);
	}
	return visible;
});

watch(
	() => [dialog.form.oemId, dialog.form.carType, dialog.form.carPower],
	(_value, oldValue) => {
		if (!dialog.visible) return;
		resetProductSelection();
		if (oldValue) {
			productSelectKey.value += 1;
		}
		if (canSelectProduct.value) {
			void loadProducts();
		}
	}
);

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 normalizeKeyword(value: string) {
	return value.trim().toLowerCase();
}

function normalizeAgentIds(agentIds: unknown, fallback?: unknown): number[] {
	let source: unknown[] = [];
	if (Array.isArray(agentIds)) {
		source = agentIds;
	} else if (typeof agentIds === 'string') {
		try {
			const parsed = JSON.parse(agentIds);
			source = Array.isArray(parsed) ? parsed : agentIds.split(/[;；,，]/);
		} catch {
			source = agentIds.split(/[;；,，]/);
		}
	}
	const ids = source
		.map(item => Number(item))
		.filter(item => Number.isFinite(item) && item > 0);
	const fallbackId = Number(fallback);
	if (ids.length === 0 && Number.isFinite(fallbackId) && fallbackId > 0) {
		ids.push(fallbackId);
	}
	return Array.from(new Set(ids));
}

function normalizeProduct(item: any, index = 0): ProductOption | null {
	const rawId = String(item.id ?? '').trim();
	const rawValue = String(item.value ?? '').trim();
	const productNo = String(item.productNo ?? '').trim() || (rawValue && rawValue !== rawId ? rawValue : '');
	const productName = String(item.productName ?? item.product_name ?? item.label ?? '').trim();
	const productOemName = String(item.productOemName ?? item.product_oem_name ?? '').trim();
	const displayName = productName || productOemName || productNo || rawId;
	if (!displayName) return null;
	const key = [dialog.form.oemId || item.oemId || 'oem', rawId || `row-${index}`, productNo, productName, productOemName]
		.filter(Boolean)
		.join('|');
	return {
		key,
		value: key,
		label: displayName,
		displayName,
		id: rawId || key,
		oemId: Number(item.oemId ?? dialog.form.oemId),
		productNo,
		productName,
		productOemName: productOemName || undefined,
		insuranceCompany: item.insuranceCompany ? String(item.insuranceCompany) : undefined,
		fuelType: item.fuelType == null ? undefined : String(item.fuelType),
		productType: item.productType == null ? undefined : String(item.productType)
	};
}

function matchProduct(item: ProductOption, keyword: string) {
	return [
		item.productOemName,
		item.displayName,
		item.label
	]
		.filter(Boolean)
		.some(value => String(value).toLowerCase().includes(keyword));
}

function displayAgentIds(row: any) {
	return normalizeAgentIds(row.agentIds, row.agentId);
}

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.status !== undefined) body.status = filters.status;
		const data = await apiPost('/admin/audit/config/page', body);
		if (data.code === 1000 && data.data) {
			tableData.value = data.data.list || [];
			pagination.total = data.data.pagination?.total || 0;
		} else {
			ElMessage.error(data.message || '加载配置列表失败');
		}
	} catch {
		ElMessage.error('加载配置列表失败');
	} finally {
		loading.value = false;
	}
}

async function loadAgents() {
	try {
		const data = await apiPost('/admin/audit/config/agents', {});
		if (data.code === 1000 && Array.isArray(data.data)) {
			agentList.value = data.data;
		}
	} catch {
		// ignore
	}
}

async function loadOems(keyword = '') {
	oemLoading.value = true;
	try {
		const data = await apiPost('/admin/audit/config/oems', { keyword });
		if (data.code === 1000 && Array.isArray(data.data)) {
			oemOptions.value = data.data;
		}
	} catch {
		ElMessage.error('加载主机厂失败');
	} finally {
		oemLoading.value = false;
	}
}

function searchOems(keyword: string) {
	void loadOems(keyword);
}

async function loadProducts(options: { preserveSelected?: boolean } = {}) {
	if (!canSelectProduct.value) return;
	const requestVersion = ++productReloadVersion.value;
	productLoading.value = true;
	try {
		const selectedNo = dialog.form.productNo;
		const selectedName = dialog.form.productName;
		const carPower = dialog.form.oemId === CHANGAN_OEM_ID ? dialog.form.carPower || undefined : undefined;
		const data = await apiPost('/admin/audit/config/products', {
			oemId: dialog.form.oemId,
			carType: dialog.form.carType || undefined,
			carPower
		});
		if (data.code === 1000 && Array.isArray(data.data)) {
			const seen = new Set<string>();
			const nextOptions = data.data
				.map((item: any, index: number) => normalizeProduct(item, index))
				.filter((item: ProductOption | null): item is ProductOption => {
					if (!item) return false;
					if (seen.has(item.key)) return false;
					seen.add(item.key);
					return true;
				});
			if (requestVersion !== productReloadVersion.value) return;
			productOptions.value = nextOptions;
			if (options.preserveSelected && (selectedNo || selectedName)) {
				const matched = productOptions.value.find(item => {
					if (selectedNo && item.productNo === selectedNo) return true;
					return Boolean(selectedName && item.productName === selectedName);
				});
				if (matched) {
					dialog.form.productKey = matched.key;
					dialog.form.productNo = matched.productNo;
					dialog.form.productName = matched.productName;
				} else if (selectedName) {
					ensureSelectedProduct({
						id: dialog.form.id,
						oemId: dialog.form.oemId,
						productNo: selectedNo,
						productName: selectedName
					});
				}
			}
		} else {
			ElMessage.error(data.message || '加载产品失败');
		}
	} catch {
		ElMessage.error('加载产品失败');
	} finally {
		if (requestVersion === productReloadVersion.value) {
			productLoading.value = false;
		}
	}
}

function filterProducts(keyword: string) {
	productKeyword.value = keyword;
}

function handleProductVisible(visible: boolean) {
	if (visible && canSelectProduct.value && productOptions.value.length === 0) {
		void loadProducts();
	}
}

function resetProductSelection() {
	productReloadVersion.value += 1;
	clearProductValue();
	productOptions.value = [];
}

function clearProductValue() {
	dialog.form.productKey = '';
	dialog.form.productNo = '';
	dialog.form.productName = '';
	productKeyword.value = '';
}

function onOemChange(value?: number) {
	const item = oemOptions.value.find(option => option.value === value);
	dialog.form.oemName = item?.label || '';
	if (value && FIXED_NEW_ENERGY_OEMS.has(value)) {
		dialog.form.carPower = '2';
	} else if (value !== CHANGAN_OEM_ID) {
		dialog.form.carPower = '';
	}
}

function onOemClear() {
	dialog.form.oemName = '';
	dialog.form.carType = '';
	dialog.form.carPower = '';
	onProductClear();
}

function onRouteConditionChange() {
	if (dialog.form.oemId && FIXED_NEW_ENERGY_OEMS.has(dialog.form.oemId)) {
		dialog.form.carPower = '2';
	}
}

function onProductChange(value?: string) {
	const item = productOptions.value.find(option => option.key === value);
	dialog.form.productNo = item?.productNo || '';
	dialog.form.productName = item?.productName || '';
}

function onProductClear() {
	clearProductValue();
}

function onAgentChange(agentIds: number[]) {
	const nextIds = normalizeAgentIds(agentIds);
	dialog.form.agentIds = nextIds;
	const selected = agentList.value.filter(agent => nextIds.includes(agent.id));
	dialog.form.agentId = selected[0]?.id;
	dialog.form.agentName = selected.map(agent => agent.label || agent.name).join('、');
}

function onTestOemChange(value?: number) {
	if (value && FIXED_NEW_ENERGY_OEMS.has(value)) {
		testDialog.carPower = '2';
		return;
	}
	if (value !== CHANGAN_OEM_ID) {
		testDialog.carPower = '';
	}
}

async function ensureSelectedOem(row: any) {
	if (!row?.oemId || !row?.oemName) return;
	if (oemOptions.value.some(item => item.value === row.oemId)) return;
	oemOptions.value = [
		...oemOptions.value,
		{
			value: Number(row.oemId),
			label: row.oemName,
			id: Number(row.oemId),
			name: row.oemName
		}
	];
}

function ensureSelectedProduct(row: any) {
	if (!row?.productName) return;
	const key = `saved-${row.id || row.productNo || row.productName}`;
	if (productOptions.value.some(item => item.key === key)) return;
	const displayName = row.productOemName || row.productName || row.productNo;
	productOptions.value = [
		{
			key,
			value: key,
			label: displayName,
			displayName,
			id: String(row.productId ?? row.id ?? key),
			oemId: Number(row.oemId || 0),
			productNo: row.productNo || '',
			productName: row.productName,
			productOemName: row.productOemName || undefined
		},
		...productOptions.value
	];
	dialog.form.productKey = key;
}

async function openDialog(row?: any) {
	dialog.isEdit = Boolean(row);
	productReloadVersion.value = 0;
	if (row) {
		const agentIds = normalizeAgentIds(row.agentIds, row.agentId);
		dialog.form = {
			id: row.id,
			name: row.name || '',
			orderType: row.orderType || '',
			oemId: row.oemId || undefined,
			oemName: row.oemName || '',
			productKey: '',
			productNo: row.productNo || '',
			productName: row.productName || row.productKeyword || '',
			carType: row.carType || '',
			carPower: row.carPower || '',
			agentId: agentIds[0],
			agentIds,
			agentName: row.agentName || '',
			priority: row.priority || 0,
			statusBool: row.status === 1,
			remark: row.remark || ''
		};
		await ensureSelectedOem(row);
		ensureSelectedProduct(row);
	} else {
		resetForm();
	}
	dialog.visible = true;
	await nextTick();
	formRef.value?.clearValidate();
	if (dialog.form.oemId && canSelectProduct.value) {
		void loadProducts({ preserveSelected: true });
	}
}

function resetForm() {
	dialog.form = defaultForm();
	productKeyword.value = '';
	productOptions.value = [];
	productReloadVersion.value = 0;
	productSelectKey.value += 1;
	formRef.value?.clearValidate();
}

function handleResetFilters() {
	filters.keyWord = '';
	filters.status = undefined;
	pagination.page = 1;
	void loadData();
}

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

	const agentIds = normalizeAgentIds(dialog.form.agentIds);
	const selectedAgents = agentList.value.filter(agent => agentIds.includes(agent.id));
	const body: any = {
		name: dialog.form.name.trim(),
		orderType: dialog.form.orderType || null,
		oemId: dialog.form.oemId || null,
		oemName: dialog.form.oemName || null,
		productKeyword: dialog.form.productName || null,
		productNo: dialog.form.productNo || null,
		productName: dialog.form.productName || null,
		carType: dialog.form.carType || null,
		carPower: dialog.form.carPower || null,
		agentId: agentIds[0],
		agentIds,
		agentName: selectedAgents.map(agent => agent.label || agent.name).join('、'),
		priority: dialog.form.priority,
		status: dialog.form.statusBool ? 1 : 0,
		remark: dialog.form.remark || null
	};
	if (dialog.isEdit) body.id = dialog.form.id;

	submitting.value = true;
	try {
		const data = await apiPost(dialog.isEdit ? '/admin/audit/config/update' : '/admin/audit/config/add', body);
		if (data.code === 1000) {
			ElMessage.success(dialog.isEdit ? '更新成功' : '创建成功');
			dialog.visible = false;
			await loadData();
		} else {
			ElMessage.error(data.message || '操作失败');
		}
	} catch {
		ElMessage.error('操作失败');
	} finally {
		submitting.value = false;
	}
}

async function handleDelete(row: any) {
	try {
		await ElMessageBox.confirm(`确定要删除规则“${row.name}”吗？`, '删除确认', {
			type: 'warning'
		});
		const data = await apiPost('/admin/audit/config/delete', { ids: [row.id] });
		if (data.code === 1000) {
			ElMessage.success('删除成功');
			await loadData();
		} else {
			ElMessage.error(data.message || '删除失败');
		}
	} catch {
		// cancel
	}
}

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

function handleTestMatch() {
	testDialog.result = null;
	testDialog.visible = true;
}

async function doTestMatch() {
	try {
		const data = await apiPost('/admin/audit/config/testMatch', {
			orderType: testDialog.orderType,
			oemId: testDialog.oemId || null,
			productNo: testDialog.productNo || null,
			productName: testDialog.productName || null,
			carType: testDialog.carType || null,
			carPower: testDialog.carPower || null
		});
		if (data.code === 1000) {
			testDialog.result = data.data || false;
		} else {
			ElMessage.error(data.message || '匹配失败');
		}
	} catch {
		ElMessage.error('匹配测试失败');
	}
}

onMounted(() => {
	void loadData();
	void loadAgents();
	void loadOems();
});
</script>

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

	&__header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 16px;
		padding: 14px 16px;
		background: var(--el-bg-color);
		border: 1px solid var(--el-border-color-light);
		border-radius: 6px;
		margin-bottom: 12px;
	}

	&__title {
		min-width: 220px;

		h2 {
			margin: 0;
			font-size: 18px;
			font-weight: 600;
			color: var(--el-text-color-primary);
		}

		p {
			margin: 4px 0 0;
			font-size: 12px;
			color: var(--el-text-color-secondary);
		}
	}

	&__actions {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		gap: 10px;
		flex-wrap: wrap;
	}

	&__table {
		flex: 1;
	}

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

.search-input {
	width: 260px;
}

.status-select {
	width: 112px;
}

.product-cell,
.agent-cell {
	display: flex;
	flex-direction: column;
	gap: 2px;
	line-height: 1.35;

	code {
		width: fit-content;
		padding: 1px 5px;
		border-radius: 4px;
		background: var(--el-fill-color-light);
		color: var(--el-text-color-secondary);
		font-size: 12px;
	}
}

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

.condition-grid {
	display: grid;
	grid-template-columns: minmax(260px, 1fr) minmax(300px, 1fr);
	gap: 12px 16px;
	align-items: start;
}

.route-segmented {
	width: 100%;
	min-width: 220px;

	:deep(.el-segmented__item) {
		min-width: 92px;
		padding: 0 14px;
	}

	:deep(.el-segmented__item-label) {
		white-space: nowrap;
		overflow: visible;
		text-overflow: clip;
	}
}

.product-option {
	min-width: 0;
	line-height: 1.4;

	span {
		display: block;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
}

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

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

.test-result {
	margin-top: 16px;
	padding: 12px;
	background: var(--el-fill-color-light);
	border-radius: 6px;
}

@media (max-width: 960px) {
	.audit-config__header {
		align-items: stretch;
		flex-direction: column;
	}

	.audit-config__actions {
		justify-content: flex-start;
	}

	.search-input {
		width: 100%;
	}

	.rule-form .form-grid,
	.condition-grid {
		grid-template-columns: 1fr;
	}

	.route-segmented {
		min-width: 0;
	}
}
</style>
