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

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

const searchForm = reactive({ user_id: '', status: '', date_range: [] })
const pagination = reactive({ page: 1, per_page: 20 })

const formRef = ref(null)
const form = reactive({ user_id: '', attendance_date: '', clock_in: '', clock_out: '', status: 1, overtime_hours: 0, remark: '' })

const statusMap = { 1: '正常', 2: '迟到', 3: '早退', 4: '旷工', 5: '请假' }
const statusType = { 1: 'success', 2: 'warning', 3: 'warning', 4: 'danger', 5: 'info' }

async function fetchList() {
  loading.value = true
  try {
    const params = { ...pagination, user_id: searchForm.user_id, status: searchForm.status }
    if (searchForm.date_range?.length === 2) {
      params.start_date = searchForm.date_range[0]
      params.end_date = searchForm.date_range[1]
    }
    const res = await attendanceApi.getList(params)
    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, { user_id: '', status: '', date_range: [] }); handleSearch() }

async function handleClockIn() {
  try {
    await attendanceApi.clockIn()
    ElMessage.success('上班打卡成功'); fetchList()
  } catch (e) { ElMessage.error(e.response?.data?.message || '打卡失败') }
}

async function handleClockOut() {
  try {
    await attendanceApi.clockOut()
    ElMessage.success('下班打卡成功'); fetchList()
  } catch (e) { ElMessage.error(e.response?.data?.message || '打卡失败') }
}

function handleAdd() {
  Object.assign(form, { user_id: '', attendance_date: '', clock_in: '', clock_out: '', status: 1, overtime_hours: 0, remark: '' })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      await attendanceApi.create(form)
      ElMessage.success('创建成功'); dialogVisible.value = false; fetchList()
    } finally { submitLoading.value = false }
  })
}

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-input v-model="searchForm.user_id" placeholder="员工ID" clearable style="width:140px" />
      <el-select v-model="searchForm.status" placeholder="状态" clearable style="width:120px">
        <el-option v-for="(v, k) in statusMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-date-picker v-model="searchForm.date_range" type="daterange" value-format="YYYY-MM-DD" start-placeholder="开始日期" end-placeholder="结束日期" />
      <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">
          <el-button type="success" @click="handleClockIn">上班打卡</el-button>
          <el-button type="warning" @click="handleClockOut">下班打卡</el-button>
        </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 prop="attendance_date" label="考勤日期" width="120" />
          <el-table-column prop="clock_in" label="上班打卡" width="100" />
          <el-table-column prop="clock_out" label="下班打卡" width="100" />
          <el-table-column prop="overtime_hours" label="加班(h)" width="90" align="center" />
          <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 prop="remark" label="备注" min-width="150" show-overflow-tooltip />
          <el-table-column prop="created_at" label="创建时间" min-width="160" />
        </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="手动录入考勤" width="500px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="{ user_id: [{ required: true, message: '请输入员工ID' }], attendance_date: [{ required: true, message: '请选择考勤日期' }] }" 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="attendance_date">
          <el-date-picker v-model="form.attendance_date" type="date" value-format="YYYY-MM-DD" style="width:100%" />
        </el-form-item>
        <el-form-item label="上班时间">
          <el-time-picker v-model="form.clock_in" value-format="HH:mm:ss" placeholder="上班打卡时间" style="width:100%" />
        </el-form-item>
        <el-form-item label="下班时间">
          <el-time-picker v-model="form.clock_out" value-format="HH:mm:ss" placeholder="下班打卡时间" style="width:100%" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" style="width:100%">
            <el-option v-for="(v, k) in statusMap" :key="k" :label="v" :value="Number(k)" />
          </el-select>
        </el-form-item>
        <el-form-item label="加班时长">
          <el-input-number v-model="form.overtime_hours" :min="0" :max="24" :precision="1" :step="0.5" style="width:100%" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="2" />
        </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>
