<template>
	<div class="audit-workbench" v-loading="loading">
		<!-- 顶部状态条 -->
		<div class="status-bar" v-if="order">
			<div class="status-bar__left">
				<el-button :icon="ArrowLeft" text @click="router.back()">返回</el-button>
				<span class="status-bar__order-no">{{ order.orderNo }}</span>
				<el-tag size="small" :type="order.orderType === 'insure' ? undefined : 'warning'">
					{{ order.orderType === 'insure' ? '投保' : '理赔' }}
				</el-tag>
				<span class="status-bar__status" :class="'is-' + order.status">
					<span v-if="order.status === 'processing'" class="pulse-dot"></span>
					{{ statusLabel(order.status) }}
				</span>
				<span v-if="order.duration != null" class="status-bar__duration">
					{{ (order.duration / 1000).toFixed(1) }}s
				</span>
			</div>
			<div class="status-bar__right">
				<el-button
					v-if="['failed', 'rejected'].includes(order.status)"
					type="warning"
					size="small"
					@click="handleRetry"
				>
					重新审核
				</el-button>
			</div>
		</div>

		<!-- 主体：左右分栏 -->
		<div class="workbench-body" v-if="order">
			<!-- 左侧面板 -->
			<div class="left-panel">
				<!-- 审核结论 -->
				<div class="tech-card conclusion-card">
					<div class="card-title">审核结论</div>
					<template v-if="order.auditResult">
						<div class="conclusion-card__decision" :class="'is-' + order.auditResult.decision">
							{{ decisionLabel(order.auditResult.decision) }}
						</div>
						<div v-if="order.auditResult.score != null" class="score-ring-wrap">
							<div
								class="score-ring"
								:style="{ '--score': order.auditResult.score, '--color': scoreColor }"
							>
								<span class="score-ring__val">{{ order.auditResult.score }}</span>
								<span class="score-ring__label">分</span>
							</div>
						</div>
						<div class="conclusion-card__meta">
							<el-tag size="small" type="info">
								{{ order.auditResult.reviewType === 'manual' ? '人工复审' : 'AI审核' }}
							</el-tag>
						</div>
						<div v-if="order.auditResult.reason" class="conclusion-card__reason">
							{{ order.auditResult.reason }}
						</div>
					</template>
					<div v-else class="conclusion-card__pending">
						<el-icon :size="32" color="#c0c4cc" class="is-loading"><Loading /></el-icon>
						<span>等待审核中...</span>
					</div>
				</div>

				<!-- 风险雷达 -->
				<div class="tech-card">
					<div class="card-title">风险雷达</div>
					<RiskRadar :dimensions="dimensions" :size="280" />
				</div>

				<!-- 人工复审操作区 -->
				<div v-if="order.status === 'manual_review'" class="tech-card manual-review-card">
					<div class="card-title">人工复审</div>
					<el-form label-position="top" :model="reviewForm">
						<el-form-item label="审核决定">
							<el-radio-group v-model="reviewForm.decision">
								<el-radio value="approved">通过</el-radio>
								<el-radio value="rejected">驳回</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item v-if="reviewForm.decision === 'rejected'" label="快捷驳回原因">
							<el-checkbox-group v-model="reviewForm.quickReasons">
								<el-checkbox v-for="r in quickRejectReasons" :key="r" :label="r" :value="r" />
							</el-checkbox-group>
						</el-form-item>
						<el-form-item label="审核意见">
							<el-input
								v-model="reviewForm.remark"
								type="textarea"
								:rows="3"
								placeholder="请输入审核意见..."
							/>
						</el-form-item>
						<el-button
							type="primary"
							:loading="submitting"
							:disabled="!reviewForm.decision"
							style="width: 100%"
							@click="handleManualReview"
						>
							确认提交
						</el-button>
					</el-form>
				</div>
			</div>

			<!-- 右侧面板 -->
			<div class="right-panel">
				<el-tabs v-model="activeTab" class="right-tabs" :before-leave="beforeTabLeave">
					<el-tab-pane label="对话记录" name="chat" />
					<el-tab-pane label="订单数据" name="data">
						<div class="order-data-tab">
							<!-- 主机厂 & 产品 -->
							<el-descriptions title="主机厂 & 产品信息" :column="3" border size="small">
								<el-descriptions-item label="主机厂">{{ d.oemName || d.brandName || '-' }}</el-descriptions-item>
								<el-descriptions-item label="产品名称">{{ d.productName || '-' }}</el-descriptions-item>
								<el-descriptions-item label="产品编号">{{ d.productNo || '-' }}</el-descriptions-item>
								<el-descriptions-item label="保费">{{ d.policyFee ? '¥' + d.policyFee : '-' }}</el-descriptions-item>
								<el-descriptions-item label="销售价格">{{ d.salesPrice ? '¥' + d.salesPrice : (d.vehiclePrice ? '¥' + d.vehiclePrice : '-') }}</el-descriptions-item>
								<el-descriptions-item label="保障时长">{{ d.duration || '-' }}</el-descriptions-item>
								<el-descriptions-item label="套餐类型">{{ d.packageType || '-' }}</el-descriptions-item>
								<el-descriptions-item label="保险公司">{{ d.insuranceCompany || '-' }}</el-descriptions-item>
							</el-descriptions>
							<!-- 车主信息 -->
							<el-descriptions title="车主信息" :column="3" border size="small" style="margin-top:16px">
								<el-descriptions-item label="车主姓名">{{ d.cardName || '-' }}</el-descriptions-item>
								<el-descriptions-item label="身份证号">{{ d.cardNumber || '-' }}</el-descriptions-item>
								<el-descriptions-item label="手机号">{{ d.phone || '-' }}</el-descriptions-item>
								<el-descriptions-item label="性别">{{ d.sex || '-' }}</el-descriptions-item>
								<el-descriptions-item label="邮箱">{{ d.email || '-' }}</el-descriptions-item>
								<el-descriptions-item label="车主(行驶证)">{{ d.carHost || '-' }}</el-descriptions-item>
							</el-descriptions>
							<!-- 车辆信息 -->
							<el-descriptions title="车辆信息" :column="3" border size="small" style="margin-top:16px">
								<el-descriptions-item label="车架号(VIN)">{{ d.carFrame || '-' }}</el-descriptions-item>
								<el-descriptions-item label="车牌号">{{ d.carPlate || '-' }}</el-descriptions-item>
								<el-descriptions-item label="车辆类型">{{ d.carType === '0' ? '新车' : d.carType === '1' ? '在用车' : d.carType || '-' }}</el-descriptions-item>
								<el-descriptions-item label="品牌">{{ d.brandName || '-' }}</el-descriptions-item>
								<el-descriptions-item label="车型">{{ d.modelName || '-' }}</el-descriptions-item>
								<el-descriptions-item label="配置">{{ d.configName || '-' }}</el-descriptions-item>
								<el-descriptions-item label="展示名称">{{ d.carShowName || '-' }}</el-descriptions-item>
								<el-descriptions-item label="品牌型号">{{ d.brandModel || '-' }}</el-descriptions-item>
								<el-descriptions-item label="动力类型">{{ d.carPower || '-' }}</el-descriptions-item>
								<el-descriptions-item label="购车时间">{{ formatTime(d.carPurchaseTime) }}</el-descriptions-item>
								<el-descriptions-item label="购车价格">{{ d.vehiclePrice ? '¥' + d.vehiclePrice : '-' }}</el-descriptions-item>
								<el-descriptions-item label="行驶里程">{{ d.kilometers || d.mileage || '-' }}</el-descriptions-item>
							</el-descriptions>
							<!-- 录单信息 -->
							<el-descriptions title="录单信息" :column="3" border size="small" style="margin-top:16px">
								<el-descriptions-item label="录单机构">{{ d.factroyName || '-' }}</el-descriptions-item>
								<el-descriptions-item label="经销商代码">{{ d.dealerCode || d.dotCode || '-' }}</el-descriptions-item>
								<el-descriptions-item label="录单人">{{ d.creator || '-' }}</el-descriptions-item>
								<el-descriptions-item label="录单人手机">{{ d.createPhone || '-' }}</el-descriptions-item>
								<el-descriptions-item label="第三方渠道">{{ d.thirdParty || '-' }}</el-descriptions-item>
								<el-descriptions-item label="录单时间">{{ formatTime(d.createTime) }}</el-descriptions-item>
							</el-descriptions>
							<!-- 保单信息 -->
							<el-descriptions v-if="d.policyNo || d.guaranteePdf" title="保单信息" :column="3" border size="small" style="margin-top:16px">
								<el-descriptions-item label="保单号">{{ d.policyNo || '-' }}</el-descriptions-item>
								<el-descriptions-item label="生效日期">{{ formatTime(d.serviceStart) }}</el-descriptions-item>
								<el-descriptions-item label="服务期限">{{ d.serviceTime || '-' }}</el-descriptions-item>
								<el-descriptions-item label="长安订单号">{{ d.changAnNum || '-' }}</el-descriptions-item>
							</el-descriptions>
							<!-- 审核图片 -->
							<div v-if="auditImages.length > 0" style="margin-top:16px">
								<div style="font-weight:600;font-size:14px;margin-bottom:10px">审核图片</div>
								<div class="audit-images">
									<div v-for="img in auditImages" :key="img.label" class="audit-images__item">
										<div class="audit-images__label">{{ img.label }}</div>
										<el-image
											:src="img.url"
											:preview-src-list="auditImages.map(i => i.url)"
											:initial-index="auditImages.indexOf(img)"
											fit="cover"
											class="audit-images__img"
										>
											<template #error>
												<div class="audit-images__error">加载失败</div>
											</template>
										</el-image>
									</div>
								</div>
							</div>
							<!-- TYCM审核信息 -->
							<el-descriptions v-if="d.auditUserName || d.auditRemark" title="TYCM原始审核信息" :column="3" border size="small" style="margin-top:16px">
								<el-descriptions-item label="审核人">{{ d.auditUserName || '-' }}</el-descriptions-item>
								<el-descriptions-item label="是否修改过">{{ d.isAuditChange || '-' }}</el-descriptions-item>
								<el-descriptions-item label="审核备注" :span="3">{{ d.auditRemark || d.remarks || '-' }}</el-descriptions-item>
							</el-descriptions>
						</div>
					</el-tab-pane>
					<el-tab-pane label="原始数据" name="raw">
						<div class="raw-data-tab">
							<el-button size="small" @click="copyRawJson" style="margin-bottom: 12px">
								复制JSON
							</el-button>
							<pre class="json-output">{{ formatJson(order.inputData) }}</pre>
						</div>
					</el-tab-pane>
				</el-tabs>
			</div>
		</div>

		<el-empty v-if="!loading && !order" description="未找到该审核订单" />
	</div>
</template>

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

import { ref, computed, onMounted, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ArrowLeft, Loading } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useBase } from '/$/base';
import { config } from '/@/config';
import type { AuditOrder, AuditOrderDetail } from '../types/index.d';
import RiskRadar from '../components/risk-radar.vue';
import { useRiskScore } from '../composables/useRiskScore';

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

const loading = ref(false);
const order = ref<AuditOrder | null>(null);
const details = ref<AuditOrderDetail[]>([]);
const activeTab = ref('data');
const submitting = ref(false);

const quickRejectReasons = ['证件不清晰', '信息不一致', '疑似伪造', '超出保障范围'];

const reviewForm = reactive({
	decision: '' as 'approved' | 'rejected' | '',
	quickReasons: [] as string[],
	remark: '',
});

const { dimensions } = useRiskScore(details);

const scoreColor = computed(() => {
	const s = order.value?.auditScore ?? order.value?.auditResult?.score ?? 0;
	if (s >= 80) return '#67c23a';
	if (s >= 60) return '#e6a23c';
	return '#f56c6c';
});

// 订单数据：优先从宽表真实列读取，图片等低频字段从 inputData 读取
const d = computed(() => {
	const raw = (() => {
		if (!order.value?.inputData) return {};
		if (typeof order.value.inputData === 'string') {
			try { return JSON.parse(order.value.inputData); }
			catch { return {}; }
		}
		return order.value.inputData;
	})();
	const o = order.value || {} as any;
	return {
		...raw,
		// 宽表字段覆盖（优先使用真实列）
		oemName: o.oemName || raw.oemName,
		productName: o.productName || raw.productName,
		productNo: o.productNo || raw.productNo,
		salesPrice: o.salesPrice || raw.salesPrice,
		policyFee: o.policyFee || raw.policyFee || raw.fee,
		insuranceCompany: o.insuranceCompany || raw.insuranceCompany,
		dealerCode: o.dealerCode || raw.dealerCode || raw.dotCode,
		factroyName: o.factoryName || raw.factroyName,
		creator: o.creator || raw.creator,
		createPhone: o.createPhone || raw.createPhone,
		orderSource: o.orderSource || raw.orderSource,
		cardName: o.cardName || raw.cardName,
		cardNumber: o.cardNumber || raw.cardNumber,
		phone: o.phone || raw.phone,
		carHost: o.carHost || raw.carHost,
		carFrame: o.carFrame || raw.carFrame,
		carPlate: o.carPlate || raw.carPlate,
		brandName: o.brandName || raw.brandName,
		modelName: o.modelName || raw.modelName,
		vehiclePrice: o.vehiclePrice || raw.vehiclePrice,
		policyNo: o.policyNo || raw.policyNo,
		carPurchaseTime: o.carPurchaseTime || raw.carPurchaseTime,
		serviceStart: o.serviceStart || raw.serviceStart,
	};
});

const auditImages = computed(() => {
	const data = d.value;
	const imgs: { label: string; url: string }[] = [];
	const fields: [string, string][] = [
		['cardUrl', '身份证照片'], ['carBill', '购车发票'], ['licensePre', '行驶证'],
		['leftUrl', '左前45°照片'], ['rightUrl', '右后45°照片'], ['frameUrl', '车架号照片'],
		['payPicture', '支付凭证'], ['addPic', '补充图片'],
	];
	for (const [key, label] of fields) {
		if (data[key]) imgs.push({ label, url: data[key] });
	}
	return imgs;
});

function formatTime(val: any): string {
	if (!val) return '-';
	if (typeof val === 'number') return new Date(val).toLocaleString('zh-CN');
	return String(val);
}

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

function decisionLabel(decision: string) {
	const map: Record<string, string> = {
		approved: '审核通过', rejected: '审核驳回', manual_review: '建议转人工',
	};
	return map[decision] || decision;
}

function formatJson(data: any) {
	if (!data) return '无数据';
	if (typeof data === 'string') {
		try { return JSON.stringify(JSON.parse(data), null, 2); }
		catch { return data; }
	}
	return JSON.stringify(data, null, 2);
}

function copyRawJson() {
	const text = formatJson(order.value?.inputData);
	navigator.clipboard.writeText(text).then(
		() => ElMessage.success('已复制'),
		() => ElMessage.error('复制失败')
	);
}

function openAgentConversation() {
	const currentOrder = order.value;
	if (!currentOrder?.sessionId) {
		ElMessage.warning('该审核订单暂无关联会话');
		return;
	}
	if (!currentOrder.agentId) {
		ElMessage.warning('该审核订单暂无关联 Agent');
		return;
	}
	router.push({
		path: '/agent/chat',
		query: {
			agentId: String(currentOrder.agentId),
			sessionId: currentOrder.sessionId,
		},
	});
}

function beforeTabLeave(name: string | number) {
	if (name !== 'chat') return true;
	openAgentConversation();
	return false;
}

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 apiGet(url: string, params: Record<string, any> = {}) {
	const qs = new URLSearchParams(params).toString();
	const resp = await fetch(`${config.baseUrl}${url}${qs ? '?' + qs : ''}`, {
		headers: { Authorization: user.token || '' },
	});
	return resp.json();
}

async function loadDetail() {
	const id = Number(route.query.id);
	if (!id) return;
	loading.value = true;
	try {
		const [infoData, detailData] = await Promise.all([
			apiGet('/admin/audit/audit/info', { id }),
			apiPost('/admin/audit/audit/detail', { id }),
		]);
		if (infoData.code === 1000 && infoData.data) {
			order.value = infoData.data;
		}
		if (detailData.code === 1000 && detailData.data?.details) {
			details.value = detailData.data.details;
		}
	} catch {
		ElMessage.error('加载审核详情失败');
	} finally {
		loading.value = false;
	}
}

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

async function handleManualReview() {
	if (!reviewForm.decision) return;
	const reasons = [...reviewForm.quickReasons];
	if (reviewForm.remark) reasons.push(reviewForm.remark);
	const remark = reasons.join('；') || (reviewForm.decision === 'approved' ? '人工审核通过' : '人工审核驳回');

	try {
		await ElMessageBox.confirm(
			`确定${reviewForm.decision === 'approved' ? '通过' : '驳回'}该订单吗？`,
			'人工复审确认'
		);
		submitting.value = true;
		const data = await apiPost('/admin/audit/audit/manual', {
			id: order.value?.id,
			status: reviewForm.decision,
			remark,
		});
		if (data.code === 1000) {
			ElMessage.success('复审提交成功');
			loadDetail();
		} else {
			ElMessage.error(data.message || '操作失败');
		}
	} catch { /* 取消 */ }
	finally { submitting.value = false; }
}

onMounted(() => loadDetail());
</script>

<style lang="scss" scoped>
.audit-workbench {
	height: 100%;
	display: flex;
	flex-direction: column;
	background: #f0f2f5;
}

/* 顶部状态条 */
.status-bar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 12px 20px;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: #fff;
	flex-shrink: 0;

	&__left {
		display: flex;
		align-items: center;
		gap: 12px;
	}

	&__order-no {
		font-size: 16px;
		font-weight: 600;
		letter-spacing: 0.5px;
	}

	&__status {
		display: inline-flex;
		align-items: center;
		gap: 6px;
		padding: 2px 10px;
		border-radius: 12px;
		font-size: 13px;
		font-weight: 500;

		&.is-approved { background: rgba(103, 194, 58, 0.25); }
		&.is-rejected { background: rgba(245, 108, 108, 0.25); }
		&.is-manual_review { background: rgba(230, 162, 60, 0.25); }
		&.is-processing { background: rgba(255, 255, 255, 0.2); }
		&.is-pending { background: rgba(255, 255, 255, 0.15); }
		&.is-failed { background: rgba(245, 108, 108, 0.25); }
	}

	&__duration {
		font-size: 13px;
		opacity: 0.85;
	}

	:deep(.el-button--text) { color: #fff; }
}

.pulse-dot {
	width: 8px;
	height: 8px;
	border-radius: 50%;
	background: #fff;
	animation: pulse 1.5s infinite;
}

@keyframes pulse {
	0%, 100% { box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.5); }
	50% { box-shadow: 0 0 0 8px rgba(255, 255, 255, 0); }
}

/* 主体布局 */
.workbench-body {
	flex: 1;
	display: flex;
	gap: 16px;
	padding: 16px;
	overflow: hidden;
}

.left-panel {
	width: 380px;
	flex-shrink: 0;
	overflow-y: auto;
	display: flex;
	flex-direction: column;
	gap: 14px;
}

.right-panel {
	flex: 1;
	min-width: 0;
	background: #fff;
	border-radius: 10px;
	overflow: hidden;

	.right-tabs {
		height: 100%;
		display: flex;
		flex-direction: column;

		:deep(.el-tabs__content) {
			flex: 1;
			overflow-y: auto;
			padding: 16px;
		}
		:deep(.el-tabs__header) {
			padding: 0 16px;
			margin: 0;
		}
	}
}

/* 科技感卡片 */
.tech-card {
	background: #fff;
	border-radius: 10px;
	padding: 18px;
	border: 1px solid transparent;
	background-clip: padding-box;
	position: relative;

	&::before {
		content: '';
		position: absolute;
		inset: -1px;
		border-radius: 11px;
		padding: 1px;
		background: linear-gradient(135deg, rgba(102, 126, 234, 0.3), rgba(118, 75, 162, 0.15));
		-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
		-webkit-mask-composite: xor;
		mask-composite: exclude;
		pointer-events: none;
	}
}

.card-title {
	font-size: 14px;
	font-weight: 600;
	color: #303133;
	margin-bottom: 14px;
	padding-left: 10px;
	border-left: 3px solid #667eea;
}

/* 审核结论卡片 */
.conclusion-card {
	text-align: center;

	&__decision {
		font-size: 22px;
		font-weight: 700;
		padding: 8px 24px;
		border-radius: 8px;
		display: inline-block;
		margin-bottom: 14px;

		&.is-approved { background: linear-gradient(135deg, #f0f9eb, #d9f0c7); color: #529b2e; }
		&.is-rejected { background: linear-gradient(135deg, #fef0f0, #fcd5d5); color: #c45656; }
		&.is-manual_review { background: linear-gradient(135deg, #fdf6ec, #f8e3c5); color: #b88230; }
	}

	&__meta { margin: 10px 0; }

	&__reason {
		font-size: 13px;
		color: #606266;
		margin-top: 10px;
		padding: 8px 12px;
		background: #f5f7fa;
		border-radius: 6px;
		text-align: left;
		line-height: 1.6;
	}

	&__pending {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 10px;
		padding: 24px 0;
		color: #c0c4cc;
	}
}

/* 评分圆环 */
.score-ring-wrap {
	display: flex;
	justify-content: center;
	margin: 8px 0;
}

.score-ring {
	width: 80px;
	height: 80px;
	border-radius: 50%;
	background: conic-gradient(var(--color) calc(var(--score) * 3.6deg), #f0f0f0 0);
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	position: relative;

	&::after {
		content: '';
		position: absolute;
		inset: 6px;
		border-radius: 50%;
		background: #fff;
	}

	&__val {
		position: relative;
		z-index: 1;
		font-size: 22px;
		font-weight: 700;
		color: #303133;
		line-height: 1;
	}

	&__label {
		position: relative;
		z-index: 1;
		font-size: 11px;
		color: #909399;
	}
}

/* 人工复审 */
.manual-review-card {
	border-color: #e6a23c;

	&::before {
		background: linear-gradient(135deg, rgba(230, 162, 60, 0.4), rgba(230, 162, 60, 0.1));
	}
}

/* 订单数据Tab */
.order-data-tab {
	padding-bottom: 20px;
}

.audit-images {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
	gap: 14px;

	&__item { text-align: center; }

	&__label {
		font-size: 12px;
		color: #909399;
		margin-bottom: 6px;
	}

	&__img {
		width: 100%;
		height: 140px;
		border-radius: 6px;
		border: 1px solid #ebeef5;
		cursor: pointer;
	}

	&__error {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 140px;
		background: #f5f7fa;
		color: #c0c4cc;
		font-size: 12px;
		border-radius: 6px;
	}
}

/* 原始数据Tab */
.raw-data-tab {
	height: 100%;
}

.json-output {
	background: #f5f7fa;
	padding: 14px;
	border-radius: 6px;
	font-size: 12px;
	line-height: 1.6;
	overflow: auto;
	max-height: calc(100vh - 260px);
	white-space: pre-wrap;
	word-break: break-all;
	margin: 0;
}

</style>
