// pages/index/index.js
const auth = require('../../utils/auth.js')
const bankService = require('../../services/bankService.js')

Page({
  data: {
    userInfo: {},
    quickActions: [
      { key: 'dashboard', name: '数据看板', icon: '📊', path: '/pages/dashboard/dashboard' },
      { key: 'customers', name: '客户管理', icon: '👥', path: '/pages/customers/customers' },
      { key: 'transactions', name: '交易记录', icon: '💳', path: '/pages/transactions/transactions' },
      { key: 'assets', name: '资产管理', icon: '💰', path: '/pages/assets/assets' },
      { key: 'risk', name: '风险控制', icon: '⚠️', path: '/pages/risk/risk' },
      { key: 'reports', name: '报表分析', icon: '📈', path: '/pages/reports/reports' },
      { key: 'profile', name: '个人中心', icon: '👤', path: '/pages/profile/profile' }
    ],
    bankCards: [
      {
        id: 1,
        type: '储蓄卡',
        number: '**** **** **** 1234',
        balance: '125,680.50',
        bankName: '中国银行'
      },
      {
        id: 2,
        type: '信用卡',
        number: '**** **** **** 5678',
        balance: '-2,450.00',
        bankName: '招商银行'
      }
    ],
    recentTransactions: [
      {
        id: 1,
        type: 'income',
        title: '工资收入',
        amount: '+8,500.00',
        time: '2024-01-15 09:00',
        status: 'success'
      },
      {
        id: 2,
        type: 'expense',
        title: '生活缴费',
        amount: '-1,200.00',
        time: '2024-01-14 14:30',
        status: 'success'
      },
      {
        id: 3,
        type: 'transfer',
        title: '转账给张三',
        amount: '-500.00',
        time: '2024-01-14 10:15',
        status: 'success'
      }
    ],
    statsData: [
      { key: 'totalBalance', label: '总资产', value: '¥123,230.50', trend: 'up', trendText: '+2.5%' },
      { key: 'monthlyIncome', label: '月收入', value: '¥8,500.00', trend: 'up', trendText: '+5.2%' },
      { key: 'monthlyExpense', label: '月支出', value: '¥3,200.00', trend: 'down', trendText: '-1.8%' },
      { key: 'creditScore', label: '信用评分', value: '850', trend: 'up', trendText: '+10' }
    ]
  },

  onLoad() {
    // 检查认证状态
    if (!auth.isAuthenticated()) {
      wx.reLaunch({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.initData()
  },

  onShow() {
    // 检查认证状态
    if (!auth.isAuthenticated()) {
      wx.reLaunch({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.initData()
  },

  onPullDownRefresh() {
    this.loadData()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  initData() {
    // 获取用户信息
    this.setData({
      userInfo: auth.getUser() || {}
    })
    
    // 加载数据
    this.loadData()
  },
  
  async loadData() {
    try {
      // 加载仪表板数据
      const dashboardData = await bankService.getDashboardData()
      if (dashboardData) {
        this.updateStatsData(dashboardData)
      }
    } catch (error) {
      console.error('加载数据失败:', error)
    }
  },
  
  updateStatsData(data) {
    const statsData = this.data.statsData.map(stat => {
      const newValue = data[stat.key] || stat.value
      return {
        ...stat,
        value: newValue
      }
    })
    this.setData({ statsData })
  },
  
  handleAction(e) {
    const { action } = e.currentTarget.dataset
    const actionItem = this.data.quickActions.find(item => item.key === action)
    if (actionItem && actionItem.path) {
      wx.navigateTo({
        url: actionItem.path
      })
    }
  },

  handleCardTap(e) {
    const { cardId } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/assets/detail?id=${cardId}`
    })
  },

  handleTransactionTap(e) {
    const { transactionId } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/transactions/detail?id=${transactionId}`
    })
  }
})
