<template>
  <el-drawer
    v-model="dialogVisible"
    :title="title"
    resizable
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :destroy-on-close="true"
    size="85%"
    :before-close="handleClosed"
  >
    <div class="asphyxiation-form">
      <h1 class="form-title">防噎食评估表</h1>
      <!-- 基本信息 -->
      <el-row :gutter="40">
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>长者姓名</text>
          <search-the-elderly ref="selectElderRef" :disabled="isDetail" @update_elder="elderUp"
            v-model="dataForm.elderName" :tId="dataForm.tenantId" />
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>性别</text>
          <el-input v-if="!isDetail" v-model="dataForm.elderSex" disabled />
          <el-text v-else disabled="">{{ dataForm.elderSex }}</el-text>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>年龄</text>
          <el-input v-if="!isDetail" v-model="dataForm.elderAge" disabled />
          <el-text v-else disabled="">{{ dataForm.elderAge }}</el-text>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>房号/床号</text>
          <el-input v-if="!isDetail" v-model="dataForm.bedName" disabled />
          <el-text v-else disabled="">{{ dataForm.bedName }}</el-text>
        </el-col>
      </el-row>

      <!-- 吞咽功能评估表格 -->
      <div class="assessment-section">
        <div class="section-title">吞咽功能评估</div>
        <div class="assessment-table">
          <table>
            <thead>
              <tr>
                <th class="level-col">分级</th>
                <th class="judge-col">判断</th>
                <th class="rating-col">功能评级</th>
                <th class="score-col">得分</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in swallowLevels" :key="index">
                <td class="level">{{ item.level }}</td>
                <td class="judge">{{ item.judge }}</td>
                <td class="rating">{{ item.rating }}</td>
                <td class="score">
                  <el-radio
                    v-model="form.assessment.level" :value="item.score" :disabled="isDetail"
                    @change="updateRiskLevel">
                    {{ item.score }}
                  </el-radio>
                </td>
              </tr>
              <tr class="result-row">
                <td colspan="3" class="result-label">结果分级</td>
                <td class="result-content">
                  I级(5秒内)为无风险；I级(5秒以上)为低风险，II级为中风险；III级、IV级、V级为高风险
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 评估记录 -->
      <div class="assessment-records">
        <div class="record-section">
          <div class="record-header">评估记录</div>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="评估日期">
                <el-date-picker v-model="form.assessment.assessDate" type="date" :disabled="isDetail" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="评估人签名">
                <el-input v-model="form.assessment.assessor" :disabled="isDetail" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="评级结果">
                <el-input v-model="form.assessment.level" disabled />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="风险程度">
                <el-tag :type="getRiskTagType(form.assessment.level)">
                  {{ getRiskText(form.assessment.level) }}
                </el-tag>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="建议饮食">
                <el-checkbox-group v-model="form.assessment.dietSuggestions" :disabled="isDetail">
                  <el-checkbox label="普食">普食</el-checkbox>
                  <el-checkbox label="软食">软食</el-checkbox>
                  <el-checkbox label="半流食">半流食</el-checkbox>
                  <el-checkbox label="流食">流食</el-checkbox>
                  <el-checkbox label="鼻饲">鼻饲</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 预防措施 -->
      <div class="prevention-section">
        <div class="section-title">预防措施：</div>
        <el-checkbox-group v-model="form.preventionMeasures" :disabled="isDetail" class="prevention-group">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <el-checkbox label="合理控制食物大小">合理控制食物大小</el-checkbox>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <el-checkbox label="细嚼慢咽">细嚼慢咽</el-checkbox>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <el-checkbox label="进食时避免说话、大笑">进食时避免说话、大笑</el-checkbox>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <el-checkbox label="进食时少量喝汤便于顺利咽下食物">进食时少量喝汤便于顺利咽下食物</el-checkbox>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <el-checkbox label="饭后漱口，避免食物滞留口中">饭后漱口，避免食物滞留口中</el-checkbox>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <el-checkbox label="用餐时调整体位，端坐位或半坐卧位，卧床者摇高床头>60°">用餐时调整体位，端坐位或半坐卧位，卧床者摇高床头&gt;60°</el-checkbox>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-checkbox label="常多练习张口闭口、伸缩舌头、微笑动作，以训练口腔及面部肌肉">常多练习张口闭口、伸缩舌头、微笑动作，以训练口腔及面部肌肉</el-checkbox>
            </el-col>
          </el-row>
        </el-checkbox-group>
      </div>

    
          
    </div>

    <template #footer>
      <el-button @click="handleClosed">关闭</el-button>
      <el-button v-if="isDetail" type="success" @click="handleExport">打印</el-button>
      <el-button style="margin-left: 22px;margin-right: 30px" v-loading="formLoading" type="primary"
        v-show="!isDetail" @click="submitForm">确定</el-button>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import dayjs from 'dayjs'
import {
  asphyxiationCreate,
  asphyxiationGetById,
  asphyxiationUpdate
} from "@/api/social-work";

const message = useMessage()
const { t } = useI18n()
const title = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const selectElderRef = ref()
const isDetail = ref(false)
const formLoading = ref(false)

let dataForm = ref({
  id: undefined,
  elderName: '',
  elderSex: '',
  elderAge: '',
  bedName: '',
  elderId: '',
  tenantId: undefined
})

const elderUp = (e: any) => {
  dataForm.value.elderName = e.elderName
  dataForm.value.elderId = e.id
  dataForm.value.elderSex = e.elderSex === 1 ? '男' : '女'
  dataForm.value.bedName = e.bedName || ''
  dataForm.value.elderAge = e.elderAge
}

// 吞咽功能评估等级定义
const swallowLevels = [
  { level: 'I', judge: '坐位，5秒之内能不呛的一次性饮下 30mL 温水', rating: '1 级(正常)', score: 1 },
  { level: 'I', judge: '坐位，5秒以上能不呛的一次性饮下 30mL 温水', rating: '1 级(优)', score: 2 },
  { level: 'II', judge: '分两次喝完无噎呛', rating: '2 级(良)', score: 3 },
  { level: 'III', judge: '能一次喝完，但有噎呛', rating: '3 级(中)', score: 4 },
  { level: 'IV', judge: '分两次以上喝完，且有噎呛', rating: '4 级(可)', score: 5 },
  { level: 'V', judge: '常常噎呛，难以全部喝完', rating: '5 级(差)', score: 6 }
]

// 表单数据
const form = reactive({
  assessment: {
    assessDate: '',
    assessor: '',
    level: '',
    dietSuggestions: []
  },
  preventionMeasures: [],
  riskLevel: ''
})

// 获取风险等级文本
const getRiskText = (riskLevel: string) => {
  switch (riskLevel) {
    case 1: return '无风险'
    case 2: return '低风险'
    case 3: return '中度风险'
    case 4: return '高风险'
    case 5: return '高风险'
    case 6: return '高风险'
    default: return '-'
  }
}

// 获取风险等级标签类型
const getRiskTagType = (riskLevel: string) => {
  switch (riskLevel) {
    case 1: return 'success'
    case 2: return 'info'
    case 3: return 'warning'
    case 4: return 'danger'
    case 5: return 'danger'
    case 6: return 'danger'
    default: return ''
  }
}

// 更新风险等级
const updateRiskLevel = () => {
  const level = form.assessment.level
  if (!level) return

  // 根据选中的等级判断风险程度
  // I级(5秒内)为无风险；I级(5秒以上)为低风险，II级为中风险；III级、IV级、V级为高风险
  const score = Number(form.assessment.level)
  if (!score) return

  if (score === 1) {
    form.riskLevel = 'none'
  } else if (score === 2) {
    form.riskLevel = 'low'
  } else if (score === 3) {
    form.riskLevel = 'medium'
  } else {
    form.riskLevel = 'high'
  }
}

/** 将表单数据序列化为 JSON 对象 */
const serializeFormData = () => {
  return {
    assessment: {
      assessDate: form.assessment.assessDate ? dayjs(form.assessment.assessDate).format('YYYY-MM-DD') : '',
      assessor: form.assessment.assessor || '',
      level: form.assessment.level || '',
      dietSuggestions: form.assessment.dietSuggestions || []
    },
    preventionMeasures: form.preventionMeasures || [],
    riskLevel: form.riskLevel
  }
}

/** 将 JSON 对象反序列化为表单数据 */
const deserializeFormData = (formData: Record<string, any>) => {
  if (!formData) return

  if (formData.assessment) {
    form.assessment.assessDate = formData.assessment.assessDate ? dayjs(formData.assessment.assessDate).toDate() : ''
    form.assessment.assessor = formData.assessment.assessor || ''
    form.assessment.level = formData.assessment.level || ''
    form.assessment.dietSuggestions = formData.assessment.dietSuggestions || []
  }
  form.preventionMeasures = formData.preventionMeasures || []
  form.riskLevel = formData.riskLevel || ''
}

/** 重置表单数据 */
const resetForm = () => {
  dataForm.value = {
    id: undefined,
    elderName: '',
    elderSex: '',
    elderAge: '',
    bedName: '',
    elderId: '',
    tenantId: undefined
  }
  formRef.value?.resetFields()

  form.assessment = {
    assessDate: '',
    assessor: '',
    level: '',
    dietSuggestions: []
  }
  form.preventionMeasures = []
  form.riskLevel = ''
}

/** 打开弹窗 */
const open = async (tenantId: any, id?: any, detail: boolean = false) => {
  resetForm()
  dialogVisible.value = true
  dataForm.value.id = id || undefined
  dataForm.value.tenantId = tenantId
  isDetail.value = detail
  if (id) {
    title.value = "编辑-防噎食评估表"
    await loadData(id)
  } else {
    title.value = "新增-防噎食评估表"
  }
}

/** 加载评估数据 */
const loadData = async (id: number) => {
  try {
    const res = await asphyxiationGetById(id)
    if (res) {
      dataForm.value.elderName = res.elderName || ''
      dataForm.value.elderId = res.elderId || ''
      dataForm.value.elderSex = res.elderSex || ''
      dataForm.value.bedName = res.bedName || ''
      dataForm.value.elderAge = res.elderAge || ''
      await selectElderRef.value.upData(res.elderName, res.elderId)
      if (res.assessData) {
        const formData = JSON.parse(res.assessData)
        deserializeFormData(formData)
      }
    }
  } catch (error) {
    message.error('加载评估数据失败')
  }
}

defineExpose({ open })

const emit = defineEmits(['success'])

/** 提交表单 */
const submitForm = async () => {
  if (formLoading.value) return
  if (!dataForm.value.elderId) {
    message.error('请选择长者')
    return
  }

  formLoading.value = true
  try {
    const assessData = serializeFormData()
    const tempParams = {
      ...dataForm.value,
      assessData: JSON.stringify(assessData),
      riskLevel: form.riskLevel,
      assessor: form.assessment.assessor || '',
      assessDate: form.assessment.assessDate ? dayjs(form.assessment.assessDate).format('YYYY-MM-DD') : ''
    }

    if (dataForm.value.id) {
      const res = await asphyxiationUpdate(tempParams)
      if (res) {
        message.success(t('common.updateSuccess'))
        dialogVisible.value = false
        emit('success')
      }
    } else {
      const res = await asphyxiationCreate(tempParams)
      if (res) {
        message.success(t('common.createSuccess'))
        dialogVisible.value = false
        emit('success')
      }
    }
  } finally {
    setTimeout(() => {
      formLoading.value = false
    }, 500)
  }
}

// 关闭表单
const handleClosed = () => {
  dialogVisible.value = false
  resetForm()
}

/** 导出打印 */
const handleExport = () => {
  const printWindow = window.open('', '_blank')
  if (!printWindow) {
    message.error('请允许弹出窗口')
    return
  }

  const assessmentRows = swallowLevels.map((item, index) => {
    const checked = form.assessment.level === item.level ? '☑' : '☐'
    return `
      <tr>
        <td class="level">${item.level}</td>
        <td class="judge">${item.judge}</td>
        <td class="rating">${item.rating}</td>
        <td class="score">${checked}</td>
      </tr>
    `
  }).join('')

  const dietOptions = ['普食', '软食', '半流食', '流食', '鼻饲']
  const dietChecks = dietOptions.map(diet => {
    const checked = form.assessment.dietSuggestions.includes(diet) ? '☑' : '☐'
    return `${checked}${diet}`
  }).join(' ')

  const recordSection = `
    <div class="record-section">
      <div class="record-title">评估记录</div>
      <div class="record-row">
        <span class="record-label">评估日期：</span>
        <span class="record-value">${form.assessment.assessDate ? dayjs(form.assessment.assessDate).format('YYYY-MM-DD') : ''}</span>
        <span class="record-label">评估人签名：</span>
        <span class="record-value">${form.assessment.assessor || ''}</span>
        <span class="record-label">评级结果：</span>
        <span class="record-value">${form.assessment.level || ''}</span>
        <span class="record-label">风险程度：</span>
        <span class="record-value">${getRiskText(form.assessment.level)}</span>
      </div>
      <div class="record-row">
        <span class="record-label">建议饮食：</span>
        <span class="record-value">${dietChecks}</span>
      </div>
    </div>
  `

  const preventionOptions = [
    '合理控制食物大小',
    '细嚼慢咽',
    '进食时避免说话、大笑',
    '进食时少量喝汤便于顺利咽下食物',
    '饭后漱口，避免食物滞留口中',
    '用餐时调整体位，端坐位或半坐卧位，卧床者摇高床头>60°',
    '常多练习张口闭口、伸缩舌头、微笑动作，以训练口腔及面部肌肉'
  ]
  const preventionChecks = preventionOptions.map(option => {
    const checked = form.preventionMeasures.includes(option) ? '☑' : '☐'
    return `<div class="prevention-item">${checked}${option}</div>`
  }).join('')

  const printContent = `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>防噎食评估表 - ${dataForm.value.elderName || ''}</title>
      <style>
        @media print {
          @page { size: A4 portrait; margin: 10mm; }
        }
        body {
          font-family: 'SimSun', 'Microsoft YaHei', serif;
          font-size: 10pt;
          line-height: 1.4;
          color: #333;
        }
        .header {
          text-align: center;
          margin-bottom: 15px;
          border-bottom: 2px solid #333;
          padding-bottom: 10px;
        }
        .title {
          font-size: 18pt;
          font-weight: bold;
          margin-bottom: 10px;
        }
        .basic-info {
          display: flex;
          justify-content: space-between;
          margin-bottom: 15px;
          flex-wrap: wrap;
        }
        .info-item {
          margin-right: 20px;
          margin-bottom: 5px;
        }
        .info-label {
          font-weight: bold;
        }
        .section-title {
          font-size: 12pt;
          font-weight: bold;
          margin: 15px 0 10px 0;
          border-left: 4px solid #333;
          padding-left: 8px;
        }
        table {
          width: 100%;
          border-collapse: collapse;
          margin-bottom: 15px;
        }
        th, td {
          border: 1px solid #333;
          padding: 8px;
          text-align: center;
        }
        th {
          background-color: #f5f5f5;
          font-weight: bold;
        }
        .level-col { width: 8%; }
        .judge-col { width: 35%; }
        .rating-col { width: 20%; }
        .score-col { width: 12%; }
        .result-row td {
          background-color: #f9f9f9;
        }
        .record-section {
          margin-bottom: 15px;
          padding: 10px;
          border: 1px solid #ddd;
        }
        .record-title {
          font-weight: bold;
          margin-bottom: 8px;
          border-bottom: 1px solid #eee;
          padding-bottom: 5px;
        }
        .record-row {
          margin-bottom: 5px;
        }
        .record-label {
          font-weight: bold;
        }
        .prevention-section {
          margin-top: 15px;
        }
        .prevention-item {
          margin-bottom: 5px;
        }
      </style>
    </head>
    <body>
      <div class="header">
        <div class="title">防噎食评估表</div>
      </div>
      <div class="basic-info">
        <div class="info-item"><span class="info-label">姓名：</span>${dataForm.value.elderName || ''}</div>
        <div class="info-item"><span class="info-label">性别：</span>${dataForm.value.elderSex || ''}</div>
        <div class="info-item"><span class="info-label">年龄：</span>${dataForm.value.elderAge || ''}</div>
        <div class="info-item"><span class="info-label">房号/床号：</span>${dataForm.value.bedName || ''}</div>
      </div>

      <div class="section-title">吞咽功能评估</div>
      <table>
        <thead>
          <tr>
            <th class="level-col">分级</th>
            <th class="judge-col">判断</th>
            <th class="rating-col">功能评级</th>
            <th class="score-col">得分</th>
          </tr>
        </thead>
        <tbody>
          ${assessmentRows}
          <tr class="result-row">
            <td colspan="3" style="font-weight:bold;">结果分级</td>
            <td style="text-align:left;">
              I级(5秒内)为无风险；I级(5秒以上)为低风险，II级为中风险；III级、IV级、V级为高风险
            </td>
          </tr>
        </tbody>
      </table>

      <div class="section-title">评估记录</div>
      ${recordSection}

      <div class="section-title prevention-section">预防措施</div>
      ${preventionChecks}
    </body>
    </html>
  `

  printWindow.document.write(printContent)
  printWindow.document.close()
  printWindow.focus()
  setTimeout(() => {
    printWindow.print()
  }, 250)
}
</script>

<style scoped lang="scss">
.asphyxiation-form {
  padding: 0 20px;

  .form-title {
    text-align: center;
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #333;
  }

  .row {
    display: flex;
    align-items: center;
    margin-bottom: 15px;

    text {
      width: 100px;
      flex-shrink: 0;
      color: #606266;
    }

    .el-input,
    .el-text {
      flex: 1;
    }
  }

  .assessment-section {
    margin-top: 20px;

    .section-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 15px;
      color: #333;
      border-left: 4px solid #409eff;
      padding-left: 10px;
    }

    .assessment-table {
      table {
        width: 100%;
        border-collapse: collapse;
        border: 1px solid #dcdfe6;

        th,
        td {
          border: 1px solid #dcdfe6;
          padding: 10px;
          text-align: center;
        }

        th {
          background-color: #f5f7fa;
          font-weight: bold;
          color: #606266;
        }

        .level-col,
        .score-col {
          width: 10%;
        }

        .judge-col {
          width: 40%;
        }

        .rating-col {
          width: 20%;
        }

        .result-row {
          td {
            background-color: #f5f7fa;
          }

          .result-label {
            font-weight: bold;
          }

          .result-content {
            text-align: left;
            font-size: 12px;
          }
        }
      }
    }
  }

  .assessment-records {
    margin-top: 20px;

    .record-section {
      margin-bottom: 20px;
      padding: 15px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;

      .record-header {
        font-size: 14px;
        font-weight: bold;
        margin-bottom: 15px;
        color: #409eff;
        border-bottom: 1px solid #e4e7ed;
        padding-bottom: 10px;
      }
    }
  }

  .prevention-section {
    margin-top: 20px;

    .section-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 15px;
      color: #333;
      border-left: 4px solid #409eff;
      padding-left: 10px;
    }

    .prevention-group {
      .el-checkbox {
        margin-bottom: 10px;
        margin-right: 20px;
      }
    }
  }

  .api-params-section {
    margin-top: 30px;
    padding: 20px;
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
    border-radius: 4px;

    .section-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 15px;
      color: #333;
      border-left: 4px solid #67c23a;
      padding-left: 10px;
    }

    .risk-rules {
      margin-top: 15px;
      padding: 10px;
      background-color: #fff;
      border-radius: 4px;

      .rules-title {
        font-weight: bold;
        margin-bottom: 10px;
        color: #606266;
      }

      .rule-tag {
        margin-right: 10px;
        margin-bottom: 5px;
      }
    }
  }
}
</style>
