<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Icon } from '@iconify/vue'
import { careExceptionApi } from '@/api/care.js'
import { customerApi } from '@/api/crm.js'

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const detailVisible = ref(false)
const submitLoading = ref(false)
const customers = ref([])
const currentDetail = ref(null)

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

const formRef = ref(null)
const form = reactive({
  id: null, customer_id: '', care_record_id: '', level: '', exception_type: '',
  description: '', action_taken: ''
})
const isEdit = ref(false)

const levelMap = { mild: '轻度', moderate: '中度', severe: '重度' }
const statusMap = { open: '待处理', resolved: '已解决' }

const levelTagClass = {
  mild: 'bg-yellow-100 text-yellow-700 border-yellow-200',
  moderate: 'bg-orange-100 text-orange-700 border-orange-200',
  severe: 'bg-red-100 text-red-700 border-red-200'
}
const levelRowClass = {
  mild: '',
  moderate: 'bg-orange-50',
  severe: 'bg-red-50'
}

const formRules = {
  customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
  level: [{ required: true, message: '请选择严重程度', trigger: 'change' }],
  exception_type: [{ required: true, message: '请输入异常类型', trigger: 'blur' }],
  description: [{ required: true, message: '请输入异常描述', trigger: 'blur' }]
}

async function fetchList() {
  loading.value = true
  try {
    const res = await careExceptionApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } catch {
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

async function fetchCustomers() {
  try {
    const res = await customerApi.getList({ per_page: 500, status: 3 })
    customers.value = res.data?.list || res.data?.data || []
  } catch {}
}

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

function handleAdd() {
  isEdit.value = false
  Object.assign(form, { id: null, customer_id: '', care_record_id: '', level: '', exception_type: '', description: '', action_taken: '' })
  dialogVisible.value = true
}

function handleEdit(row) {
  isEdit.value = true
  Object.assign(form, {
    id: row.id, customer_id: row.customer_id, care_record_id: row.care_record_id || '',
    level: row.level, exception_type: row.exception_type,
    description: row.description, action_taken: row.action_taken || ''
  })
  dialogVisible.value = true
}

function handleView(row) {
  currentDetail.value = row
  detailVisible.value = true
}

async function handleResolve(row) {
  await ElMessageBox.confirm(`确认将该异常标记为已解决？`, '标记解决', { type: 'success', confirmButtonText: '确认解决' })
  try {
    await careExceptionApi.resolve(row.id)
    ElMessage.success('已标记为解决')
    fetchList()
  } catch {
    ElMessage.error('操作失败')
  }
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) {
        await careExceptionApi.update(form.id, form)
      } else {
        await careExceptionApi.create(form)
      }
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      fetchList()
    } catch {
      ElMessage.error('操作失败')
    } finally {
      submitLoading.value = false
    }
  })
}

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

function getRowClass({ row }) {
  return levelRowClass[row.level] || ''
}

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" :value="c.id" />
      </el-select>
      <el-select v-model="searchForm.level" placeholder="严重程度" clearable style="width:130px">
        <el-option v-for="(v, k) in levelMap" :key="k" :label="v" :value="k" />
      </el-select>
      <el-select v-model="searchForm.status" placeholder="处理状态" clearable style="width:130px">
        <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" value-format="YYYY-MM-DD" placeholder="异常日期" style="width:160px" />
      <el-button type="primary" @click="handleSearch">
        <Icon icon="solar:magnifer-bold-duotone" class="mr-1" />查询
      </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-semibold text-gray-700">护理异常记录</span>
        </div>
        <el-button type="primary" @click="handleAdd">
          <Icon icon="solar:add-circle-bold-duotone" class="mr-1" />新建异常
        </el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width:100%" :row-class-name="getRowClass">
          <el-table-column label="客户" min-width="100">
            <template #default="{ row }">{{ row.customer_name || '-' }}</template>
          </el-table-column>
          <el-table-column label="严重程度" width="90" align="center">
            <template #default="{ row }">
              <span :class="['text-xs font-medium px-2 py-0.5 rounded border', levelTagClass[row.level]]">
                {{ levelMap[row.level] || '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="exception_type" label="异常类型" min-width="120" />
          <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
          <el-table-column prop="action_taken" label="处理措施" min-width="150" show-overflow-tooltip />
          <el-table-column label="状态" width="90" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 'resolved' ? 'success' : 'danger'" size="small">
                {{ statusMap[row.status] || '-' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="记录时间" min-width="160" />
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" text @click="handleView(row)">详情</el-button>
              <el-button v-if="row.status === 'open'" size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button v-if="row.status === 'open'" size="small" type="success" text @click="handleResolve(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="isEdit ? '编辑异常' : '新建异常'" width="560px" 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 style="width:100%" placeholder="请选择客户">
            <el-option v-for="c in customers" :key="c.id" :label="c.name" :value="c.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="严重程度" prop="level">
          <el-select v-model="form.level" style="width:100%">
            <el-option v-for="(v, k) in levelMap" :key="k" :label="v" :value="k" />
          </el-select>
        </el-form-item>
        <el-form-item label="异常类型" prop="exception_type">
          <el-input v-model="form.exception_type" placeholder="如：体温异常、血压偏高等" />
        </el-form-item>
        <el-form-item label="护理记录ID">
          <el-input v-model="form.care_record_id" placeholder="关联护理记录（可选）" />
        </el-form-item>
        <el-form-item label="异常描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="详细描述异常情况" />
        </el-form-item>
        <el-form-item label="处理措施">
          <el-input v-model="form.action_taken" type="textarea" :rows="2" 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>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" title="异常详情" width="500px">
      <template v-if="currentDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="客户">{{ currentDetail.customer_name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="严重程度">
            <span :class="['text-xs font-medium px-2 py-0.5 rounded border', levelTagClass[currentDetail.level]]">
              {{ levelMap[currentDetail.level] || '-' }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="异常类型">{{ currentDetail.exception_type || '-' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentDetail.status === 'resolved' ? 'success' : 'danger'" size="small">
              {{ statusMap[currentDetail.status] || '-' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="异常描述" :span="2">{{ currentDetail.description || '-' }}</el-descriptions-item>
          <el-descriptions-item label="处理措施" :span="2">{{ currentDetail.action_taken || '-' }}</el-descriptions-item>
          <el-descriptions-item label="记录时间">{{ currentDetail.created_at || '-' }}</el-descriptions-item>
          <el-descriptions-item label="解决时间">{{ currentDetail.resolved_at || '-' }}</el-descriptions-item>
        </el-descriptions>
      </template>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>
