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

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

const formRef = ref(null)
const form = reactive({ id: null, customer_id: '', type: 1, baby_name: '', baby_gender: '', baby_birthday: '', birth_weight: '', birth_method: '', allergies: '', medical_history: '', risk_level: 0, assessment: [] })
const isEdit = ref(false)
const formRules = {
  customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }]
}

const typeMap = { 1: '妈妈', 2: '宝宝' }
const genderMap = { 1: '男', 2: '女' }
const birthMethodMap = { 1: '顺产', 2: '剖宫产' }
const riskMap = { 0: '正常', 1: '低风险', 2: '高风险' }
const riskType = { 0: 'success', 1: 'warning', 2: 'danger' }

async function fetchList() {
  loading.value = true
  try { const res = await careProfileApi.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: '', type: '', risk_level: '' }); handleSearch() }
function handleAdd() { isEdit.value = false; Object.assign(form, { id: null, customer_id: '', type: 1, baby_name: '', baby_gender: '', baby_birthday: '', birth_weight: '', birth_method: '', allergies: '', medical_history: '', risk_level: 0, assessment: [] }); dialogVisible.value = true }
async function handleEdit(row) { isEdit.value = true; const res = await careProfileApi.getDetail(row.id); const d = res.data; Object.assign(form, { id: d.id, customer_id: d.customer_id, type: d.type, baby_name: d.baby_name || '', baby_gender: d.baby_gender || '', baby_birthday: d.baby_birthday || '', birth_weight: d.birth_weight || '', birth_method: d.birth_method || '', allergies: d.allergies || '', medical_history: d.medical_history || '', risk_level: d.risk_level || 0, assessment: d.assessment || [] }); 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 careProfileApi.update(form.id, form) } else { await careProfileApi.create(form) }
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功'); dialogVisible.value = false; fetchList()
    } finally { submitLoading.value = false }
  })
}

async function handleDetail(row) { const res = await careProfileApi.getDetail(row.id); detailData.value = res.data; detailVisible.value = true }

async function handleDelete(row) {
  await ElMessageBox.confirm('确定删除该护理档案吗？', '删除确认', { type: 'warning' })
  await careProfileApi.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() })
</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.type" placeholder="类型" clearable style="width:120px"><el-option v-for="(v,k) in typeMap" :key="k" :label="v" :value="Number(k)" /></el-select>
      <el-select v-model="searchForm.risk_level" placeholder="风险等级" clearable style="width:120px"><el-option v-for="(v,k) in riskMap" :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"></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="类型" width="80" align="center"><template #default="{ row }"><el-tag :type="row.type===1?'':'success'" size="small">{{ typeMap[row.type] }}</el-tag></template></el-table-column>
          <el-table-column prop="baby_name" label="宝宝名" min-width="100" />
          <el-table-column label="性别" width="70" align="center"><template #default="{ row }">{{ genderMap[row.baby_gender] || '-' }}</template></el-table-column>
          <el-table-column label="分娩方式" width="90"><template #default="{ row }">{{ birthMethodMap[row.birth_method] || '-' }}</template></el-table-column>
          <el-table-column label="风险等级" width="90" align="center"><template #default="{ row }"><el-tag :type="riskType[row.risk_level]" size="small">{{ riskMap[row.risk_level] }}</el-tag></template></el-table-column>
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" text @click="handleDetail(row)">详情</el-button>
              <el-button size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button 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="isEdit?'编辑档案':'新增档案'" width="650px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="80px">
        <el-row :gutter="16">
          <el-col :span="12"><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" :value="c.id" /></el-select></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="类型" prop="type"><el-select v-model="form.type" style="width:100%"><el-option v-for="(v,k) in typeMap" :key="k" :label="v" :value="Number(k)" /></el-select></el-form-item></el-col>
          <template v-if="form.type===2">
            <el-col :span="12"><el-form-item label="宝宝名"><el-input v-model="form.baby_name" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="性别"><el-select v-model="form.baby_gender" style="width:100%"><el-option label="男" :value="1" /><el-option label="女" :value="2" /></el-select></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="出生日期"><el-date-picker v-model="form.baby_birthday" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="出生体重"><el-input-number v-model="form.birth_weight" :min="0" :precision="2" style="width:100%" /><span style="margin-left:4px">kg</span></el-form-item></el-col>
          </template>
          <el-col :span="12"><el-form-item label="分娩方式"><el-select v-model="form.birth_method" clearable style="width:100%"><el-option label="顺产" :value="1" /><el-option label="剖宫产" :value="2" /></el-select></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="风险等级"><el-select v-model="form.risk_level" style="width:100%"><el-option v-for="(v,k) in riskMap" :key="k" :label="v" :value="Number(k)" /></el-select></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="过敏史"><el-input v-model="form.allergies" type="textarea" :rows="2" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="病史"><el-input v-model="form.medical_history" type="textarea" :rows="2" /></el-form-item></el-col>
        </el-row>
      </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-drawer v-model="detailVisible" title="护理档案详情" size="600px">
      <template v-if="detailData">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="客户">{{ detailData.customer?.name }}</el-descriptions-item>
          <el-descriptions-item label="类型">{{ typeMap[detailData.type] }}</el-descriptions-item>
          <el-descriptions-item label="宝宝名">{{ detailData.baby_name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="风险等级"><el-tag :type="riskType[detailData.risk_level]" size="small">{{ riskMap[detailData.risk_level] }}</el-tag></el-descriptions-item>
          <el-descriptions-item label="过敏史">{{ detailData.allergies || '-' }}</el-descriptions-item>
          <el-descriptions-item label="病史">{{ detailData.medical_history || '-' }}</el-descriptions-item>
        </el-descriptions>
        <h4 style="margin:16px 0 8px">护理计划</h4>
        <el-table :data="detailData.plans || []" border size="small">
          <el-table-column prop="plan_date" label="日期" width="110" />
          <el-table-column prop="stage" label="阶段" />
          <el-table-column label="护士"><template #default="{ row }">{{ row.nurse?.name || '-' }}</template></el-table-column>
          <el-table-column label="状态" width="80"><template #default="{ row }"><el-tag size="small">{{ ['待执行','执行中','已完成'][row.status] }}</el-tag></template></el-table-column>
        </el-table>
      </template>
    </el-drawer>
  </div>
</template>
