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

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

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

const formRef = ref(null)
const form = reactive({ shift_date: '', shift_type: 1, content: '', issues: '' })

const shiftTypeMap = { 1: '早班', 2: '中班', 3: '晚班', 4: '夜班' }
const shiftTagType = { 1: '', 2: 'warning', 3: 'danger', 4: 'info' }
const statusMap = { 0: '待确认', 1: '已确认' }
const statusType = { 0: 'warning', 1: 'success' }

const formRules = {
  shift_date: [{ required: true, message: '请选择交接日期' }],
  shift_type: [{ required: true, message: '请选择班次' }],
  content: [{ required: true, message: '请输入交接内容' }]
}

async function fetchList() {
  loading.value = true
  try {
    const res = await handoverApi.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, { shift_date: '', shift_type: '' }); handleSearch() }

function handleAdd() {
  Object.assign(form, { shift_date: '', shift_type: 1, content: '', issues: '' })
  dialogVisible.value = true
}

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

async function handleConfirm(row) {
  await ElMessageBox.confirm('确定确认接班吗？', '确认接班', { type: 'warning' })
  await handoverApi.confirm(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-date-picker v-model="searchForm.shift_date" type="date" value-format="YYYY-MM-DD" placeholder="交接日期" clearable style="width:160px" />
      <el-select v-model="searchForm.shift_type" placeholder="班次" clearable style="width:120px">
        <el-option v-for="(v, k) in shiftTypeMap" :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 prop="shift_date" label="交接日期" width="120" />
          <el-table-column label="班次" width="90" align="center">
            <template #default="{ row }">
              <el-tag :type="shiftTagType[row.shift_type]" size="small">{{ shiftTypeMap[row.shift_type] }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="交班人" min-width="100">
            <template #default="{ row }">{{ row.handover_user?.name || '-' }}</template>
          </el-table-column>
          <el-table-column label="接班人" min-width="100">
            <template #default="{ row }">{{ row.receiver_user?.name || '待确认' }}</template>
          </el-table-column>
          <el-table-column prop="content" label="交接内容" min-width="200" 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="120" fixed="right" align="center">
            <template #default="{ row }">
              <el-button v-if="row.status === 0" size="small" type="success" text @click="handleConfirm(row)">确认接班</el-button>
            </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="新增交接记录" width="600px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-form-item label="交接日期" prop="shift_date">
          <el-date-picker v-model="form.shift_date" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期" style="width:100%" />
        </el-form-item>
        <el-form-item label="班次" prop="shift_type">
          <el-select v-model="form.shift_type" style="width:100%">
            <el-option v-for="(v, k) in shiftTypeMap" :key="k" :label="v" :value="Number(k)" />
          </el-select>
        </el-form-item>
        <el-form-item label="交接内容" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="4" placeholder="请输入交接内容" />
        </el-form-item>
        <el-form-item label="遗留问题">
          <el-input v-model="form.issues" 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>
