<template>
  <div class="transactions-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>交易管理</h1>
      <p>查询和管理银行交易记录</p>
    </div>
    
    <!-- 搜索和筛选区域 -->
    <a-card class="filter-card" :bordered="false">
      <a-form layout="inline" :model="filterForm">
        <a-form-item label="交易类型">
          <a-select
            v-model:value="filterForm.type"
            style="width: 150px"
            placeholder="选择交易类型"
            allow-clear
          >
            <a-select-option value="deposit">存款</a-select-option>
            <a-select-option value="withdrawal">取款</a-select-option>
            <a-select-option value="transfer">转账</a-select-option>
            <a-select-option value="payment">支付</a-select-option>
            <a-select-option value="interest">利息</a-select-option>
            <a-select-option value="fee">手续费</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="账户号码">
          <a-input
            v-model:value="filterForm.accountNumber"
            placeholder="输入账户号码"
            style="width: 200px"
            allow-clear
          />
        </a-form-item>
        
        <a-form-item label="交易日期">
          <a-range-picker
            v-model:value="filterForm.dateRange"
            :placeholder="['开始日期', '结束日期']"
            style="width: 300px"
          />
        </a-form-item>
        
        <a-form-item label="金额范围">
          <a-input-number
            v-model:value="filterForm.minAmount"
            placeholder="最小金额"
            style="width: 120px"
            :precision="2"
          />
          <span style="margin: 0 8px;">至</span>
          <a-input-number
            v-model:value="filterForm.maxAmount"
            placeholder="最大金额"
            style="width: 120px"
            :precision="2"
          />
        </a-form-item>
        
        <a-form-item>
          <a-button type="primary" @click="handleSearch">
            <search-outlined /> 搜索
          </a-button>
          <a-button style="margin-left: 8px" @click="resetFilters">
            <reload-outlined /> 重置
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>
    
    <!-- 交易统计卡片 -->
    <!-- <a-row :gutter="[16, 16]" class="stats-cards">
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stat-card">
          <a-statistic
            title="今日交易总数"
            :value="stats.todayCount"
            :loading="statsLoading"
          >
            <template #prefix>
              <transaction-outlined style="color: #1890ff" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stat-card">
          <a-statistic
            title="今日交易总额"
            :value="stats.todayAmount"
            :precision="2"
            :loading="statsLoading"
            :formatter="value => `¥${value}`"
          >
            <template #prefix>
              <dollar-outlined style="color: #52c41a" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stat-card">
          <a-statistic
            title="本月交易总数"
            :value="stats.monthCount"
            :loading="statsLoading"
          >
            <template #prefix>
              <bar-chart-outlined style="color: #fa8c16" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stat-card">
          <a-statistic
            title="本月交易总额"
            :value="stats.monthAmount"
            :precision="2"
            :loading="statsLoading"
            :formatter="value => `¥${value}`"
          >
            <template #prefix>
              <fund-outlined style="color: #722ed1" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row> -->
    
    <!-- 交易表格 -->
    <a-card :bordered="false" class="table-card">
      <template #title>
        <div class="table-title">
          <span>交易记录列表</span>
          <a-button type="primary" @click="exportTransactions">
            <download-outlined /> 导出数据
          </a-button>
        </div>
      </template>
      
      <a-table
        :columns="columns"
        :data-source="transactions"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <!-- 交易类型列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <a-tag :color="getTransactionTypeColor(record.type)">
              {{ getTransactionTypeName(record.type) }}
            </a-tag>
          </template>
          
          <!-- 金额列 -->
          <template v-if="column.key === 'amount'">
            <span :style="{ color: isNegativeTransaction(record.type) ? '#f5222d' : '#52c41a' }">
              {{ isNegativeTransaction(record.type) ? '-' : '+' }}{{ formatCurrency(record.amount) }}
            </span>
          </template>
          
          <!-- 状态列 -->
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusName(record.status) }}
            </a-tag>
          </template>
          
          <!-- 操作列 -->
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="viewTransactionDetail(record)">详情</a>
              <a-divider type="vertical" />
              <a @click="printReceipt(record)">打印凭证</a>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 交易详情对话框 -->
    <a-modal
      v-model:visible="detailModalVisible"
      title="交易详情"
      :footer="null"
      width="700px"
    >
      <template v-if="selectedTransaction">
        <a-descriptions bordered :column="{ xxl: 2, xl: 2, lg: 2, md: 1, sm: 1, xs: 1 }">
          <a-descriptions-item label="交易ID">{{ selectedTransaction.id }}</a-descriptions-item>
          <a-descriptions-item label="交易类型">
            <a-tag :color="getTransactionTypeColor(selectedTransaction.type)">
              {{ getTransactionTypeName(selectedTransaction.type) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="交易金额">
            <span :style="{ color: isNegativeTransaction(selectedTransaction.type) ? '#f5222d' : '#52c41a' }">
              {{ isNegativeTransaction(selectedTransaction.type) ? '-' : '+' }}{{ formatCurrency(selectedTransaction.amount) }}
            </span>
          </a-descriptions-item>
          <a-descriptions-item label="交易状态">
            <a-tag :color="getStatusColor(selectedTransaction.status)">
              {{ getStatusName(selectedTransaction.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="交易时间">{{ selectedTransaction.timestamp }}</a-descriptions-item>
          <a-descriptions-item label="账户号码">{{ selectedTransaction.accountNumber }}</a-descriptions-item>
          <a-descriptions-item label="账户名称">{{ selectedTransaction.accountName }}</a-descriptions-item>
          <a-descriptions-item label="交易渠道">{{ getChannelName(selectedTransaction.channel) }}</a-descriptions-item>
          <a-descriptions-item label="交易描述" :span="2">{{ selectedTransaction.description || '无' }}</a-descriptions-item>
          
          <template v-if="selectedTransaction.type === 'transfer'">
            <a-descriptions-item label="收款账户">{{ selectedTransaction.targetAccountNumber }}</a-descriptions-item>
            <a-descriptions-item label="收款人">{{ selectedTransaction.targetAccountName }}</a-descriptions-item>
          </template>
          
          <a-descriptions-item label="交易备注" :span="2">{{ selectedTransaction.notes || '无' }}</a-descriptions-item>
        </a-descriptions>
        
        <div style="margin-top: 24px;">
          <h3>交易流水</h3>
          <a-timeline>
            <a-timeline-item color="green">
              交易发起 - {{ selectedTransaction.timestamp }}
            </a-timeline-item>
            <a-timeline-item color="blue">
              交易处理 - {{ selectedTransaction.processedTime || '立即处理' }}
            </a-timeline-item>
            <a-timeline-item :color="selectedTransaction.status === 'completed' ? 'green' : 'red'">
              交易{{ selectedTransaction.status === 'completed' ? '完成' : '失败' }} - {{ selectedTransaction.completedTime || selectedTransaction.timestamp }}
            </a-timeline-item>
          </a-timeline>
        </div>
        
        <div style="margin-top: 16px; text-align: right;">
          <a-button @click="printReceipt(selectedTransaction)" style="margin-right: 8px;">
            <printer-outlined /> 打印凭证
          </a-button>
          <a-button @click="detailModalVisible = false">关闭</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { 
  SearchOutlined, 
  ReloadOutlined, 
  DownloadOutlined, 
  TransactionOutlined,
  DollarOutlined,
  BarChartOutlined,
  FundOutlined,
  PrinterOutlined
} from '@ant-design/icons-vue';

export default defineComponent({
  name: 'TransactionsPage',
  components: {
    SearchOutlined,
    ReloadOutlined,
    DownloadOutlined,
    TransactionOutlined,
    DollarOutlined,
    BarChartOutlined,
    FundOutlined,
    PrinterOutlined
  },
  setup() {
    // 表格列定义
    const columns = [
      {
        title: '交易ID',
        dataIndex: 'id',
        key: 'id',
        sorter: true,
      },
      {
        title: '交易类型',
        dataIndex: 'type',
        key: 'type',
        filters: [
          { text: '存款', value: 'deposit' },
          { text: '取款', value: 'withdrawal' },
          { text: '转账', value: 'transfer' },
          { text: '支付', value: 'payment' },
          { text: '利息', value: 'interest' },
          { text: '手续费', value: 'fee' },
        ],
      },
      {
        title: '账户号码',
        dataIndex: 'accountNumber',
        key: 'accountNumber',
        sorter: true,
      },
      {
        title: '账户名称',
        dataIndex: 'accountName',
        key: 'accountName',
        sorter: true,
      },
      {
        title: '金额',
        dataIndex: 'amount',
        key: 'amount',
        sorter: true,
      },
      {
        title: '交易时间',
        dataIndex: 'timestamp',
        key: 'timestamp',
        sorter: true,
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        filters: [
          { text: '已完成', value: 'completed' },
          { text: '处理中', value: 'processing' },
          { text: '失败', value: 'failed' },
        ],
      },
      {
        title: '交易渠道',
        dataIndex: 'channel',
        key: 'channel',
        filters: [
          { text: '柜台', value: 'counter' },
          { text: '网银', value: 'online' },
          { text: '手机银行', value: 'mobile' },
          { text: 'ATM', value: 'atm' },
        ],
      },
      {
        title: '操作',
        key: 'action',
      },
    ];

    // 状态变量
    const transactions = ref([]);
    const loading = ref(false);
    const statsLoading = ref(false);
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showTotal: (total) => `共 ${total} 条记录`,
    });

    // 筛选表单
    const filterForm = reactive({
      type: undefined,
      accountNumber: '',
      dateRange: [],
      minAmount: null,
      maxAmount: null,
    });

    // 统计数据
    const stats = reactive({
      todayCount: 0,
      todayAmount: 0,
      monthCount: 0,
      monthAmount: 0,
    });

    // 交易详情相关
    const detailModalVisible = ref(false);
    const selectedTransaction = ref(null);

    // 获取交易列表
    const fetchTransactions = async (params = {}) => {
      loading.value = true;
      try {
        // 这里应该是实际的API调用
        // const response = await api.getTransactions(params);
        // transactions.value = response.data;
        // pagination.total = response.total;
        
        // 模拟数据
        setTimeout(() => {
          const mockTransactions = [
            { 
              id: 'T20230917001', 
              type: 'deposit', 
              accountNumber: '6225123456789001',
              accountName: '张三储蓄账户',
              amount: 5000.00, 
              timestamp: '2023-09-17 09:30:25',
              processedTime: '2023-09-17 09:30:26',
              completedTime: '2023-09-17 09:30:28',
              status: 'completed',
              channel: 'counter',
              description: '现金存款',
              notes: ''
            },
            { 
              id: 'T20230917002', 
              type: 'withdrawal', 
              accountNumber: '6225123456789002',
              accountName: '李四活期账户',
              amount: 2000.00, 
              timestamp: '2023-09-17 10:15:42',
              processedTime: '2023-09-17 10:15:43',
              completedTime: '2023-09-17 10:15:45',
              status: 'completed',
              channel: 'atm',
              description: 'ATM取款',
              notes: ''
            },
            { 
              id: 'T20230917003', 
              type: 'transfer', 
              accountNumber: '6225123456789001',
              accountName: '张三储蓄账户',
              targetAccountNumber: '6225123456789002',
              targetAccountName: '李四活期账户',
              amount: 3000.00, 
              timestamp: '2023-09-17 11:05:18',
              processedTime: '2023-09-17 11:05:20',
              completedTime: '2023-09-17 11:05:22',
              status: 'completed',
              channel: 'online',
              description: '转账给李四',
              notes: '项目款'
            },
            { 
              id: 'T20230916001', 
              type: 'payment', 
              accountNumber: '6225123456789003',
              accountName: '王五信用卡',
              amount: 1500.00, 
              timestamp: '2023-09-16 14:30:10',
              processedTime: '2023-09-16 14:30:12',
              completedTime: '2023-09-16 14:30:15',
              status: 'completed',
              channel: 'mobile',
              description: '电商购物',
              notes: ''
            },
            { 
              id: 'T20230916002', 
              type: 'interest', 
              accountNumber: '6225123456789001',
              accountName: '张三储蓄账户',
              amount: 125.50, 
              timestamp: '2023-09-16 23:59:59',
              processedTime: '2023-09-16 23:59:59',
              completedTime: '2023-09-16 23:59:59',
              status: 'completed',
              channel: 'system',
              description: '利息结算',
              notes: '月度利息'
            },
            { 
              id: 'T20230915001', 
              type: 'fee', 
              accountNumber: '6225123456789003',
              accountName: '王五信用卡',
              amount: 50.00, 
              timestamp: '2023-09-15 00:00:01',
              processedTime: '2023-09-15 00:00:01',
              completedTime: '2023-09-15 00:00:01',
              status: 'completed',
              channel: 'system',
              description: '年费',
              notes: ''
            },
            { 
              id: 'T20230915002', 
              type: 'transfer', 
              accountNumber: '6225123456789004',
              accountName: '赵六房贷',
              targetAccountNumber: '6225123456789001',
              targetAccountName: '张三储蓄账户',
              amount: 5000.00, 
              timestamp: '2023-09-15 09:45:30',
              processedTime: '2023-09-15 09:45:32',
              status: 'failed',
              channel: 'online',
              description: '转账',
              notes: '余额不足'
            },
          ];
          transactions.value = mockTransactions;
          pagination.total = mockTransactions.length;
          loading.value = false;
        }, 500);
      } catch (error) {
        message.error('获取交易列表失败');
        loading.value = false;
      }
    };

    // 获取统计数据
    const fetchStats = async () => {
      statsLoading.value = true;
      try {
        // 这里应该是实际的API调用
        // const response = await api.getTransactionStats();
        // Object.assign(stats, response.data);
        
        // 模拟数据
        setTimeout(() => {
          stats.todayCount = 15;
          stats.todayAmount = 25000.00;
          stats.monthCount = 342;
          stats.monthAmount = 1250000.00;
          statsLoading.value = false;
        }, 300);
      } catch (error) {
        message.error('获取统计数据失败');
        statsLoading.value = false;
      }
    };

    // 表格变化处理
    const handleTableChange = (pag, filters, sorter) => {
      const params = {
        page: pag.current,
        pageSize: pag.pageSize,
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
      };
      
      pagination.current = pag.current;
      fetchTransactions(params);
    };

    // 搜索处理
    const handleSearch = () => {
      pagination.current = 1;
      
      const params = {
        type: filterForm.type,
        accountNumber: filterForm.accountNumber,
        startDate: filterForm.dateRange?.[0]?.format('YYYY-MM-DD'),
        endDate: filterForm.dateRange?.[1]?.format('YYYY-MM-DD'),
        minAmount: filterForm.minAmount,
        maxAmount: filterForm.maxAmount,
      };
      
      fetchTransactions(params);
    };

    // 重置筛选条件
    const resetFilters = () => {
      filterForm.type = undefined;
      filterForm.accountNumber = '';
      filterForm.dateRange = [];
      filterForm.minAmount = null;
      filterForm.maxAmount = null;
      
      pagination.current = 1;
      fetchTransactions();
    };

    // 查看交易详情
    const viewTransactionDetail = (record) => {
      selectedTransaction.value = record;
      detailModalVisible.value = true;
    };

    // 打印交易凭证
    const printReceipt = (record) => {
      message.success(`正在打印交易 ${record.id} 的凭证`);
      // 实际应用中，这里应该调用打印API或生成PDF
    };

    // 导出交易数据
    const exportTransactions = () => {
      message.success('交易数据导出中，请稍候...');
      // 实际应用中，这里应该调用导出API
      setTimeout(() => {
        message.success('交易数据导出成功');
      }, 1500);
    };

    // 格式化货币
    const formatCurrency = (value) => {
      return new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY',
        minimumFractionDigits: 2
      }).format(value).replace('CN¥', '¥');
    };

    // 判断是否为负向交易（支出）
    const isNegativeTransaction = (type) => {
      return ['withdrawal', 'payment', 'fee', 'transfer'].includes(type);
    };

    // 获取交易类型名称
    const getTransactionTypeName = (type) => {
      const typeMap = {
        deposit: '存款',
        withdrawal: '取款',
        transfer: '转账',
        payment: '支付',
        interest: '利息',
        fee: '手续费',
      };
      return typeMap[type] || type;
    };

    // 获取交易类型颜色
    const getTransactionTypeColor = (type) => {
      const colorMap = {
        deposit: 'green',
        withdrawal: 'red',
        transfer: 'blue',
        payment: 'orange',
        interest: 'purple',
        fee: 'cyan',
      };
      return colorMap[type] || 'default';
    };

    // 获取交易状态名称
    const getStatusName = (status) => {
      const statusMap = {
        completed: '已完成',
        processing: '处理中',
        failed: '失败',
      };
      return statusMap[status] || status;
    };

    // 获取交易状态颜色
    const getStatusColor = (status) => {
      const colorMap = {
        completed: 'green',
        processing: 'blue',
        failed: 'red',
      };
      return colorMap[status] || 'default';
    };

    // 获取交易渠道名称
    const getChannelName = (channel) => {
      const channelMap = {
        counter: '柜台',
        online: '网银',
        mobile: '手机银行',
        atm: 'ATM',
        system: '系统',
      };
      return channelMap[channel] || channel;
    };

    // 生命周期钩子
    onMounted(() => {
      fetchTransactions();
      fetchStats();
    });

    return {
      columns,
      transactions,
      loading,
      pagination,
      filterForm,
      stats,
      statsLoading,
      detailModalVisible,
      selectedTransaction,
      handleTableChange,
      handleSearch,
      resetFilters,
      viewTransactionDetail,
      printReceipt,
      exportTransactions,
      formatCurrency,
      isNegativeTransaction,
      getTransactionTypeName,
      getTransactionTypeColor,
      getStatusName,
      getStatusColor,
      getChannelName,
    };
  },
});
</script>

<style scoped>
.transactions-page {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin-bottom: 8px;
  font-size: 24px;
  font-weight: 500;
}

.page-header p {
  color: rgba(0, 0, 0, 0.45);
}

.filter-card {
  margin-bottom: 24px;
}

.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 4px;
}

.table-card {
  margin-bottom: 24px;
}

.table-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>