<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reservationApi, roomApi } from '@/api/room.js'
import { customerApi } from '@/api/crm.js'

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

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

const formRef = ref(null)
const form = reactive({ id: null, customer_id: '', room_id: '', contract_id: '', check_in_date: '', check_out_date: '', remark: '' })
const isEdit = ref(false)
const formRules = {
  customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
  room_id: [{ required: true, message: '请选择房间', trigger: 'change' }],
  check_in_date: [{ required: true, message: '请选择入住日期', trigger: 'change' }],
  check_out_date: [{ required: true, message: '请选择退房日期', trigger: 'change' }]
}

const statusMap = { 0: '预定', 1: '已入住', 2: '已退房', 3: '已取消' }
const statusType = { 0: 'warning', 1: 'success', 2: 'info', 3: 'danger' }

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

async function fetchCustomers() { try { const res = await customerApi.getList({ per_page: 500 }); customers.value = res.data?.list || res.data?.data || [] } catch {} }
async function fetchRooms() { try { const res = await roomApi.getList({ per_page: 200 }); rooms.value = res.data?.list || res.data?.data || [] } catch {} }

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() { Object.assign(searchForm, { customer_id: '', room_id: '', status: '' }); handleSearch() }
function handleAdd() { isEdit.value = false; Object.assign(form, { id: null, customer_id: '', room_id: '', contract_id: '', check_in_date: '', check_out_date: '', remark: '' }); 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 reservationApi.update(form.id, form) } else { await reservationApi.create(form) }
      ElMessage.success(isEdit.value ? '更新成功' : '预定成功'); dialogVisible.value = false; fetchList(); fetchRooms()
    } finally { submitLoading.value = false }
  })
}

async function handleCheckIn(row) {
  await ElMessageBox.confirm(`确定为「${row.customer?.name}」办理入住？`, '入住确认', { type: 'info' })
  await reservationApi.checkIn(row.id); ElMessage.success('入住成功'); fetchList(); fetchRooms()
}

async function handleCheckOut(row) {
  await ElMessageBox.confirm(`确定为「${row.customer?.name}」办理退房？`, '退房确认', { type: 'warning' })
  await reservationApi.checkOut(row.id); ElMessage.success('退房成功'); fetchList(); fetchRooms()
}

async function handleCancel(row) {
  await ElMessageBox.confirm('确定取消该预定吗？', '取消确认', { type: 'warning' })
  await reservationApi.cancel(row.id, {}); ElMessage.success('已取消'); fetchList(); fetchRooms()
}

async function handleDelete(row) {
  await ElMessageBox.confirm('确定删除该预定吗？', '删除确认', { type: 'warning' })
  await reservationApi.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(); fetchCustomers(); fetchRooms() })
</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.customer_id" placeholder="选择客户" clearable filterable style="width:180px"><el-option v-for="c in customers" :key="c.id" :label="`${c.name}(${c.phone})`" :value="c.id" /></el-select>
      <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-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.customer?.name || '-' }}</template></el-table-column>
          <el-table-column label="房间" min-width="120"><template #default="{ row }">{{ row.room?.number || '-' }} ({{ row.room?.room_type?.name || '' }})</template></el-table-column>
          <el-table-column prop="check_in_date" label="入住日期" min-width="110" />
          <el-table-column prop="check_out_date" label="退房日期" min-width="110" />
          <el-table-column label="状态" width="100" 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="260" fixed="right" align="center">
            <template #default="{ row }">
              <el-button v-if="row.status===0" size="small" type="success" text @click="handleCheckIn(row)">入住</el-button>
              <el-button v-if="row.status===1" size="small" type="warning" text @click="handleCheckOut(row)">退房</el-button>
              <el-button v-if="row.status<2" size="small" type="info" text @click="handleCancel(row)">取消</el-button>
              <el-button v-if="row.status!==1" size="small" type="danger" text @click="handleDelete(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="550px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="80px">
        <el-form-item label="客户" prop="customer_id"><el-select v-model="form.customer_id" filterable style="width:100%"><el-option v-for="c in customers" :key="c.id" :label="`${c.name}(${c.phone})`" :value="c.id" /></el-select></el-form-item>
        <el-form-item label="房间" prop="room_id"><el-select v-model="form.room_id" filterable style="width:100%"><el-option v-for="r in rooms.filter(r=>r.status===1)" :key="r.id" :label="`${r.number} (${r.room_type?.name||''})`" :value="r.id" /></el-select></el-form-item>
        <el-form-item label="入住日期" prop="check_in_date"><el-date-picker v-model="form.check_in_date" type="date" value-format="YYYY-MM-DD" style="width:100%" /></el-form-item>
        <el-form-item label="退房日期" prop="check_out_date"><el-date-picker v-model="form.check_out_date" type="date" value-format="YYYY-MM-DD" 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>
