<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<!-- 余额信息卡片 -->
			<el-row :gutter="20" class="mb20">
				<el-col :span="6" v-for="item in balanceCards" :key="item.key">
					<el-card shadow="hover" class="balance-card">
						<div class="balance-item">
							<div class="balance-label">{{ item.label }}</div>
							<div class="balance-value">¥{{ formatAmount(balanceData[item.key]) }}</div>
						</div>
					</el-card>
				</el-col>
			</el-row>

			<!-- 搜索表单 -->
			<el-row class="ml10" v-show="showSearch">
				<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef">
					<el-form-item label="订单号" prop="query">
						<el-input placeholder="请输入订单号" style="max-width: 180px" v-model="state.queryForm.query" clearable />
					</el-form-item>
					<el-form-item label="订单类型" prop="orderFlowType">
						<el-select v-model="state.queryForm.orderFlowType" placeholder="请选择订单类型" style="max-width: 180px" clearable>
							<el-option label="支付订单" value="PAY" />
							<el-option label="提现订单" value="WITHDRAW" />
						</el-select>
					</el-form-item>
					<el-form-item label="订单创建时间" prop="orderCreateTime">
						<el-date-picker
							v-model="state.queryForm.orderCreateTime"
							type="datetimerange"
							range-separator="至"
							start-placeholder="开始时间"
							end-placeholder="结束时间"
							style="max-width: 360px"
							clearable
						/>
					</el-form-item>
					<el-form-item label="支付时间" prop="payTime">
						<el-date-picker
							v-model="state.queryForm.payTime"
							type="datetimerange"
							range-separator="至"
							start-placeholder="开始时间"
							end-placeholder="结束时间"
							style="max-width: 360px"
							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-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="beforeAmount" show-overflow-tooltip>
					<template #default="scope">
						<span>¥{{ scope.row.beforeAmount ? scope.row.beforeAmount.toFixed(2) : '0.00' }}</span>
					</template>
				</el-table-column>
				<el-table-column label="变更金额" prop="operationAmount" show-overflow-tooltip>
					<template #default="scope">
						<span :class="scope.row.amountType === 'ADD' ? 'amount-add' : 'amount-sub'">
							{{ scope.row.amountType === 'ADD' ? '+' : '-' }} ¥{{ scope.row.operationAmount ? scope.row.operationAmount.toFixed(2) : '0.00' }}
						</span>
					</template>
				</el-table-column>
				<el-table-column label="变更后余额" prop="afterAmount" show-overflow-tooltip>
					<template #default="scope">
						<span>¥{{ scope.row.afterAmount ? scope.row.afterAmount.toFixed(2) : '0.00' }}</span>
					</template>
				</el-table-column>
				<el-table-column label="订单类型" prop="orderType" show-overflow-tooltip align="center">
					<template #default="scope">
						<el-tag :type="orderTypeMap[scope.row.orderType]?.type || 'info'" size="small">
							{{ orderTypeMap[scope.row.orderType]?.label || '--' }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="业务订单" prop="orderNo" show-overflow-tooltip width="200">
					<template #default="scope">
						{{ scope.row.orderNo || '--' }}
					</template>
				</el-table-column>
				<el-table-column label="订单金额" prop="orderAmount" show-overflow-tooltip>
					<template #default="scope">
						<span class="amount-value">¥{{ scope.row.orderAmount ? scope.row.orderAmount.toFixed(2) : '0.00' }}</span>
					</template>
				</el-table-column>
				<!-- <el-table-column label="手续费" prop="feeAmount" show-overflow-tooltip>
					<template #default="scope">
						<span class="amount-value">¥{{ calculateFee(scope.row) }}</span>
					</template>
				</el-table-column> -->
				<el-table-column label="创建时间" prop="payTime" show-overflow-tooltip width="180">
					<template #default="scope">
						{{ scope.row.payTime || scope.row.orderCreateTime || '--' }}
					</template>
				</el-table-column>
			</el-table>
			<pagination @current-change="currentChangeHandle" @size-change="sizeChangeHandle" v-bind="state.pagination" />
		</div>
	</div>
</template>

<script lang="ts" name="settlementFundFlow" setup>
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchFundFlowList, getMerchantBalance } from '/@/api/settlement';

// 余额卡片配置
const balanceCards = [
	{ key: 'totalUseAmount', label: '可用余额' },
	{ key: 'totalAmount', label: '总金额' },
	{ key: 'freezeAmount', label: '总冻结金额' },
	{ key: 'withdrawnAmount', label: '总提现金额' },
];

// 余额数据
const balanceData = ref({
	totalAmount: 0,
	totalUseAmount: 0,
	freezeAmount: 0,
	withdrawnAmount: 0,
	withdrawnTotalAmount: 0,
});

// 订单类型映射
const orderTypeMap: Record<string, { label: string; type: any }> = {
	PAY: { label: '支付订单', type: 'success' },
	WITHDRAW: { label: '提现订单', type: 'warning' },
};

// 定义变量内容
const queryRef = ref();
const showSearch = ref(true);
const selectObjs = ref([]);
const multiple = ref(true);

// 定义表格查询、变更
const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {
		query: '',
		orderFlowType: '',
		walletType: 'USE', // 默认传递可用金额
		orderCreateTime: '',
		payTime: '',
	},
	pageList: fetchFundFlowList,
	createdIsNeed: false,
});

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

// 加载余额数据
const loadBalance = async () => {
	try {
		const res = await getMerchantBalance();
		if (res.code === 0 && res.data) {
			balanceData.value = res.data;
		}
	} catch (err) {
		// 加载余额数据失败
	}
};

// 格式化金额
const formatAmount = (amount: number) => {
	return amount ? amount.toFixed(2) : '0.00';
};

// 重置查询
const resetQuery = () => {
	queryRef.value?.resetFields();
	state.queryForm = {
		query: '',
		orderFlowType: '',
		walletType: 'USE', // 重置时也保持默认值为可用金额
		orderCreateTime: '',
		payTime: '',
	};
	getDataList();
};

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

// 页面加载时获取数据
onMounted(() => {
	loadBalance();
	getDataList();
});

// 页面激活时刷新数据（用于 keep-alive 缓存的页面）
onActivated(() => {
	loadBalance();
	getDataList();
});
</script>

<style scoped lang="scss">
.balance-card {
	.balance-item {
		text-align: center;
		padding: 10px 0;

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

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

.amount-value {
	font-size: 14px;
	font-weight: bold;
	color: #f56c6c;
}

.amount-add {
	font-size: 14px;
	font-weight: bold;
	color: #67c23a;
}

.amount-sub {
	font-size: 14px;
	font-weight: bold;
	color: #f56c6c;
}
</style>
