<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { leaveRequestApi } from '@/api/hr.js'

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)

const searchForm = reactive({ type: '', status: '' })
const pagination = reactive({ page: 1, per_page: 20 })

const formRef = ref(null)
const form = reactive({ id: null, user_id: '', type: 1, start_date: '', end_date: '', days: 1, reason: '' })

const typeMap = { 1: '年假', 2: '事假', 3: '病假', 4: '调休', 5: '产假', 6: '婚假' }
const statusMap = { 0: '待审批', 1: '已批准', 2: '已拒绝' }
const statusType = { 0: 'warning', 1: 'success', 2: 'danger' }

const formRules = {
  user_id: [{ required: true, message: '请输入员工ID' }],
  type: [{ required: true, message: '请选择请假类型' }],
  start_date: [{ required: true, message: '请选择开始日期' }],
  end_date: [{ required: true, message: '请选择结束日期' }],
  days: [{ required: true, message: '请输入请假天数' }]
}

async function fetchList() {
  loading.value = true
  try {
    const res = await leaveRequestApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } finally { loading.value = false }
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() { Object.assign(searchForm, { type: '', status: '' }); handleSearch() }

function handleAdd() {
  isEdit.value = false
  Object.assign(form, { id: null, user_id: '', type: 1, start_date: '', end_date: '', days: 1, reason: '' })
  dialogVisible.value = true
}

function handleEdit(row) {
  isEdit.value = true
  Object.assign(form, { id: row.id, user_id: row.user_id, type: row.type, start_date: row.start_date, end_date: row.end_date, days: row.days, reason: row.reason })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) { await leaveRequestApi.update(form.id, form) } else { await leaveRequestApi.create(form) }
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功'); dialogVisible.value = false; fetchList()
    } finally { submitLoading.value = false }
  })
}

async function handleAudit(row, status) {
  const label = status === 1 ? '批准' : '拒绝'
  await ElMessageBox.confirm(`确定${label}该请假申请吗？`, '审批确认', { type: 'warning' })
  await leaveRequestApi.audit(row.id, { status })
  ElMessage.success(`${label}成功`); fetchList()
}

async function handleDelete(row) {
  await ElMessageBox.confirm('确定删除该请假申请吗？', '删除确认', { type: 'warning' })
  await leaveRequestApi.delete(row.id); ElMessage.success('删除成功'); fetchList()
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }
onMounted(() => { fetchList() })
</script>

<template>
  <div class="p-6 space-y-4">
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-select v-model="searchForm.type" placeholder="请假类型" clearable style="width:130px">
        <el-option v-for="(v, k) in typeMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-select v-model="searchForm.status" placeholder="审批状态" clearable style="width:130px">
        <el-option v-for="(v, k) in statusMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-3">
          <span class="font-medium text-gray-700">请假申请列表</span>
        </div>
        <el-button type="primary" @click="handleAdd">新增请假</el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width:100%">
          <el-table-column label="员工" min-width="100">
            <template #default="{ row }">{{ row.user?.name || '-' }}</template>
          </el-table-column>
          <el-table-column label="类型" width="80" align="center">
            <template #default="{ row }">
              <el-tag size="small">{{ typeMap[row.type] }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="start_date" label="开始日期" width="120" />
          <el-table-column prop="end_date" label="结束日期" width="120" />
          <el-table-column prop="days" label="天数" width="70" align="center" />
          <el-table-column prop="reason" label="事由" min-width="180" show-overflow-tooltip />
          <el-table-column label="状态" width="90" align="center">
            <template #default="{ row }">
              <el-tag :type="statusType[row.status]" size="small">{{ statusMap[row.status] }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="{ row }">
              <template v-if="row.status === 0">
                <el-button size="small" type="success" text @click="handleAudit(row, 1)">批准</el-button>
                <el-button size="small" type="danger" text @click="handleAudit(row, 2)">拒绝</el-button>
                <el-button size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
                <el-button size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.per_page" :total="total" :page-sizes="[10,20,50]" layout="total,sizes,prev,pager,next,jumper" background @current-change="handlePageChange" @size-change="handleSizeChange" />
      </div>
    </div>
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑请假' : '新增请假'" width="500px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-form-item label="员工ID" prop="user_id">
          <el-input v-model="form.user_id" placeholder="请输入员工ID" />
        </el-form-item>
        <el-form-item label="请假类型" prop="type">
          <el-select v-model="form.type" style="width:100%">
            <el-option v-for="(v, k) in typeMap" :key="k" :label="v" :value="Number(k)" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="start_date">
          <el-date-picker v-model="form.start_date" type="date" value-format="YYYY-MM-DD" style="width:100%" />
        </el-form-item>
        <el-form-item label="结束日期" prop="end_date">
          <el-date-picker v-model="form.end_date" type="date" value-format="YYYY-MM-DD" style="width:100%" />
        </el-form-item>
        <el-form-item label="天数" prop="days">
          <el-input-number v-model="form.days" :min="0.5" :max="365" :precision="1" :step="0.5" style="width:100%" />
        </el-form-item>
        <el-form-item label="事由">
          <el-input v-model="form.reason" type="textarea" :rows="3" placeholder="请输入请假事由" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
