<template>
  <div class="min-h-screen bg-gray-100 dark:bg-gray-900">
    <!-- 顶部导航 -->
    <div class="bg-white dark:bg-gray-800 shadow">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
        <div class="flex justify-between items-center">
          <h1 class="text-2xl font-bold text-gray-900 dark:text-white">财务管理</h1>
          <div class="flex space-x-4">
            <button @click="showAddTransactionModal = true" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700">
              新增交易
            </button>
            <button @click="exportFinancialData" class="bg-green-600 text-white px-4 py-2 rounded-md hover:bg-green-700">
              导出报表
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 财务概览卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <h3 class="text-lg font-medium text-gray-900 dark:text-white">总收入</h3>
          <p class="mt-2 text-3xl font-bold text-green-600 dark:text-green-400">¥{{ formatNumber(totalIncome) }}</p>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <h3 class="text-lg font-medium text-gray-900 dark:text-white">总支出</h3>
          <p class="mt-2 text-3xl font-bold text-red-600 dark:text-red-400">¥{{ formatNumber(totalExpense) }}</p>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <h3 class="text-lg font-medium text-gray-900 dark:text-white">净利润</h3>
          <p class="mt-2 text-3xl font-bold text-blue-600 dark:text-blue-400">¥{{ formatNumber(netProfit) }}</p>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <h3 class="text-lg font-medium text-gray-900 dark:text-white">预算使用率</h3>
          <p class="mt-2 text-3xl font-bold text-yellow-600 dark:text-yellow-400">{{ budgetUtilization }}%</p>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">交易类型</label>
            <select v-model="filters.type" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">全部</option>
              <option v-for="type in transactionTypes" :key="type.id" :value="type.id">{{ type.name }}</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">交易状态</label>
            <select v-model="filters.status" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">全部</option>
              <option v-for="status in transactionStatuses" :key="status.id" :value="status.id">{{ status.name }}</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">日期范围</label>
            <div class="flex space-x-2">
              <input type="date" v-model="filters.startDate" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <input type="date" v-model="filters.endDate" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
            </div>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">搜索</label>
            <input type="text" v-model="filters.search" placeholder="交易编号/描述" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
        </div>
      </div>

      <!-- 交易列表 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
          <thead class="bg-gray-50 dark:bg-gray-700">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">交易信息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">金额</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">类型</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
            <tr v-for="transaction in filteredTransactions" :key="transaction.id">
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900 dark:text-white">{{ transaction.number }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ transaction.description }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ formatDate(transaction.date) }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getAmountClass(transaction.type)" class="text-sm font-medium">
                  {{ transaction.type === 1 ? '+' : '-' }}¥{{ formatNumber(transaction.amount) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getTypeClass(transaction.type)" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full">
                  {{ getTypeName(transaction.type) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getStatusClass(transaction.status)" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full">
                  {{ getStatusName(transaction.status) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button @click="viewTransaction(transaction)" class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300 mr-3">查看</button>
                <button @click="editTransaction(transaction)" class="text-green-600 hover:text-green-900 dark:text-green-400 dark:hover:text-green-300 mr-3">编辑</button>
                <button @click="deleteTransaction(transaction)" class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 新增交易模态框 -->
    <div v-if="showAddTransactionModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center">
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6">
        <h2 class="text-xl font-bold mb-4 text-gray-900 dark:text-white">新增交易</h2>
        <form @submit.prevent="addTransaction">
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">交易类型</label>
            <select v-model="newTransaction.type" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option v-for="type in transactionTypes" :key="type.id" :value="type.id">{{ type.name }}</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">金额</label>
            <input type="number" v-model="newTransaction.amount" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">日期</label>
            <input type="date" v-model="newTransaction.date" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">描述</label>
            <textarea v-model="newTransaction.description" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white" rows="4"></textarea>
          </div>
          <div class="flex justify-end space-x-3">
            <button type="button" @click="showAddTransactionModal = false" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
              取消
            </button>
            <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
              创建
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

// 交易数据
const transactions = ref([
  {
    id: 1,
    number: 'TR20240315001',
    type: 1,
    amount: 5000,
    description: '产品销售',
    date: new Date().toISOString().split('T')[0],
    status: 1
  },
  {
    id: 2,
    number: 'TR20240315002',
    type: 2,
    amount: 2000,
    description: '办公用品采购',
    date: new Date(Date.now() - 86400000).toISOString().split('T')[0],
    status: 1
  }
])

// 交易类型
const transactionTypes = [
  { id: 1, name: '收入' },
  { id: 2, name: '支出' }
]

// 交易状态
const transactionStatuses = [
  { id: 1, name: '已完成' },
  { id: 2, name: '待审核' },
  { id: 3, name: '已取消' }
]

// 筛选条件
const filters = ref({
  type: '',
  status: '',
  startDate: '',
  endDate: '',
  search: ''
})

// 模态框状态
const showAddTransactionModal = ref(false)

// 新交易表单
const newTransaction = ref({
  type: '',
  amount: '',
  date: '',
  description: ''
})

// 计算属性
const filteredTransactions = computed(() => {
  return transactions.value.filter(transaction => {
    const matchesType = !filters.value.type || transaction.type === filters.value.type
    const matchesStatus = !filters.value.status || transaction.status === filters.value.status
    const matchesDate = (!filters.value.startDate || transaction.date >= filters.value.startDate) &&
      (!filters.value.endDate || transaction.date <= filters.value.endDate)
    const matchesSearch = !filters.value.search ||
      transaction.number.toLowerCase().includes(filters.value.search.toLowerCase()) ||
      transaction.description.toLowerCase().includes(filters.value.search.toLowerCase())
    return matchesType && matchesStatus && matchesDate && matchesSearch
  })
})

const totalIncome = computed(() => {
  return transactions.value
    .filter(t => t.type === 1)
    .reduce((sum, t) => sum + t.amount, 0)
})

const totalExpense = computed(() => {
  return transactions.value
    .filter(t => t.type === 2)
    .reduce((sum, t) => sum + t.amount, 0)
})

const netProfit = computed(() => {
  return totalIncome.value - totalExpense.value
})

const budgetUtilization = computed(() => {
  // 这里使用一个简单的计算方式，实际应用中应该根据实际的预算使用情况计算
  return 75
})

// 格式化数字
const formatNumber = (number) => {
  return number.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

// 获取类型名称
const getTypeName = (typeId) => {
  const type = transactionTypes.find(t => t.id === typeId)
  return type ? type.name : '未知'
}

// 获取状态名称
const getStatusName = (statusId) => {
  const status = transactionStatuses.find(s => s.id === statusId)
  return status ? status.name : '未知'
}

// 获取金额样式
const getAmountClass = (type) => {
  return type === 1 ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'
}

// 获取类型样式
const getTypeClass = (typeId) => {
  const classes = {
    1: 'bg-green-100 text-green-800 dark:bg-green-700 dark:text-green-300',
    2: 'bg-red-100 text-red-800 dark:bg-red-700 dark:text-red-300'
  }
  return classes[typeId] || classes[1]
}

// 获取状态样式
const getStatusClass = (statusId) => {
  const classes = {
    1: 'bg-green-100 text-green-800 dark:bg-green-700 dark:text-green-300',
    2: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-700 dark:text-yellow-300',
    3: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
  }
  return classes[statusId] || classes[1]
}

// 添加交易
const addTransaction = () => {
  const transaction = {
    id: transactions.value.length + 1,
    number: `TR${new Date().getTime()}`,
    ...newTransaction.value,
    status: 1
  }
  transactions.value.push(transaction)
  showAddTransactionModal.value = false
  resetNewTransaction()
}

// 重置新交易表单
const resetNewTransaction = () => {
  newTransaction.value = {
    type: '',
    amount: '',
    date: '',
    description: ''
  }
}

// 查看交易
const viewTransaction = (transaction) => {
  // 实现查看交易逻辑
  console.log('查看交易:', transaction)
}

// 编辑交易
const editTransaction = (transaction) => {
  // 实现编辑交易逻辑
  console.log('编辑交易:', transaction)
}

// 删除交易
const deleteTransaction = (transaction) => {
  if (confirm(`确定要删除交易 ${transaction.number} 吗？`)) {
    const index = transactions.value.findIndex(t => t.id === transaction.id)
    if (index !== -1) {
      transactions.value.splice(index, 1)
    }
  }
}

// 导出财务数据
const exportFinancialData = () => {
  // 实现导出财务数据的逻辑
  console.log('导出财务数据')
}
</script> 