<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row class="ml10" v-show="showSearch">
				<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef">
					<el-form-item label="商户订单号" prop="mchOrderNo">
						<el-input placeholder="请输入商户订单号" style="max-width: 180px" v-model="state.queryForm.mchOrderNo" clearable />
					</el-form-item>
					<el-form-item label="平台订单号" prop="transactionId">
						<el-input placeholder="请输入平台订单号" style="max-width: 180px" v-model="state.queryForm.transactionId" clearable />
					</el-form-item>
					<el-form-item label="订单状态" prop="orderStatus">
						<el-select v-model="state.queryForm.orderStatus" placeholder="请选择订单状态" style="max-width: 180px" clearable>
							<el-option label="创建订单" value="CREATE_ORDER" />
							<el-option label="支付成功" value="PAY_SUCCESS" />
							<el-option label="支付失败" value="PAY_FAIL" />
							<el-option label="取消订单" value="CANCEL_ORDER" />
							<el-option label="支付超时" value="PAY_TIMEOUT" />
						</el-select>
					</el-form-item>
					<el-form-item label="支付通道" prop="paymentChannelId">
						<el-input placeholder="请输入支付通道ID" style="max-width: 180px" v-model="state.queryForm.paymentChannelId" clearable />
					</el-form-item>
					<el-form-item>
						<el-button @click="getDataList" icon="search" type="primary">查询</el-button>
						<el-button @click="resetQuery" icon="Refresh">重置</el-button>
					</el-form-item>
				</el-form>
			</el-row>
			<el-row>
				<div class="mb8" style="width: 100%">
					<right-toolbar
						@queryTable="getDataList"
						class="ml10"
						style="float: right; margin-right: 20px"
						v-model:showSearch="showSearch"
					></right-toolbar>
				</div>
			</el-row>

			<!-- 统计信息卡片 -->
			<el-row :gutter="20" class="mb20" v-if="statistics">
				<el-col :span="6">
					<el-card shadow="hover">
						<div class="statistic-item">
							<div class="statistic-label">提交订单数</div>
							<div class="statistic-value">{{ statistics.numberOrders || 0 }}</div>
						</div>
					</el-card>
				</el-col>
				<el-col :span="6">
					<el-card shadow="hover">
						<div class="statistic-item">
							<div class="statistic-label">订单总金额</div>
							<div class="statistic-value">¥{{ (statistics.totalOrderAmount || 0).toFixed(2) }}</div>
						</div>
					</el-card>
				</el-col>
				<el-col :span="6">
					<el-card shadow="hover">
						<div class="statistic-item">
							<div class="statistic-label">已付订单数</div>
							<div class="statistic-value success">{{ statistics.paidOrders || 0 }}</div>
						</div>
					</el-card>
				</el-col>
				<el-col :span="6">
					<el-card shadow="hover">
						<div class="statistic-item">
							<div class="statistic-label">已付总金额</div>
							<div class="statistic-value success">¥{{ (statistics.totalAmountPaid || 0).toFixed(2) }}</div>
						</div>
					</el-card>
				</el-col>
			</el-row>

			<el-table
				:data="state.dataList"
				@selection-change="handleSelectionChange"
				@sort-change="sortChangeHandle"
				style="width: 100%"
				v-loading="state.loading"
				border
				:cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle"
			>
				<el-table-column align="center" type="selection" width="40" />
				<el-table-column label="商户订单号" prop="mchOrderNo" show-overflow-tooltip />
				<el-table-column label="平台订单号" prop="transactionId" show-overflow-tooltip />
				<el-table-column label="通道编码" prop="paymentChannelId" show-overflow-tooltip />
				<el-table-column label="金额" prop="amount" show-overflow-tooltip>
					<template #default="scope">
						<span style="color: #f56c6c; font-weight: bold">¥{{ scope.row.amount ? scope.row.amount.toFixed(2) : '0.00' }}</span>
					</template>
				</el-table-column>
				<el-table-column label="订单状态" prop="orderStatus" show-overflow-tooltip>
					<template #default="scope">
						<el-tag :type="orderStatusMap[scope.row.orderStatus]?.type || 'info'" size="small">
							{{ orderStatusMap[scope.row.orderStatus]?.label || scope.row.orderStatus }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作">
					<template #default="scope">
						<!-- <el-button icon="View" @click="handleView(scope.row)" text type="primary" size="small">查看</el-button> -->
						<el-button icon="Document" @click="handleNotifyLog(scope.row)" text type="warning" size="small">回调日志</el-button>
					</template>
				</el-table-column>
			</el-table>
			<pagination @current-change="currentChangeHandle" @size-change="sizeChangeHandle" v-bind="state.pagination" />
		</div>

		<!-- 回调日志弹窗 -->
		<notify-log-dialog ref="notifyLogDialogRef" />
	</div>
</template>

<script lang="ts" name="orderPayOrder" setup>
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchPayOrderList, fetchPayOrderStatistics } from '/@/api/order';
import { useMessage } from '/@/hooks/message';

// 引入组件
const NotifyLogDialog = defineAsyncComponent(() => import('./notifyLog.vue'));

// 订单状态映射
const orderStatusMap: Record<string, { label: string; type: any }> = {
	CREATE_ORDER: { label: '创建订单', type: 'info' },
	PAY_SUCCESS: { label: '支付成功', type: 'success' },
	PAY_FAIL: { label: '支付失败', type: 'danger' },
	CANCEL_ORDER: { label: '取消订单', type: 'warning' },
	PAY_TIMEOUT: { label: '支付超时', type: 'info' },
};

// 定义变量内容
const notifyLogDialogRef = ref();
const queryRef = ref();
const showSearch = ref(true);
const selectObjs = ref([]);
const multiple = ref(true);
const statistics = ref<any>(null);

// 定义表格查询、变更
const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {
		mchOrderNo: '',
		transactionId: '',
		orderStatus: '',
		paymentChannelId: '',
	},
	pageList: fetchPayOrderList,
	descs: ['create_time'],
	createdIsNeed: false, // 禁用自动加载，由 getDataListWithStats 手动调用
});

const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, tableStyle } = useTable(state);

// 加载统计数据
const loadStatistics = async () => {
	try {
		const res = await fetchPayOrderStatistics(state.queryForm);
		statistics.value = res.data;
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};

// 重写 getDataList，同时加载统计数据
const originalGetDataList = getDataList;
const getDataListWithStats = async (reload = true) => {
	await originalGetDataList(reload);
	await loadStatistics();
};

// 重置查询
const resetQuery = () => {
	queryRef.value?.resetFields();
	getDataListWithStats();
};

// 多选事件
const handleSelectionChange = (objs: any) => {
	selectObjs.value = objs.map((val: any) => val.id);
	multiple.value = !objs.length;
};

// 查看回调日志
const handleNotifyLog = (row: any) => {
	notifyLogDialogRef.value.openDialog(row.appId, row.id);
};

// 初始化加载数据
onMounted(() => {
	getDataListWithStats();
});
</script>

<style scoped>
.statistic-item {
	text-align: center;
	padding: 10px 0;
}

.statistic-label {
	font-size: 14px;
	color: #909399;
	margin-bottom: 8px;
}

.statistic-value {
	font-size: 24px;
	font-weight: bold;
	color: #303133;
}

.statistic-value.success {
	color: #67c23a;
}
</style>
