<template>
	<div class="audit-orders">
		<!-- 顶部筛选栏 -->
		<div class="audit-orders__header">
			<el-select v-model="filters.orderType" placeholder="订单类型" clearable style="width: 120px">
				<el-option label="投保" value="insure" />
				<el-option label="理赔" value="claim" />
			</el-select>
			<el-select v-model="filters.status" placeholder="审核状态" clearable style="width: 140px">
				<el-option label="待处理" value="pending" />
				<el-option label="处理中" value="processing" />
				<el-option label="通过" value="approved" />
				<el-option label="驳回" value="rejected" />
				<el-option label="转人工" value="manual_review" />
				<el-option label="失败" value="failed" />
			</el-select>
			<el-select v-model="filters.auditDecision" placeholder="审核结论" clearable style="width: 140px">
				<el-option label="通过" value="approved" />
				<el-option label="驳回" value="rejected" />
				<el-option label="转人工" value="manual_review" />
			</el-select>
			<el-select v-model="filters.insuranceCompany" placeholder="保险公司" clearable style="width: 140px">
				<el-option
					v-for="item in filterOptions.insurances"
					:key="item"
					:label="item"
					:value="item"
				/>
			</el-select>
			<el-select v-model="filters.orderSource" placeholder="订单来源" clearable style="width: 120px">
				<el-option
					v-for="item in filterOptions.orderSources"
					:key="item"
					:label="item"
					:value="item"
				/>
			</el-select>
			<el-date-picker
				v-model="filters.timeRange"
				type="daterange"
				range-separator="至"
				start-placeholder="开始日期"
				end-placeholder="结束日期"
				value-format="YYYY-MM-DD HH:mm:ss"
				style="width: 280px"
			/>
			<el-input
				v-model="filters.keyword"
				placeholder="搜索订单号/车主/手机/车架号..."
				clearable
				style="width: 260px"
				@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="audit-orders__table"
		>
			<el-table-column prop="orderNo" label="订单号" min-width="180" show-overflow-tooltip />
			<el-table-column prop="orderType" label="类型" width="80" align="center">
				<template #default="{ row }">
					<el-tag :type="row.orderType === 'insure' ? undefined : 'warning'" size="small">
						{{ row.orderType === 'insure' ? '投保' : '理赔' }}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="oemName" label="主机厂" width="100" show-overflow-tooltip>
				<template #default="{ row }">{{ row.oemName || row.brandName || '-' }}</template>
			</el-table-column>
			<el-table-column prop="productName" label="产品" width="150" show-overflow-tooltip>
				<template #default="{ row }">{{ row.productName || '-' }}</template>
			</el-table-column>
			<el-table-column prop="cardName" label="车主" width="80" show-overflow-tooltip>
				<template #default="{ row }">{{ row.cardName || '-' }}</template>
			</el-table-column>
			<el-table-column prop="phone" label="手机号" width="120">
				<template #default="{ row }">{{ row.phone || '-' }}</template>
			</el-table-column>
			<el-table-column prop="carFrame" label="车架号" width="170" show-overflow-tooltip>
				<template #default="{ row }">{{ row.carFrame || '-' }}</template>
			</el-table-column>
			<el-table-column prop="status" label="审核状态" width="100" align="center">
				<template #default="{ row }">
					<el-tag :type="statusTagType(row.status)" size="small">
						{{ statusLabel(row.status) }}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="auditScore" label="评分" width="70" align="center">
				<template #default="{ row }">
					<span v-if="row.auditScore != null">{{ row.auditScore }}</span>
					<span v-else class="text-muted">-</span>
				</template>
			</el-table-column>
			<el-table-column prop="factoryName" label="录单机构" width="160" show-overflow-tooltip>
				<template #default="{ row }">{{ row.factoryName || '-' }}</template>
			</el-table-column>
			<el-table-column prop="insuranceCompany" label="保险公司" width="140" show-overflow-tooltip>
				<template #default="{ row }">{{ row.insuranceCompany || '-' }}</template>
			</el-table-column>
			<el-table-column prop="repairFactoryName" label="报修机构" width="160" show-overflow-tooltip>
				<template #default="{ row }">{{ row.repairFactoryName || '-' }}</template>
			</el-table-column>
			<el-table-column prop="repairItems" label="报修类型" width="120" show-overflow-tooltip>
				<template #default="{ row }">{{ row.repairItems || '-' }}</template>
			</el-table-column>
			<el-table-column prop="repairStatus" label="报修状态" width="100" show-overflow-tooltip>
				<template #default="{ row }">{{ row.repairStatus || '-' }}</template>
			</el-table-column>
			<el-table-column prop="reportNo" label="报案号" width="160" show-overflow-tooltip>
				<template #default="{ row }">{{ row.reportNo || '-' }}</template>
			</el-table-column>
			<el-table-column prop="policyNo" label="保单号" width="160" show-overflow-tooltip>
				<template #default="{ row }">{{ row.policyNo || '-' }}</template>
			</el-table-column>
			<el-table-column prop="creator" label="录单人" width="80" show-overflow-tooltip>
				<template #default="{ row }">{{ row.creator || '-' }}</template>
			</el-table-column>
			<el-table-column prop="duration" label="耗时" width="80" align="center">
				<template #default="{ row }">
					<span v-if="row.duration != null">{{ (row.duration / 1000).toFixed(1) }}s</span>
					<span v-else class="text-muted">-</span>
				</template>
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" width="170" />
			<el-table-column label="操作" width="280" fixed="right" align="center">
				<template #default="{ row }">
					<el-button size="small" link type="primary" @click="handleDetail(row)">
						详情
					</el-button>
					<el-button
						v-if="row.status === 'pending'"
						size="small"
						link
						type="primary"
						@click="handleStartAudit(row)"
					>
						审核
					</el-button>
					<el-button
						v-if="['failed', 'rejected'].includes(row.status)"
						size="small"
						link
						type="warning"
						@click="handleRetry(row)"
					>
						重新审核
					</el-button>
					<el-button
						v-if="row.status === 'manual_review'"
						size="small"
						link
						type="success"
						@click="handleManual(row, 'approved')"
					>
						通过
					</el-button>
					<el-button
						v-if="row.status === 'manual_review'"
						size="small"
						link
						type="danger"
						@click="handleManual(row, 'rejected')"
					>
						驳回
					</el-button>
					<el-button
						size="small"
						link
						type="danger"
						@click="handleDelete(row)"
					>
						删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 分页 -->
		<div class="audit-orders__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="manualDialog.visible" title="人工复审" width="440px">
			<el-form label-width="80px">
				<el-form-item label="审核结论">
					<el-tag :type="manualDialog.status === 'approved' ? 'success' : 'danger'">
						{{ manualDialog.status === 'approved' ? '通过' : '驳回' }}
					</el-tag>
				</el-form-item>
				<el-form-item label="审核意见">
					<el-input
						v-model="manualDialog.remark"
						type="textarea"
						:rows="3"
						placeholder="请输入审核意见..."
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="manualDialog.visible = false">取消</el-button>
				<el-button type="primary" @click="submitManual">确认</el-button>
			</template>
		</el-dialog>
	</div>
</template>

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

import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Search, Refresh } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useBase } from '/$/base';
import { config } from '/@/config';
import type { AuditOrder } from '../types/index.d';

const router = useRouter();
const { user } = useBase();

const loading = ref(false);
const tableData = ref<AuditOrder[]>([]);
const filterOptions = reactive({
	insurances: [] as string[],
	orderSources: [] as string[]
});

const filters = reactive({
	orderType: '',
	status: '',
	auditDecision: '',
	insuranceCompany: '',
	orderSource: '',
	keyword: '',
	timeRange: null as string[] | null
});

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

const manualDialog = reactive({
	visible: false,
	orderId: 0,
	status: '' as 'approved' | 'rejected',
	remark: ''
});

// 状态标签
function statusLabel(status: string) {
	const map: Record<string, string> = {
		pending: '待处理',
		processing: '处理中',
		approved: '通过',
		rejected: '驳回',
		manual_review: '转人工',
		failed: '失败'
	};
	return map[status] || status;
}

function statusTagType(status: string): 'info' | 'success' | 'warning' | 'danger' | undefined {
	const map: Record<string, 'info' | 'success' | 'warning' | 'danger' | undefined> = {
		pending: 'info',
		processing: 'warning',
		approved: 'success',
		rejected: 'danger',
		manual_review: undefined,
		failed: 'danger'
	};
	return map[status] || 'info';
}

// API请求封装
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();
}

// 加载数据
async function loadData() {
	loading.value = true;
	try {
		const body: any = {
			page: pagination.page,
			size: pagination.size,
			keyWord: filters.keyword || undefined,
			orderType: filters.orderType || undefined,
			status: filters.status || undefined,
			auditDecision: filters.auditDecision || undefined,
			insuranceCompany: filters.insuranceCompany || undefined,
			orderSource: filters.orderSource || undefined
		};
		if (filters.timeRange?.length === 2) {
			body.startTime = filters.timeRange[0];
			body.endTime = filters.timeRange[1];
		}

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

async function loadFilterOptions() {
	try {
		const data = await apiPost('/admin/audit/audit/filterOptions', {});
		if (data.code === 1000 && data.data) {
			filterOptions.insurances = Array.isArray(data.data.insurances) ? data.data.insurances : [];
			filterOptions.orderSources = Array.isArray(data.data.orderSources) ? data.data.orderSources : [];
		}
	} catch {
		// 筛选项加载失败不影响订单列表
	}
}

function mergeOrderSourceOptions(rows: AuditOrder[]) {
	const current = new Set(filterOptions.orderSources);
	for (const row of rows) {
		const source = (row as any).orderSource;
		if (source) current.add(String(source));
	}
	filterOptions.orderSources = Array.from(current);
}

// 重置筛选
function handleReset() {
	filters.orderType = '';
	filters.status = '';
	filters.auditDecision = '';
	filters.insuranceCompany = '';
	filters.orderSource = '';
	filters.keyword = '';
	filters.timeRange = null;
	pagination.page = 1;
	loadData();
}

// 查看详情
function handleDetail(row: AuditOrder) {
	router.push({ path: '/audit/detail', query: { id: String(row.id) } });
}

// 删除
async function handleDelete(row: AuditOrder) {
	try {
		await ElMessageBox.confirm(`确定要删除订单 ${row.orderNo} 的审核数据吗？删除后不可恢复。`, '删除确认', { type: 'warning' });
		const data = await apiPost('/admin/audit/audit/remove', { ids: [row.id] });
		if (data.code === 1000) {
			ElMessage.success('删除成功');
			loadData();
		} else {
			ElMessage.error(data.message || '删除失败');
		}
	} catch {
		// 取消
	}
}

// 重新审核
async function handleRetry(row: AuditOrder) {
	try {
		await ElMessageBox.confirm('确定要重新审核该订单吗？', '重新审核');
		const data = await apiPost('/admin/audit/audit/retry', { id: row.id });
		if (data.code === 1000) {
			ElMessage.success('已提交重新审核');
			loadData();
		} else {
			ElMessage.error(data.message || '操作失败');
		}
	} catch {
		// 取消
	}
}

// 待处理订单 → 开始审核（复用 retry 接口，后端会自动匹配 Agent）
async function handleStartAudit(row: AuditOrder) {
	try {
		await ElMessageBox.confirm('确定要开始审核该订单吗？', '开始审核');
		const data = await apiPost('/admin/audit/audit/retry', { id: row.id });
		if (data.code === 1000) {
			ElMessage.success('已提交审核');
			loadData();
		} else {
			ElMessage.error(data.message || '操作失败');
		}
	} catch {
		// 取消
	}
}

// 人工复审
function handleManual(row: AuditOrder, status: 'approved' | 'rejected') {
	manualDialog.orderId = row.id;
	manualDialog.status = status;
	manualDialog.remark = '';
	manualDialog.visible = true;
}

async function submitManual() {
	try {
		const data = await apiPost('/admin/audit/audit/manual', {
			id: manualDialog.orderId,
			status: manualDialog.status,
			remark: manualDialog.remark
		});
		if (data.code === 1000) {
			ElMessage.success('复审完成');
			manualDialog.visible = false;
			loadData();
		} else {
			ElMessage.error(data.message || '操作失败');
		}
	} catch {
		ElMessage.error('操作失败');
	}
}

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

<style lang="scss" scoped>
.audit-orders {
	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;
	}
}

.text-muted {
	color: var(--el-text-color-placeholder);
}
</style>
