<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { customerOutingApi } 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 returnVisible = ref(false)
const currentOuting = ref(null)
const customers = ref([])

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

const formRef = ref(null)
const form = reactive({
  customer_id: '', outing_time: '', expected_return: '', reason: ''
})
const returnForm = reactive({ actual_return: '', remark: '' })

const formRules = {
  customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
  outing_time: [{ required: true, message: '请选择外出时间', trigger: 'change' }],
  expected_return: [{ required: true, message: '请选择预计返回时间', trigger: 'change' }]
}

const statusMap = { pending: '待出发', out: '外出中', returned: '已返回' }
const statusType = { pending: 'warning', out: 'primary', returned: 'success' }

async function fetchList() {
  loading.value = true
  try {
    const res = await customerOutingApi.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 {}
}

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

function handleAdd() {
  Object.assign(form, { customer_id: '', outing_time: '', expected_return: '', reason: '' })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      await customerOutingApi.create(form)
      ElMessage.success('外出申请已创建')
      dialogVisible.value = false; fetchList()
    } finally { submitLoading.value = false }
  })
}

function openReturn(row) {
  currentOuting.value = row
  Object.assign(returnForm, { actual_return: '', remark: '' })
  returnVisible.value = true
}

async function submitReturn() {
  if (!returnForm.actual_return) { ElMessage.warning('请选择实际返回时间'); return }
  await customerOutingApi.recordBack(currentOuting.value.id, returnForm)
  ElMessage.success('返回登记成功')
  returnVisible.value = false; fetchList()
}

async function handleDelete(row) {
  await ElMessageBox.confirm(`确定删除该外出记录吗？`, '删除确认', { type: 'warning' })
  try {
    await customerOutingApi.getDetail(row.id)
    ElMessage.error('暂不支持删除，请联系管理员')
  } catch (e) {
    console.error(e)
  }
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }

onMounted(() => { fetchList(); fetchCustomers() })
</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="k" />
      </el-select>
      <el-date-picker v-model="searchForm.date" type="date" placeholder="外出日期" value-format="YYYY-MM-DD" style="width:150px" />
      <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-2">
          <span class="w-1 h-5 bg-rose-500 rounded-full inline-block"></span>
          <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 || row.customer?.name || '-' }}</template>
          </el-table-column>
          <el-table-column prop="outing_time" label="外出时间" min-width="160" />
          <el-table-column prop="expected_return" label="预计返回" min-width="160" />
          <el-table-column prop="actual_return" label="实际返回" min-width="160">
            <template #default="{ row }">{{ row.actual_return || '-' }}</template>
          </el-table-column>
          <el-table-column prop="reason" label="外出原因" min-width="150" 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="180" fixed="right" align="center">
            <template #default="{ row }">
              <el-button v-if="row.status === 'out'" size="small" type="success" text @click="openReturn(row)">登记返回</el-button>
              <el-button v-if="row.status !== 'returned'" 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>

    <!-- New Outing Dialog -->
    <el-dialog v-model="dialogVisible" title="新建外出申请" width="520px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="客户" prop="customer_id">
          <el-select v-model="form.customer_id" filterable placeholder="请选择客户" 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="outing_time">
          <el-date-picker v-model="form.outing_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择外出时间" style="width:100%" />
        </el-form-item>
        <el-form-item label="预计返回" prop="expected_return">
          <el-date-picker v-model="form.expected_return" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择预计返回时间" 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>

    <!-- Return Dialog -->
    <el-dialog v-model="returnVisible" title="登记返回" width="420px" destroy-on-close>
      <el-form label-width="100px">
        <el-form-item label="实际返回时间">
          <el-date-picker v-model="returnForm.actual_return" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择实际返回时间" style="width:100%" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="returnForm.remark" type="textarea" :rows="2" placeholder="可选备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="returnVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReturn">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
