<template>
  <div class="accounts-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>账户管理</h1>
      <p>管理银行账户信息</p>
    </div>
    
    <!-- 操作栏 -->
    <div class="action-bar">
      <a-button type="primary" @click="showAddAccountModal">
        <plus-outlined /> 添加账户
      </a-button>
      <a-input-search
        v-model:value="searchQuery"
        placeholder="搜索账户..."
        style="width: 250px; margin-left: 16px;"
        @search="handleSearch"
      />
    </div>
    
    <!-- 账户表格 -->
    <a-table
      :columns="columns"
      :data-source="accounts"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      row-key="id"
    >
      <!-- 状态列 -->
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusName(record.status) }}
          </a-tag>
        </template>
        
        <!-- 账户类型列 -->
        <template v-if="column.key === 'type'">
          <a-tag :color="getTypeColor(record.type)">
            {{ getTypeName(record.type) }}
          </a-tag>
        </template>
        
        <!-- 余额列 -->
        <template v-if="column.key === 'balance'">
          <span :style="{ color: record.balance < 0 ? '#f5222d' : '' }">
            {{ formatCurrency(record.balance) }}
          </span>
        </template>
        
        <!-- 操作列 -->
        <template v-if="column.key === 'action'">
          <a-space>
            <a @click="viewAccount(record)">查看</a>
            <a-divider type="vertical" />
            <a @click="editAccount(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要冻结此账户吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="freezeAccount(record.id)"
              v-if="record.status === 'active'"
            >
              <a class="warning-link">冻结</a>
            </a-popconfirm>
            <a-popconfirm
              title="确定要激活此账户吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="activateAccount(record.id)"
              v-if="record.status === 'frozen'"
            >
              <a class="success-link">激活</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
    
    <!-- 添加/编辑账户对话框 -->
    <a-modal
      v-model:visible="accountModalVisible"
      :title="isEditing ? '编辑账户' : '添加账户'"
      @ok="handleAccountFormSubmit"
      :confirmLoading="submitting"
    >
      <a-form
        :model="accountForm"
        :rules="rules"
        ref="accountFormRef"
        layout="vertical"
      >
        <a-form-item label="账户号码" name="accountNumber" v-if="isEditing">
          <a-input v-model:value="accountForm.accountNumber" disabled />
        </a-form-item>
        
        <a-form-item label="账户名称" name="name">
          <a-input v-model:value="accountForm.name" />
        </a-form-item>
        
        <a-form-item label="账户类型" name="type">
          <a-select v-model:value="accountForm.type">
            <a-select-option value="savings">储蓄账户</a-select-option>
            <a-select-option value="checking">活期账户</a-select-option>
            <a-select-option value="credit">信用账户</a-select-option>
            <a-select-option value="loan">贷款账户</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="所属用户" name="userId">
          <a-select
            v-model:value="accountForm.userId"
            :loading="usersLoading"
            show-search
            placeholder="选择用户"
            :filter-option="filterUserOption"
          >
            <a-select-option v-for="user in usersList" :key="user.id" :value="user.id">
              {{ user.name }} ({{ user.username }})
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="初始余额" name="balance" v-if="!isEditing">
          <a-input-number
            v-model:value="accountForm.balance"
            :precision="2"
            style="width: 100%"
          />
        </a-form-item>
        
        <a-form-item label="状态" name="status" v-if="isEditing">
          <a-select v-model:value="accountForm.status">
            <a-select-option value="active">活跃</a-select-option>
            <a-select-option value="frozen">冻结</a-select-option>
            <a-select-option value="closed">关闭</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="备注" name="notes">
          <a-textarea v-model:value="accountForm.notes" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>
    
    <!-- 账户详情对话框 -->
    <a-modal
      v-model:visible="accountDetailVisible"
      title="账户详情"
      :footer="null"
      width="700px"
    >
      <template v-if="selectedAccount">
        <a-descriptions bordered :column="{ xxl: 2, xl: 2, lg: 2, md: 1, sm: 1, xs: 1 }">
          <a-descriptions-item label="账户号码">{{ selectedAccount.accountNumber }}</a-descriptions-item>
          <a-descriptions-item label="账户名称">{{ selectedAccount.name }}</a-descriptions-item>
          <a-descriptions-item label="账户类型">{{ getTypeName(selectedAccount.type) }}</a-descriptions-item>
          <a-descriptions-item label="账户状态">
            <a-tag :color="getStatusColor(selectedAccount.status)">
              {{ getStatusName(selectedAccount.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="当前余额">{{ formatCurrency(selectedAccount.balance) }}</a-descriptions-item>
          <a-descriptions-item label="所属用户">{{ selectedAccount.userName }}</a-descriptions-item>
          <a-descriptions-item label="开户日期">{{ selectedAccount.createdAt }}</a-descriptions-item>
          <a-descriptions-item label="最后更新">{{ selectedAccount.updatedAt }}</a-descriptions-item>
          <a-descriptions-item label="备注" :span="2">{{ selectedAccount.notes || '无' }}</a-descriptions-item>
        </a-descriptions>
        
        <a-divider>最近交易记录</a-divider>
        
        <a-table
          :columns="transactionColumns"
          :data-source="recentTransactions"
          :loading="transactionsLoading"
          :pagination="{ pageSize: 5 }"
          size="small"
        >
          <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: record.type === 'withdrawal' ? '#f5222d' : '#52c41a' }">
                {{ record.type === 'withdrawal' ? '-' : '+' }}{{ formatCurrency(record.amount) }}
              </span>
            </template>
          </template>
        </a-table>
        
        <div style="margin-top: 16px; text-align: right;">
          <a-button @click="accountDetailVisible = false">关闭</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { api } from '@/utils/api';

export default defineComponent({
  name: 'AccountsPage',
  components: {
    PlusOutlined
  },
  setup() {
    // 表格列定义
    const columns = [
      {
        title: '账户号码',
        dataIndex: 'accountNumber',
        key: 'accountNumber',
        sorter: true,
      },
      {
        title: '账户名称',
        dataIndex: 'name',
        key: 'name',
        sorter: true,
      },
      {
        title: '账户类型',
        dataIndex: 'type',
        key: 'type',
        filters: [
          { text: '储蓄账户', value: 'savings' },
          { text: '活期账户', value: 'checking' },
          { text: '信用账户', value: 'credit' },
          { text: '贷款账户', value: 'loan' },
        ],
      },
      {
        title: '所属用户',
        dataIndex: 'userName',
        key: 'userName',
        sorter: true,
      },
      {
        title: '余额',
        dataIndex: 'balance',
        key: 'balance',
        sorter: true,
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        filters: [
          { text: '活跃', value: 'active' },
          { text: '冻结', value: 'frozen' },
          { text: '关闭', value: 'closed' },
        ],
      },
      {
        title: '开户日期',
        dataIndex: 'createdAt',
        key: 'createdAt',
        sorter: true,
      },
      {
        title: '操作',
        key: 'action',
      },
    ];

    // 交易记录列定义
    const transactionColumns = [
      {
        title: '交易ID',
        dataIndex: 'id',
        key: 'id',
      },
      {
        title: '交易类型',
        dataIndex: 'type',
        key: 'type',
      },
      {
        title: '金额',
        dataIndex: 'amount',
        key: 'amount',
      },
      {
        title: '交易时间',
        dataIndex: 'timestamp',
        key: 'timestamp',
      },
      {
        title: '备注',
        dataIndex: 'description',
        key: 'description',
      },
    ];

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

    // 用户列表相关
    const usersList = ref([]);
    const usersLoading = ref(false);

    // 账户表单相关
    const accountFormRef = ref(null);
    const accountModalVisible = ref(false);
    const isEditing = ref(false);
    const submitting = ref(false);
    const accountForm = reactive({
      id: null,
      accountNumber: '',
      name: '',
      type: 'savings',
      userId: null,
      balance: 0,
      status: 'active',
      notes: '',
    });

    // 账户详情相关
    const accountDetailVisible = ref(false);
    const selectedAccount = ref(null);
    const recentTransactions = ref([]);
    const transactionsLoading = ref(false);

    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入账户名称', trigger: 'blur' },
      ],
      type: [
        { required: true, message: '请选择账户类型', trigger: 'change' },
      ],
      userId: [
        { required: true, message: '请选择所属用户', trigger: 'change' },
      ],
      balance: [
        { required: true, message: '请输入初始余额', trigger: 'blur' },
      ],
    };

    // 获取账户列表
    const fetchAccounts = async (params = {}) => {
      loading.value = true;
      try {
        const response = await api.accounts.getList({
          page: pagination.current,
          pageSize: pagination.pageSize,
          search: searchText.value,
          type: typeFilter.value,
          status: statusFilter.value,
          ...params
        });
        
        if (response.success) {
          accounts.value = response.data.accounts || [];
          pagination.total = response.data.pagination?.total || 0;
        } else {
          message.error(response.message || '获取账户列表失败');
          // 使用模拟数据作为备用
          const mockAccounts = [
            { 
              id: 1, 
              accountNumber: '6225123456789001', 
              name: '张三储蓄账户', 
              type: 'savings', 
              userId: 1, 
              userName: '张三', 
              balance: 10000.50, 
              status: 'active', 
              createdAt: '2023-01-01', 
              updatedAt: '2023-09-15',
              notes: '主要储蓄账户'
            },
            { 
              id: 2, 
              accountNumber: '6225123456789002', 
              name: '李四活期账户', 
              type: 'checking', 
              userId: 2, 
              userName: '李四', 
              balance: 5000.75, 
              status: 'active', 
              createdAt: '2023-02-15', 
              updatedAt: '2023-09-10',
              notes: ''
            },
            { 
              id: 3, 
              accountNumber: '6225123456789003', 
              name: '王五信用卡', 
              type: 'credit', 
              userId: 3, 
              userName: '王五', 
              balance: -2000.00, 
              status: 'active', 
              createdAt: '2023-03-20', 
              updatedAt: '2023-09-12',
              notes: '信用额度: 50000'
            },
            { 
              id: 4, 
              accountNumber: '6225123456789004', 
              name: '赵六房贷', 
              type: 'loan', 
              userId: 4, 
              userName: '赵六', 
              balance: -500000.00, 
              status: 'frozen', 
              createdAt: '2023-04-10', 
              updatedAt: '2023-09-01',
              notes: '30年房贷'
            },
          ];
          accounts.value = mockAccounts;
          pagination.total = mockAccounts.length;
        }
      } catch (error) {
        console.error('获取账户列表失败:', error);
        message.error('获取账户列表失败');
        // 使用模拟数据作为备用
        const mockAccounts = [
          { 
            id: 1, 
            accountNumber: '6225123456789001', 
            name: '张三储蓄账户', 
            type: 'savings', 
            userId: 1, 
            userName: '张三', 
            balance: 10000.50, 
            status: 'active', 
            createdAt: '2023-01-01', 
            updatedAt: '2023-09-15',
            notes: '主要储蓄账户'
          }
        ];
        accounts.value = mockAccounts;
        pagination.total = mockAccounts.length;
      } finally {
        loading.value = false;
      }
    };

    // 获取用户列表
    const fetchUsers = async () => {
      usersLoading.value = true;
      try {
        const response = await api.users.getList({ page: 1, pageSize: 100 });
        if (response.success) {
          usersList.value = response.data.users || [];
        } else {
          // 使用模拟数据作为备用
          usersList.value = [
            { id: 1, username: 'zhangsan', name: '张三' },
            { id: 2, username: 'lisi', name: '李四' },
            { id: 3, username: 'wangwu', name: '王五' },
            { id: 4, username: 'zhaoliu', name: '赵六' },
          ];
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
        message.error('获取用户列表失败');
        // 使用模拟数据作为备用
        usersList.value = [
          { id: 1, username: 'zhangsan', name: '张三' },
          { id: 2, username: 'lisi', name: '李四' },
          { id: 3, username: 'wangwu', name: '王五' },
          { id: 4, username: 'zhaoliu', name: '赵六' },
        ];
      } finally {
        usersLoading.value = false;
      }
    };

    // 获取账户交易记录
    const fetchAccountTransactions = async (accountId) => {
      transactionsLoading.value = true;
      try {
        // 这里应该是实际的API调用
        // const response = await api.getAccountTransactions(accountId);
        // recentTransactions.value = response.data;
        
        // 模拟数据
        setTimeout(() => {
          recentTransactions.value = [
            { 
              id: 'T20230915001', 
              type: 'deposit', 
              amount: 1000.00, 
              timestamp: '2023-09-15 10:30:25', 
              description: '工资入账' 
            },
            { 
              id: 'T20230914002', 
              type: 'withdrawal', 
              amount: 500.00, 
              timestamp: '2023-09-14 15:45:12', 
              description: '超市购物' 
            },
            { 
              id: 'T20230913003', 
              type: 'transfer', 
              amount: 2000.00, 
              timestamp: '2023-09-13 09:20:45', 
              description: '转账给李四' 
            },
            { 
              id: 'T20230912004', 
              type: 'withdrawal', 
              amount: 100.00, 
              timestamp: '2023-09-12 18:10:33', 
              description: '餐饮消费' 
            },
            { 
              id: 'T20230911005', 
              type: 'deposit', 
              amount: 5000.00, 
              timestamp: '2023-09-11 14:05:22', 
              description: '投资回报' 
            },
          ];
          transactionsLoading.value = false;
        }, 400);
      } catch (error) {
        message.error('获取交易记录失败');
        transactionsLoading.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;
      fetchAccounts(params);
    };

    // 搜索处理
    const handleSearch = () => {
      pagination.current = 1;
      fetchAccounts({ search: searchQuery.value });
    };

    // 显示添加账户对话框
    const showAddAccountModal = () => {
      isEditing.value = false;
      resetAccountForm();
      accountModalVisible.value = true;
    };

    // 编辑账户
    const editAccount = (record) => {
      isEditing.value = true;
      Object.assign(accountForm, { ...record });
      accountModalVisible.value = true;
    };

    // 查看账户详情
    const viewAccount = (record) => {
      selectedAccount.value = record;
      accountDetailVisible.value = true;
      fetchAccountTransactions(record.id);
    };

    // 冻结账户
    const freezeAccount = async (id) => {
      try {
        // 这里应该是实际的API调用
        // await api.updateAccountStatus(id, 'frozen');
        message.success('账户已冻结');
        fetchAccounts({ page: pagination.current });
      } catch (error) {
        message.error('冻结账户失败');
      }
    };

    // 激活账户
    const activateAccount = async (id) => {
      try {
        // 这里应该是实际的API调用
        // await api.updateAccountStatus(id, 'active');
        message.success('账户已激活');
        fetchAccounts({ page: pagination.current });
      } catch (error) {
        message.error('激活账户失败');
      }
    };

    // 提交账户表单
    const handleAccountFormSubmit = () => {
      accountFormRef.value.validate().then(async () => {
        submitting.value = true;
        try {
          if (isEditing.value) {
            // 编辑账户
            // await api.updateAccount(accountForm.id, accountForm);
            message.success('账户更新成功');
          } else {
            // 添加账户
            // await api.createAccount(accountForm);
            message.success('账户添加成功');
          }
          accountModalVisible.value = false;
          fetchAccounts({ page: pagination.current });
        } catch (error) {
          message.error(isEditing.value ? '更新账户失败' : '添加账户失败');
        } finally {
          submitting.value = false;
        }
      });
    };

    // 重置账户表单
    const resetAccountForm = () => {
      accountForm.id = null;
      accountForm.accountNumber = '';
      accountForm.name = '';
      accountForm.type = 'savings';
      accountForm.userId = null;
      accountForm.balance = 0;
      accountForm.status = 'active';
      accountForm.notes = '';
      
      // 如果表单已经创建，则重置验证
      if (accountFormRef.value) {
        accountFormRef.value.resetFields();
      }
    };

    // 用户选择过滤
    const filterUserOption = (input, option) => {
      return (
        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
        option.value.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    };

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

    // 获取账户状态名称
    const getStatusName = (status) => {
      const statusMap = {
        active: '活跃',
        frozen: '冻结',
        closed: '关闭',
      };
      return statusMap[status] || status;
    };

    // 获取账户状态颜色
    const getStatusColor = (status) => {
      const colorMap = {
        active: 'green',
        frozen: 'orange',
        closed: 'red',
      };
      return colorMap[status] || 'default';
    };

    // 获取账户类型名称
    const getTypeName = (type) => {
      const typeMap = {
        savings: '储蓄账户',
        checking: '活期账户',
        credit: '信用账户',
        loan: '贷款账户',
      };
      return typeMap[type] || type;
    };

    // 获取账户类型颜色
    const getTypeColor = (type) => {
      const colorMap = {
        savings: 'blue',
        checking: 'green',
        credit: 'purple',
        loan: 'orange',
      };
      return colorMap[type] || 'default';
    };

    // 获取交易类型名称
    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';
    };

    // 生命周期钩子
    onMounted(() => {
      fetchAccounts();
      fetchUsers();
    });

    return {
      columns,
      transactionColumns,
      accounts,
      loading,
      searchQuery,
      pagination,
      usersList,
      usersLoading,
      accountFormRef,
      accountModalVisible,
      isEditing,
      submitting,
      accountForm,
      rules,
      accountDetailVisible,
      selectedAccount,
      recentTransactions,
      transactionsLoading,
      handleTableChange,
      handleSearch,
      showAddAccountModal,
      editAccount,
      viewAccount,
      freezeAccount,
      activateAccount,
      handleAccountFormSubmit,
      filterUserOption,
      formatCurrency,
      getStatusName,
      getStatusColor,
      getTypeName,
      getTypeColor,
      getTransactionTypeName,
      getTransactionTypeColor,
    };
  },
});
</script>

<style scoped>
.accounts-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);
}

.action-bar {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.warning-link {
  color: #faad14;
}

.success-link {
  color: #52c41a;
}

.danger-link {
  color: #ff4d4f;
}
</style>