<template>
	<el-card shadow="never" class="dimension-panel">
		<template #header>
			<div style="display: flex; justify-content: space-between; align-items: center">
				<div style="display: flex; align-items: center; gap: 12px">
					<span style="font-weight: 600">数据明细</span>
					<el-select v-model="groupBy" style="width: 140px" @change="loadData">
						<el-option label="按产品" value="product" />
						<el-option label="按门店" value="dealer" />
						<el-option label="按车企" value="oem" />
						<el-option label="按保险公司" value="insurance" />
					</el-select>
				</div>
				<el-button type="primary" plain size="small" @click="handleExport">
					导出Excel
				</el-button>
			</div>
		</template>
		<el-table :data="list" stripe size="small" max-height="500" :default-sort="{ prop: 'orderCount', order: 'descending' }">
			<el-table-column prop="name" :label="groupLabel" min-width="160" show-overflow-tooltip />
			<el-table-column prop="orderCount" label="订单数" width="90" sortable />
			<el-table-column prop="approvedCount" label="通过" width="80" sortable />
			<el-table-column prop="rejectedCount" label="驳回" width="80" sortable />
			<el-table-column prop="passRate" label="通过率" width="90" sortable>
				<template #default="{ row }">{{ row.passRate }}%</template>
			</el-table-column>
			<el-table-column prop="totalPolicyFee" label="保费合计" width="120" sortable>
				<template #default="{ row }">¥{{ (row.totalPolicyFee || 0).toLocaleString() }}</template>
			</el-table-column>
			<el-table-column prop="avgDuration" label="平均耗时" width="100" sortable>
				<template #default="{ row }">{{ formatDuration(row.avgDuration) }}</template>
			</el-table-column>
		</el-table>
	</el-card>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { useBase } from '/$/base';
import { config } from '/@/config';
import { export_json_to_excel } from '/@/plugins/excel/utils/index';
import type { DimensionStatItem, StatsQuery } from '../types/index.d';

const props = defineProps<{ query: StatsQuery }>();
const { user } = useBase();

const groupBy = ref('product');
const list = ref<DimensionStatItem[]>([]);

const apiMap: Record<string, string> = {
	product: 'statsByProduct',
	dealer: 'statsByDealer',
	oem: 'statsByOem',
	insurance: 'statsByInsurance',
};

const groupLabel = computed(() => {
	const map: Record<string, string> = { product: '产品', dealer: '门店', oem: '车企', insurance: '保险公司' };
	return map[groupBy.value] || '名称';
});

async function loadData() {
	try {
		const api = apiMap[groupBy.value];
		const resp = await fetch(`${config.baseUrl}/admin/audit/audit/${api}`, {
			method: 'POST',
			headers: { 'Content-Type': 'application/json', Authorization: user.token || '' },
			body: JSON.stringify(props.query),
		});
		const data = await resp.json();
		list.value = data.code === 1000 ? (data.data || []) : [];
	} catch {
		ElMessage.error('加载维度数据失败');
	}
}

watch(() => props.query, () => loadData(), { deep: true });
onMounted(() => loadData());

function formatDuration(ms: number) {
	if (!ms) return '-';
	if (ms < 1000) return ms + 'ms';
	return (ms / 1000).toFixed(1) + 's';
}

function handleExport() {
	if (list.value.length === 0) {
		ElMessage.warning('暂无数据可导出');
		return;
	}
	const header = ['名称', '订单数', '通过', '驳回', '通过率(%)', '保费合计', '销售额合计', '平均耗时(ms)'];
	const data = list.value.map(r => [
		r.name, r.orderCount, r.approvedCount, r.rejectedCount,
		r.passRate, r.totalPolicyFee, r.totalFee, r.avgDuration,
	]);
	export_json_to_excel({
		header,
		data,
		filename: `审核统计_按${groupLabel.value}_${new Date().toISOString().slice(0, 10)}`,
	});
}

defineExpose({ loadData });
</script>
