<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { callRecordApi } 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 searchForm = reactive({ customer_id: '', handled: '', date: '' })
const pagination = reactive({ page: 1, per_page: 20 })

const formRef = ref(null)
const form = reactive({
  customer_id: '', room_no: '', call_type: 'nurse', content: ''
})
const formRules = {
  customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
  call_type: [{ required: true, message: '请选择呼叫类型', trigger: 'change' }],
  content: [{ required: true, message: '请输入呼叫内容', trigger: 'blur' }]
}

const callTypeMap = { nurse: '护理', meal: '膳食', service: '服务', emergency: '紧急' }
const callTypeTagType = { nurse: 'primary', meal: 'success', service: 'info', emergency: 'danger' }

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

function handleAdd() {
  Object.assign(form, { customer_id: '', room_no: '', call_type: 'nurse', content: '' })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      await callRecordApi.create(form)
      ElMessage.success('呼叫记录已创建')
      dialogVisible.value = false; fetchList()
    } finally { submitLoading.value = false }
  })
}

async function handleHandle(row) {
  await ElMessageBox.confirm(`确定标记该呼叫为「已处理」吗？`, '处理确认', { type: 'info' })
  try {
    await callRecordApi.handle(row.id, {})
    ElMessage.success('已标记为处理')
    fetchList()
  } 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.handled" placeholder="处理状态" clearable style="width:120px">
        <el-option label="未处理" :value="0" />
        <el-option label="已处理" :value="1" />
      </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%" :row-class-name="({ row }) => !row.handled ? 'bg-rose-50/40' : ''">
          <el-table-column label="客户" min-width="100">
            <template #default="{ row }">{{ row.customer_name || row.customer?.name || '-' }}</template>
          </el-table-column>
          <el-table-column prop="room_no" label="房间号" width="90" align="center" />
          <el-table-column label="呼叫类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="callTypeTagType[row.call_type]" size="small">{{ callTypeMap[row.call_type] }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="content" label="呼叫内容" min-width="180" show-overflow-tooltip />
          <el-table-column label="处理状态" width="95" align="center">
            <template #default="{ row }">
              <el-tag :type="row.handled ? 'success' : 'danger'" size="small">{{ row.handled ? '已处理' : '未处理' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="处理人" min-width="100">
            <template #default="{ row }">{{ row.handler_name || row.handler?.name || '-' }}</template>
          </el-table-column>
          <el-table-column prop="handled_at" label="处理时间" min-width="160">
            <template #default="{ row }">{{ row.handled_at || '-' }}</template>
          </el-table-column>
          <el-table-column prop="created_at" label="呼叫时间" min-width="160" />
          <el-table-column label="操作" width="120" fixed="right" align="center">
            <template #default="{ row }">
              <el-button v-if="!row.handled" size="small" type="success" text @click="handleHandle(row)">标记处理</el-button>
              <span v-else class="text-gray-400 text-xs">已完成</span>
            </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 Call Record Dialog -->
    <el-dialog v-model="dialogVisible" title="新建呼叫记录" width="500px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <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="房间号">
          <el-input v-model="form.room_no" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="呼叫类型" prop="call_type">
          <el-select v-model="form.call_type" style="width:100%">
            <el-option v-for="(v, k) in callTypeMap" :key="k" :label="v" :value="k" />
          </el-select>
        </el-form-item>
        <el-form-item label="呼叫内容" prop="content">
          <el-input v-model="form.content" 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>
