<template>
  <div class="payment-list-container">
    <!-- 顶部资金卡片 -->
    <el-row :gutter="20" class="mb-20">
      <el-col :span="6">
        <vab-card shadow="hover" class="stat-card">
          <div class="stat-icon bg-primary">
            <vab-icon icon="money-cny-circle-line" />
          </div>
          <div class="stat-info">
            <div class="stat-value">¥ 458,200.00</div>
            <div class="stat-label">本学年应收总额</div>
          </div>
        </vab-card>
      </el-col>
      <el-col :span="6">
        <vab-card shadow="hover" class="stat-card">
          <div class="stat-icon bg-success">
            <vab-icon icon="checkbox-circle-line" />
          </div>
          <div class="stat-info">
            <div class="stat-value">¥ 389,450.00</div>
            <div class="stat-label">实收总额 (85%)</div>
          </div>
        </vab-card>
      </el-col>
      <el-col :span="6">
        <vab-card shadow="hover" class="stat-card">
          <div class="stat-icon bg-danger">
            <vab-icon icon="close-circle-line" />
          </div>
          <div class="stat-info">
            <div class="stat-value">¥ 68,750.00</div>
            <div class="stat-label">待缴欠费</div>
          </div>
        </vab-card>
      </el-col>
      <el-col :span="6">
        <vab-card shadow="hover" class="stat-card">
          <div class="stat-icon bg-warning">
            <vab-icon icon="refund-2-line" />
          </div>
          <div class="stat-info">
            <div class="stat-value">¥ 2,100.00</div>
            <div class="stat-label">累计退费</div>
          </div>
        </vab-card>
      </el-col>
    </el-row>

    <vab-card>
      <vab-query-form>
        <vab-query-form-left-panel>
          <el-form :inline="true" :model="queryForm" @submit.prevent>
            <el-form-item label="学生信息">
              <el-input v-model="queryForm.keyword" placeholder="姓名/学号" clearable />
            </el-form-item>
            <el-form-item label="费用类型">
              <el-select v-model="queryForm.feeType" placeholder="全部" clearable style="width: 140px">
                <el-option label="住宿费" value="accommodation" />
                <el-option label="水电费" value="utility" />
                <el-option label="押金" value="deposit" />
              </el-select>
            </el-form-item>
            <el-form-item label="缴费状态">
              <el-select v-model="queryForm.status" placeholder="全部" clearable style="width: 120px">
                <el-option label="已缴清" value="paid" />
                <el-option label="欠费" value="unpaid" />
                <el-option label="部分缴纳" value="partial" />
                <el-option label="已退费" value="refunded" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"> <vab-icon icon="search-line" /> 查询</el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-left-panel>
        <vab-query-form-right-panel>
          <el-button type="primary" @click="handleAdd"> <vab-icon icon="add-line" /> 创建账单</el-button>
          <el-button @click="handleExport"> <vab-icon icon="file-excel-line" /> 导出报表</el-button>
        </vab-query-form-right-panel>
      </vab-query-form>

      <el-table v-loading="loading" :data="tableData" border stripe>
        <el-table-column prop="billNo" label="账单编号" fixed />
        <el-table-column prop="studentName" label="学生姓名" width="100" />
        <el-table-column prop="studentId" label="学号" width="120" />
        <el-table-column prop="feeType" label="费用类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getFeeTypeTag(row.feeType)">{{ getFeeTypeLabel(row.feeType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="应收金额" width="120" sortable>
          <template #default="{ row }">
            <span class="font-bold">¥ {{ row.amount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paidAmount" label="已缴金额" width="120">
          <template #default="{ row }">
            <span class="text-success">¥ {{ row.paidAmount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dueDate" label="截止日期" width="120" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button v-if="row.status !== 'paid' && row.status !== 'refunded'" type="primary" size="small" @click="handlePay(row)"> <vab-icon icon="pay-line" /> 缴费</el-button>
            <el-button v-if="row.status === 'paid'" type="warning" size="small" @click="handleRefund(row)"> <vab-icon icon="refund-2-line" /> 退费</el-button>
            <el-button size="small" @click="handleDetail(row)"> <vab-icon icon="info-line" /> 详情</el-button>
            <el-button v-if="row.status === 'paid'" size="small" type="info" @click="handlePrint(row)" circle> <vab-icon icon="printer-line" /> </el-button>
          </template>
        </el-table-column>
      </el-table>

      <vab-pagination
        :current-page="queryForm.pageNo"
        :page-size="queryForm.pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </vab-card>

    <!-- 缴费弹窗 -->
    <pay-dialog ref="payDialogRef" @success="handlePaySuccess" />

    <!-- 退费弹窗 -->
    <refund-dialog ref="refundDialogRef" @success="handleRefundSuccess" />

    <!-- 票据预览 -->
    <receipt-dialog ref="receiptDialogRef" />

    <!-- 账单详情抽屉 -->
    <payment-detail-drawer ref="detailDrawerRef" />
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import PayDialog from './components/PayDialog.vue'
import RefundDialog from './components/RefundDialog.vue'
import ReceiptDialog from './components/ReceiptDialog.vue'
import PaymentDetailDrawer from './components/PaymentDetailDrawer.vue'
import ExcelJS from 'exceljs'
import { saveAs } from 'file-saver'

defineOptions({
  name: 'PaymentList',
})

// --- Data ---
const queryForm = reactive({
  keyword: '',
  feeType: '',
  status: '',
  pageNo: 1,
  pageSize: 10,
})

const loading = ref(false)
const total = ref(100)
const tableData = ref([])
const payDialogRef = ref()
const refundDialogRef = ref()
const receiptDialogRef = ref()
const detailDrawerRef = ref()

// --- Mock Data ---
const generateMockData = () => {
  return [
    {
      billNo: 'JF20260101001',
      studentName: '梁健',
      studentId: '31901001',
      feeType: 'accommodation',
      amount: 1200.00,
      paidAmount: 0,
      status: 'unpaid',
      dueDate: '2026-02-01'
    },
    {
      billNo: 'JF20260101002',
      studentName: '鲁永波',
      studentId: '31901002',
      feeType: 'accommodation',
      amount: 1200.00,
      paidAmount: 1200.00,
      status: 'paid',
      dueDate: '2026-02-01'
    },
    {
      billNo: 'JF20260101003',
      studentName: '王应哲',
      studentId: '31901003',
      feeType: 'utility',
      amount: 200.00,
      paidAmount: 100.00,
      status: 'partial',
      dueDate: '2026-01-31'
    },
    {
      billNo: 'JF20260101004',
      studentName: '杨勇捷',
      studentId: '31901004',
      feeType: 'deposit',
      amount: 500.00,
      paidAmount: 500.00,
      status: 'refunded',
      dueDate: '2026-01-15'
    }
  ]
}

// --- Helpers ---
const getFeeTypeLabel = (type) => {
  const map = { accommodation: '住宿费', utility: '水电费', deposit: '押金' }
  return map[type] || type
}
const getFeeTypeTag = (type) => {
  const map = { accommodation: '', utility: 'warning', deposit: 'info' }
  return map[type]
}
const getStatusLabel = (status) => {
  const map = { unpaid: '欠费', paid: '已缴清', partial: '部分缴纳', refunded: '已退费' }
  return map[status]
}
const getStatusType = (status) => {
  const map = { unpaid: 'danger', paid: 'success', partial: 'warning', refunded: 'info' }
  return map[status]
}

// --- Methods ---
const handleQuery = () => {
  loading.value = true
  setTimeout(() => {
    tableData.value = generateMockData()
    loading.value = false
  }, 500)
}

const handleAdd = () => {
  ElMessage.info('创建账单功能待开发')
}

const handleExport = async () => {
  loading.value = true
  try {
    const workbook = new ExcelJS.Workbook()
    const worksheet = workbook.addWorksheet('缴费列表')

    worksheet.columns = [
      { header: '账单编号', key: 'billNo', width: 20 },
      { header: '学生姓名', key: 'studentName', width: 15 },
      { header: '学号', key: 'studentId', width: 15 },
      { header: '费用类型', key: 'feeType', width: 15 },
      { header: '应收金额', key: 'amount', width: 15 },
      { header: '已缴金额', key: 'paidAmount', width: 15 },
      { header: '状态', key: 'status', width: 15 },
      { header: '截止日期', key: 'dueDate', width: 15 },
    ]

    const data = tableData.value.map(item => ({
      ...item,
      feeType: getFeeTypeLabel(item.feeType),
      status: getStatusLabel(item.status),
      amount: item.amount.toFixed(2),
      paidAmount: item.paidAmount.toFixed(2),
    }))

    worksheet.addRows(data)

    const buffer = await workbook.xlsx.writeBuffer()
    const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    saveAs(blob, `缴费列表_${new Date().toLocaleDateString()}.xlsx`)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error(error)
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

// 缴费逻辑
const handlePay = (row) => {
  payDialogRef.value.open(row)
}

const handlePaySuccess = (updatedBill) => {
  const index = tableData.value.findIndex(item => item.billNo === updatedBill.billNo)
  if (index !== -1) {
    tableData.value[index].paidAmount += updatedBill.payAmount
    if (tableData.value[index].paidAmount >= tableData.value[index].amount) {
      tableData.value[index].status = 'paid'
    } else {
      tableData.value[index].status = 'partial'
    }
  }
}

// 退费逻辑
const handleRefund = (row) => {
  refundDialogRef.value.open(row)
}

const handleRefundSuccess = (updatedBill) => {
  const index = tableData.value.findIndex(item => item.billNo === updatedBill.billNo)
  if (index !== -1) {
    tableData.value[index].paidAmount -= updatedBill.refundAmount
    if (tableData.value[index].paidAmount <= 0) {
      tableData.value[index].status = 'refunded'
      tableData.value[index].paidAmount = 0
    } else {
      tableData.value[index].status = 'partial'
    }
  }
}

const handleDetail = (row) => {
  detailDrawerRef.value.open(row)
}

// 打印逻辑
const handlePrint = (row) => {
  receiptDialogRef.value.open(row)
}

const handleCurrentChange = (val) => {
  queryForm.pageNo = val
  handleQuery()
}
const handleSizeChange = (val) => {
  queryForm.pageSize = val
  handleQuery()
}

// Lifecycle
handleQuery()
</script>

<style lang="scss" scoped>
.payment-list-container {
  .mb-20 { margin-bottom: 20px; }
  .text-success { color: var(--el-color-success); }
  .text-danger { color: var(--el-color-danger); }
  .text-lg { font-size: 18px; }
  .font-bold { font-weight: bold; }

  .stat-card {
    :deep(.el-card__body) {
      display: flex;
      align-items: center;
      padding: 20px;
    }

    .stat-icon {
      width: 56px;
      height: 56px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      font-size: 28px;
      color: #fff;
      &.bg-primary { background: var(--el-color-primary); }
      &.bg-success { background: var(--el-color-success); }
      &.bg-danger { background: var(--el-color-danger); }
      &.bg-warning { background: var(--el-color-warning); }
    }

    .stat-info {
      .stat-value { font-size: 24px; font-weight: bold; color: #303133; }
      .stat-label { font-size: 13px; color: #909399; margin-top: 5px; }
    }
  }
}
</style>