<template>
  <div class="account-details-container">
    <a-card title="账户明细" :bordered="false">
      <!-- 筛选区域 -->
      <div class="filter-container">
        <a-form layout="inline" :model="filterForm">
          <a-form-item label="日期范围">
            <a-range-picker
              v-model:value="dateRange"
              format="YYYY-MM-DD"
              :placeholder="['开始日期', '结束日期']"
              @change="handleDateChange"
            />
          </a-form-item>
          <a-form-item label="交易类型">
            <a-select
              v-model:value="filterForm.type"
              style="width: 120px"
              placeholder="全部类型"
              allowClear
              @change="handleSearch"
            >
              <a-select-option value="INCOME">收入</a-select-option>
              <a-select-option value="EXPENSE">支出</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleSearch">查询</a-button>
            <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data-source="detailsList"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        rowKey="id"
      >
        <template #bodyCell="{ column, record }">
          <!-- 金额列 -->
          <template v-if="column.dataIndex === 'amount'">
            <span :class="record.type === 'INCOME' ? 'income-amount' : 'expense-amount'">
              {{ record.type === 'INCOME' ? '+' : '-' }}{{ record.amount.toFixed(2) }}
            </span>
          </template>
          
          <!-- 类型列 -->
          <template v-if="column.dataIndex === 'type'">
            <a-tag :color="record.type === 'INCOME' ? 'green' : 'red'">
              {{ record.type === 'INCOME' ? '收入' : '支出' }}
            </a-tag>
          </template>
          
          <!-- 交易号列 -->
          <template v-if="column.dataIndex === 'transaction_id'">
            <span v-if="record.transaction_id">{{ record.transaction_id }}</span>
            <span v-else>-</span>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue';
import { getAccountDetails } from '../api/finance';
import { message } from 'ant-design-vue';
import { formatDate } from '../utils/format';

export default {
  name: 'AccountDetails',
  setup() {
    // 筛选表单
    const filterForm = reactive({
      start_date: '',
      end_date: '',
      type: undefined
    });
    
    // 日期范围
    const dateRange = ref([]);
    
    // 表格列定义
    const columns = [
      {
        title: '交易时间',
        dataIndex: 'create_time',
        width: 180,
        sorter: true,
        customRender: ({ text }) => formatDate(text)
      },
      {
        title: '交易类型',
        dataIndex: 'type',
        width: 100
      },
      {
        title: '金额(元)',
        dataIndex: 'amount',
        width: 120,
        align: 'right'
      },
      {
        title: '交易描述',
        dataIndex: 'description'
      },
      {
        title: '交易号',
        dataIndex: 'transaction_id',
        width: 180
      }
    ];
    
    // 明细列表数据
    const detailsList = ref([]);
    // 加载状态
    const loading = ref(false);
    
    // 分页配置
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showTotal: (total) => `共 ${total} 条记录`
    });
    
    // 处理日期变化
    const handleDateChange = (dates, dateStrings) => {
      filterForm.start_date = dateStrings[0] || '';
      filterForm.end_date = dateStrings[1] || '';
    };
    
    // 获取账户明细列表
    const fetchAccountDetails = async () => {
      loading.value = true;
      try {
        const params = {
          skip: (pagination.current - 1) * pagination.pageSize,
          limit: pagination.pageSize,
          ...filterForm
        };
        
        // 移除空值
        Object.keys(params).forEach(key => {
          if (params[key] === '' || params[key] === undefined) {
            delete params[key];
          }
        });
        
        console.log('请求参数:', params);
        const response = await getAccountDetails(params);
        console.log('API返回数据:', response);
        
        // 根据request.js的处理，response已经是data部分了
        detailsList.value = response?.items || [];
        pagination.total = response?.total || 0;
        console.log('处理后的列表数据:', detailsList.value);
      } catch (error) {
        console.error('获取账户明细失败:', error);
        message.error('获取账户明细失败，请稍后重试');
        detailsList.value = [];
        pagination.total = 0;
      } finally {
        loading.value = false;
      }
    };
    
    // 处理查询
    const handleSearch = () => {
      pagination.current = 1;
      fetchAccountDetails();
    };
    
    // 处理重置
    const handleReset = () => {
      filterForm.start_date = '';
      filterForm.end_date = '';
      filterForm.type = undefined;
      dateRange.value = [];
      pagination.current = 1;
      fetchAccountDetails();
    };
    
    // 处理表格变化（排序、分页）
    const handleTableChange = (pag) => {
      pagination.current = pag.current;
      pagination.pageSize = pag.pageSize;
      fetchAccountDetails();
    };
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchAccountDetails();
    });
    
    return {
      filterForm,
      dateRange,
      columns,
      detailsList,
      loading,
      pagination,
      handleDateChange,
      handleSearch,
      handleReset,
      handleTableChange,
      formatDate
    };
  }
};
</script>

<style scoped>
.account-details-container {
  padding: 0;
}

.filter-container {
  margin-bottom: 16px;
}

.income-amount {
  color: #52c41a;
  font-weight: 500;
}

.expense-amount {
  color: #f5222d;
  font-weight: 500;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
}
</style> 