<template>
  <div class="reimburse-page">
    <div class="page-header">
      <div>
        <h2>报销管理</h2>
        <p>管理个人报销申请及审批进度</p>
      </div>
      <el-button type="primary" :icon="Plus" @click="openCreate">新建报销</el-button>
    </div>

    <div class="filter-card">
      <el-form :inline="true" :model="filters" @submit.prevent>
        <el-form-item label="关键词">
          <el-input v-model="filters.keyword" clearable placeholder="请输入备注说明" @keyup.enter="loadList" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filters.status" clearable placeholder="全部状态" style="width: 150px">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="loadList">查询</el-button>
          <el-button :icon="Refresh" @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-card">
      <el-table v-loading="loading" :data="list" stripe>
        <el-table-column prop="apply_date" label="申请日期" width="120">
          <template #default="{ row }">{{ formatDate(row.apply_date) }}</template>
        </el-table-column>
        <el-table-column prop="description" label="备注说明" min-width="220" show-overflow-tooltip>
          <template #default="{ row }">{{ row.description || '-' }}</template>
        </el-table-column>
        <el-table-column prop="total_amount" label="报销金额" width="130">
          <template #default="{ row }">¥ {{ money(row.total_amount) }}</template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="110">
          <template #default="{ row }">
            <el-tag :type="statusType(row.status)">{{ statusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="175">
          <template #default="{ row }">{{ formatDateTime(row.create_time) }}</template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="245">
          <template #default="{ row }">
            <el-button link type="primary" @click="openDetail(row.id)">详情</el-button>
            <el-button v-if="row.status === 0" link type="primary" @click="openEdit(row.id)">编辑</el-button>
            <el-button v-if="row.status === 0" link type="success" @click="handleSubmit(row)">提交</el-button>
            <el-button v-if="row.status === 0" link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
        <template #empty><el-empty description="暂无报销记录" /></template>
      </el-table>
      <div class="pagination">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @update:current-page="pagination.page = $event"
          @update:page-size="pagination.pageSize = $event"
          @current-change="loadList"
          @size-change="loadList"
        />
      </div>
    </div>

    <ReimburseEdit
      v-model="formVisible"
      :title="formTitle"
      :form-data="form"
      :saving="saving"
      @save="saveForm"
    />

    <ReimburseDetail
      v-model="detailVisible"
      :detail="detail"
      :records="records"
      :expense-type-options="expenseTypeOptions"
      @changed="reloadDetail"
    />
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'
import ReimburseEdit from './components/edit.vue'
import ReimburseDetail from './components/detail.vue'
import {
  createReimbursement,
  deleteReimbursement,
  getReimbursementDetail,
  getReimbursementExpenseTypes,
  getReimbursementList,
  getReimbursementRecords,
  submitReimbursement,
  updateReimbursement
} from '@/api/reimburse'

const statusOptions = [
  { value: 0, label: '草稿' },
  { value: 1, label: '审批中' },
  { value: 2, label: '已通过' },
  { value: 3, label: '已驳回' },
  { value: 4, label: '已撤回' },
  { value: 5, label: '已打款' }
]
const filters = reactive({ keyword: '', status: undefined })
const pagination = reactive({ page: 1, pageSize: 10, total: 0 })
const list = ref([])
const loading = ref(false)
const saving = ref(false)
const formVisible = ref(false)
const detailVisible = ref(false)
const editingId = ref(0)
const detail = ref(null)
const records = ref([])
const expenseTypeOptions = ref([])

const emptyForm = () => ({
  apply_date: new Date().toISOString().slice(0, 10),
  description: ''
})
const form = reactive(emptyForm())
const formTitle = computed(() => editingId.value ? '编辑报销单' : '新建报销单')

const responseData = res => res?.data?.data ?? res?.data ?? res ?? {}

const loadExpenseTypes = async () => {
  try {
    const data = responseData(await getReimbursementExpenseTypes())
    expenseTypeOptions.value = Array.isArray(data) ? data : data.list || []
  } catch (error) {
    ElMessage.error(error?.message || '加载费用类型失败')
  }
}

const loadList = async () => {
  loading.value = true
  try {
    const data = responseData(await getReimbursementList({ ...filters, ...pagination }))
    list.value = data.list || []
    pagination.total = Number(data.total || 0)
  } catch (error) {
    ElMessage.error(error?.message || '加载报销列表失败')
  } finally {
    loading.value = false
  }
}

const resetFilters = () => {
  filters.keyword = ''
  filters.status = undefined
  pagination.page = 1
  loadList()
}

const resetForm = () => Object.assign(form, emptyForm())

const openCreate = () => {
  editingId.value = 0
  resetForm()
  formVisible.value = true
}

const openEdit = async id => {
  try {
    const data = responseData(await getReimbursementDetail(id))
    editingId.value = id
    Object.assign(form, {
      apply_date: data.apply_date || new Date().toISOString().slice(0, 10),
      description: data.description || ''
    })
    formVisible.value = true
  } catch (error) {
    ElMessage.error(error?.message || '加载报销详情失败')
  }
}

const saveForm = async payload => {
  saving.value = true
  try {
    if (editingId.value) await updateReimbursement(editingId.value, payload)
    else await createReimbursement(payload)
    ElMessage.success('保存成功')
    formVisible.value = false
    loadList()
  } catch (error) {
    ElMessage.error(error?.message || '保存失败')
  } finally {
    saving.value = false
  }
}

const handleSubmit = async row => {
  try {
    await ElMessageBox.confirm('提交后将进入审批流程，确认提交吗？', '提示', { type: 'warning' })
    await submitReimbursement(row.id)
    ElMessage.success('提交成功')
    loadList()
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') ElMessage.error(error?.message || '提交失败')
  }
}

const handleDelete = async row => {
  try {
    await ElMessageBox.confirm('确认删除这条报销记录吗？', '删除确认', { type: 'warning' })
    await deleteReimbursement(row.id)
    ElMessage.success('删除成功')
    loadList()
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') ElMessage.error(error?.message || '删除失败')
  }
}

const reloadDetail = async id => {
  try {
    const [detailRes, recordsRes] = await Promise.all([
      getReimbursementDetail(id),
      getReimbursementRecords(id)
    ])
    detail.value = responseData(detailRes)
    records.value = responseData(recordsRes) || []
    await loadList()
  } catch (error) {
    ElMessage.error(error?.message || '刷新详情失败')
  }
}

const openDetail = async id => {
  await reloadDetail(id)
  detailVisible.value = true
}

const money = value => Number(value || 0).toFixed(2)
const formatDate = value => {
  if (!value) return '-'
  const text = String(value)
  const match = text.match(/^(\d{4}-\d{2}-\d{2})/)
  if (match) return match[1]
  return text
}
const formatDateTime = value => value
  ? new Date(value).toLocaleString('zh-CN', { hour12: false })
  : '-'
const statusLabel = value => statusOptions.find(item => item.value === value)?.label || '未知'
const statusType = value => ({
  0: 'info',
  1: 'warning',
  2: 'success',
  3: 'danger',
  4: 'info',
  5: 'success'
})[value] || 'info'
onMounted(() => {
  loadExpenseTypes()
  loadList()
})
</script>

<style lang="less" scoped>
.reimburse-page {
  min-height: calc(100vh - 84px);
  background: #f5f7fa;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.page-header h2 {
  margin: 0 0 8px;
  color: #303133;
  font-size: 22px;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 13px;
}

.filter-card,
.table-card {
  background: #fff;
  border-radius: 6px;
  padding: 18px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, .05);
}

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

.filter-card :deep(.el-form-item) {
  margin-bottom: 0;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 18px;
}

@media (max-width: 768px) {
  .reimburse-page {
    padding: 12px;
  }

  .page-header {
    align-items: flex-start;
    gap: 12px;
  }

  .filter-card {
    overflow-x: auto;
  }
}
</style>
