<template>
  <el-drawer
    v-model="dialogVisible"
    :title="title"
    resizable
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :destroy-on-close="true"
    size="70%"
    :before-close="handleClosed"
  >

    <div class="mmse-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.contractNumber" disabled />
            <el-text v-else disabled="">{{dataForm.contractNumber}}</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" :model-value="dayjs(dataForm.checkInTime).format('YYYY-MM-DD')=='Invalid Date'?'':dayjs(dataForm.checkInTime).format('YYYY-MM-DD')" disabled />
            <el-text v-else disabled="">{{dayjs(dataForm.checkInTime).format('YYYY-MM-DD')}}</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>

      <el-row :gutter="40">
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>评估人</text>
          <el-input :disabled="isDetail" v-model="form.assessor"  />
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="row">
          <text>评估日期</text>
          <el-date-picker :disabled="isDetail" v-model="form.assessDate" type="date" style="width: 100%;"/>

        </el-col>
      </el-row>

        <!-- 表单内容区域 -->
        <div class="form-body">
          <!-- 总分显示 -->
          <div class="total-score-section">
            <div class="total-score">
              <span class="score-label">总分：</span>
              <span class="score-value">{{ totalScore }}</span>
              <span class="score-max">/ 30分</span>
            </div>

          </div>

          <!-- 一、定向力 (10分) -->
          <div class="section">
            <div class="section-title">一、定向力（10分）</div>

            <div class="form-item">
              <span class="item-number">1.</span>
              <span class="item-label">时间定向（5分）：</span>
              <div class="score-group">
                <div class="score-row">
                  <span>今年是哪一年？</span>
                  <el-radio-group :disabled="isDetail" v-model="form.orientation.year" size="small">
                    <el-radio :value="1">正确(1分)</el-radio>
                    <el-radio :value="0">错误(0分)</el-radio>
                  </el-radio-group>
                </div>
                <div class="score-row">
                  <span>现在是什么季节？</span>
                  <el-radio-group  :disabled="isDetail" v-model="form.orientation.season" size="small">
                    <el-radio :value="1">正确(1分)</el-radio>
                    <el-radio :value="0">错误(0分)</el-radio>
                  </el-radio-group>
                </div>
                <div class="score-row">
                  <span>现在是几月份？</span>
                  <el-radio-group :disabled="isDetail" v-model="form.orientation.month" size="small">
                    <el-radio :value="1">正确(1分)</el-radio>
                    <el-radio :value="0">错误(0分)</el-radio>
                  </el-radio-group>
                </div>
                <div class="score-row">
                  <span>今天是几号？</span>
                  <el-radio-group :disabled="isDetail" v-model="form.orientation.day" size="small">
                    <el-radio :value="1">正确(1分)</el-radio>
                    <el-radio :value="0">错误(0分)</el-radio>
                  </el-radio-group>
                </div>
                <div class="score-row">
                  <span>今天是星期几？</span>
                  <el-radio-group :disabled="isDetail" v-model="form.orientation.weekDay" size="small">
                    <el-radio :value="1">正确(1分)</el-radio>
                    <el-radio :value="0">错误(0分)</el-radio>
                  </el-radio-group>
                </div>
              </div>
            </div>

            <div class="form-item">
              <span class="item-number">2.</span>
              <span class="item-label">地点定向（5分）：</span>
              <div class="score-group">
                <div class="score-row">
                  <span>你住在那个省？</span>
                  <el-radio-group :disabled="isDetail" v-model="form.orientation.province" size="small">
                    <el-radio :value="1">正确(1分)</el-radio>
                    <el-radio :value="0">错误(0分)</el-radio>
                  </el-radio-group>
                </div>
                <div class="score-row">
                  <span>你住在那个县（区）？</span>
                  <el-radio-group :disabled="isDetail" v-model="form.orientation.county" size="small">
                    <el-radio :value="1">正确(1分)</el-radio>
                    <el-radio :value="0">错误(0分)</el-radio>
                  </el-radio-group>
                </div>
                <div class="score-row">
                  <span>你住在那个乡（街道）？</span>
                  <el-radio-group :disabled="isDetail" v-model="form.orientation.town" size="small">
                    <el-radio :value="1">正确(1分)</el-radio>
                    <el-radio :value="0">错误(0分)</el-radio>
                  </el-radio-group>
                </div>
                <div class="score-row">
                  <span>咱们现在在哪个养老院？</span>
                  <el-radio-group :disabled="isDetail" v-model="form.orientation.nursingHome" size="small">
                    <el-radio :value="1">正确(1分)</el-radio>
                    <el-radio :value="0">错误(0分)</el-radio>
                  </el-radio-group>
                </div>
                <div class="score-row">
                  <span>咱们现在在第几层楼？</span>
                  <el-radio-group :disabled="isDetail" v-model="form.orientation.floor" size="small">
                    <el-radio :value="1">正确(1分)</el-radio>
                    <el-radio :value="0">错误(0分)</el-radio>
                  </el-radio-group>
                </div>
              </div>
            </div>
          </div>

          <!-- 二、记忆力 (3分) -->
          <div class="section">
            <div class="section-title">二、记忆力（3分）</div>
            <div class="form-item">
              <span class="item-number">3.</span>
              <span class="item-label">告诉你三种东西，我说完后，请你重复一遍并记住，待会还会问你（各1分，共3分）：</span>
              <el-radio-group :disabled="isDetail" v-model="form.memory.score" size="small">
                <el-radio :value="3">3分</el-radio>
                <el-radio :value="2">2分</el-radio>
                <el-radio :value="1">1分</el-radio>
                <el-radio :value="0">0分</el-radio>
              </el-radio-group>
            </div>
          </div>

          <!-- 三、注意力和计算力 (5分) -->
          <div class="section">
            <div class="section-title">三、注意力和计算力（5分）</div>
            <div class="form-item">
              <span class="item-number">4.</span>
              <span class="item-label">100-7=？连续减5次（93、86、79、72、65。各1分，共5分。若错了，但下一个答案正确，只记一次错误）：</span>
              <el-radio-group :disabled="isDetail" v-model="form.attention.score" size="small">
                <el-radio :value="5">5分</el-radio>
                <el-radio :value="4">4分</el-radio>
                <el-radio :value="3">3分</el-radio>
                <el-radio :value="2">2分</el-radio>
                <el-radio :value="1">1分</el-radio>
                <el-radio :value="0">0分</el-radio>
              </el-radio-group>
            </div>
          </div>

          <!-- 四、回忆能力 (3分) -->
          <div class="section">
            <div class="section-title">四、回忆能力（3分）</div>
            <div class="form-item">
              <span class="item-number">5.</span>
              <span class="item-label">现在请你说出我刚才告诉你让你记住的那些东西？</span>
              <el-radio-group :disabled="isDetail" v-model="form.recall.score" size="small">
                <el-radio :value="3">3分</el-radio>
                <el-radio :value="2">2分</el-radio>
                <el-radio :value="1">1分</el-radio>
                <el-radio :value="0">0分</el-radio>
              </el-radio-group>
            </div>
          </div>

          <!-- 五、命名能力 (2分) -->
          <div class="section">
            <div class="section-title">五、命名能力（2分）</div>
            <div class="form-item">
              <span class="item-number">6.</span>
              <span class="item-label">命名能力：</span>
              <div class="score-group">
                <div class="score-row">
                  <span>出示手表，问这个是什么东西？</span>
                  <el-radio-group :disabled="isDetail" v-model="form.naming.watch" size="small">
                    <el-radio :value="1">正确(1分)</el-radio>
                    <el-radio :value="0">错误(0分)</el-radio>
                  </el-radio-group>
                </div>
                <div class="score-row">
                  <span>出示钢笔，问这个是什么东西？</span>
                  <el-radio-group :disabled="isDetail" v-model="form.naming.pen" size="small">
                    <el-radio :value="1">正确(1分)</el-radio>
                    <el-radio :value="0">错误(0分)</el-radio>
                  </el-radio-group>
                </div>
              </div>
            </div>
          </div>

          <!-- 六、复述能力 (1分) -->
          <div class="section">
            <div class="section-title">六、复述能力（1分）</div>
            <div class="form-item">
              <span class="item-number">7.</span>
              <span class="item-label">我现在说一句话，请跟我清楚的重复一遍（四十四只石狮子）！</span>
              <el-radio-group :disabled="isDetail" v-model="form.repetition.score" size="small">
                <el-radio :value="1">正确(1分)</el-radio>
                <el-radio :value="0">错误(0分)</el-radio>
              </el-radio-group>
            </div>
          </div>

          <!-- 七、阅读能力 (1分) -->
          <div class="section">
            <div class="section-title">七、阅读能力（1分）</div>
            <div class="form-item">
              <span class="item-number">8.</span>
              <span class="item-label">（闭上你的眼睛）请你念念这句话，并按上面意思去做！</span>
              <el-radio-group :disabled="isDetail" v-model="form.reading.score" size="small">
                <el-radio :value="1">正确(1分)</el-radio>
                <el-radio :value="0">错误(0分)</el-radio>
              </el-radio-group>
            </div>
          </div>

          <!-- 八、三步命令 (3分) -->
          <div class="section">
            <div class="section-title">八、三步命令（3分）</div>
            <div class="form-item">
              <span class="item-number">9.</span>
              <span class="item-label">我给您一张纸请您按我说的去做，现在开始："用右手拿着这张纸，用两只手将它对折起来，放在您的左腿上。"（每个动作1分，共3分）：</span>
              <el-radio-group :disabled="isDetail" v-model="form.threeStepCommand.score" size="small">
                <el-radio :value="3">3分</el-radio>
                <el-radio :value="2">2分</el-radio>
                <el-radio :value="1">1分</el-radio>
                <el-radio :value="0">0分</el-radio>
              </el-radio-group>
            </div>
          </div>

          <!-- 九、书写能力 (1分) -->
          <div class="section">
            <div class="section-title">九、书写能力（1分）</div>
            <div class="form-item">
              <span class="item-number">10.</span>
              <span class="item-label">书写能力要求受试者自己写一句完整的句子：</span>
              <el-radio-group :disabled="isDetail" v-model="form.writing.score" size="small">
                <el-radio :value="1">正确(1分)</el-radio>
                <el-radio :value="0">错误(0分)</el-radio>
              </el-radio-group>
            </div>
          </div>

          <!-- 十、结构能力 (1分) -->
          <div class="section">
            <div class="section-title">十、结构能力（1分）</div>
            <div class="form-item">
              <span class="item-number">11.</span>
              <span class="item-label">（出示图案）请你照上面图案画下来！</span>
              <div class="structure-content">
                <div class="structure-image">
                  <!-- 两个重叠的五边形图案 -->
                  <svg viewBox="0 0 200 120" class="pentagon-svg">
                    <!-- 左侧五边形 -->
                    <polygon points="50,10 90,30 90,80 50,100 10,80 10,30" fill="none" stroke="#333" stroke-width="2"/>
                    <!-- 右侧五边形 -->
                    <polygon points="110,10 150,30 150,80 110,100 70,80 70,30" fill="none" stroke="#333" stroke-width="2"/>
                  </svg>
                </div>
                <el-radio-group :disabled="isDetail" v-model="form.structure.score" size="small">
                  <el-radio :value="1">正确(1分)</el-radio>
                  <el-radio :value="0">错误(0分)</el-radio>
                </el-radio-group>
              </div>
            </div>
          </div>

          <!-- 风险程度判断 -->
          <div class="section risk-section">
            <div class="section-title">风险程度判断</div>
            <div class="risk-judgment">
              <el-radio-group :disabled="isDetail" v-model="form.riskLevel" >
                <el-radio value="none" style="margin-right: 10px">无风险：MMSE ≥27分</el-radio>
                <el-radio value="low" style="margin-right: 10px">低风险：MMSE 26-21分</el-radio>
                <el-radio value="medium" style="margin-right: 10px">中风险：MMSE 10-20分</el-radio>
                <el-radio value="high" style="margin-right: 10px">高风险：MMSE ≤9分</el-radio>
              </el-radio-group>
            </div>
          </div>

          <!-- 预防措施 -->
          <div class="section">
            <div class="section-title">预防措施</div>
            <div class="form-item">
              <el-checkbox-group :disabled="isDetail" v-model="form.preventiveMeasures" class="preventive-measures">
                <el-checkbox value="diet">饮食与生活习惯管理</el-checkbox>
                <el-checkbox value="environment">环境优化与安全保障</el-checkbox>
                <el-checkbox value="emotion">情绪与行为干预</el-checkbox>
                <el-checkbox value="monitoring">健康监测</el-checkbox>
                <el-checkbox value="personalized">个性化活动（计算能力训练、方向感知觉训练、记忆力训练等）</el-checkbox>
                <el-checkbox value="other">其他</el-checkbox>
              </el-checkbox-group>
              <template v-if="form.preventiveMeasures.includes('other')">
                <el-input v-model="form.preventiveMeasuresOther" class="other-input" placeholder="请输入其他预防措施" />
              </template>
            </div>
          </div>
        </div>
    </div>


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

  </el-drawer>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'

import dayjs from 'dayjs'

import {mmseCreate, mmseGetById, mmseUpdate} from "@/api/social-work";
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const title = ref('')
const dialogVisible = ref(false) // 弹窗
const formRef = ref() // 表单 Ref
const selectElderRef = ref() // 表单 Ref
const isDetail = ref(false) // 是否详情打开
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
let dataForm = ref({
  // 表单字段
  id: undefined,
  idCard: '',
  contractNumber: '', //档案号
  elderName: '',//长者姓名
  bedName: '', //床位号
  elderAge: '', //年龄
  elderSex: '', //性别
  checkInTime: '', //入院日期
  elderId: '',
  tenantId: undefined
})




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

// ========== MMSE 表单序列化方法 ==========

/** 计算总分 */
const totalScore = computed(() => {
  const orientationScore = 
    (form.orientation.year || 0) +
    (form.orientation.season || 0) +
    (form.orientation.month || 0) +
    (form.orientation.day || 0) +
    (form.orientation.weekDay || 0) +
    (form.orientation.province || 0) +
    (form.orientation.county || 0) +
    (form.orientation.town || 0) +
    (form.orientation.nursingHome || 0) +
    (form.orientation.floor || 0)
  
  const namingScore = (form.naming.watch || 0) + (form.naming.pen || 0)
  
  return orientationScore +
    (form.memory.score || 0) +
    (form.attention.score || 0) +
    (form.recall.score || 0) +
    namingScore +
    (form.repetition.score || 0) +
    (form.reading.score || 0) +
    (form.threeStepCommand.score || 0) +
    (form.writing.score || 0) +
    (form.structure.score || 0)
})

/** 风险程度文本 */
const riskLevelText = computed(() => {
  const score = totalScore.value
  if (score >= 27) return '无风险'
  if (score >= 21) return '低风险'
  if (score >= 10) return '中风险'
  return '高风险'
})

/** 风险程度样式类 */
const riskLevelClass = computed(() => {
  const score = totalScore.value
  if (score >= 27) return 'risk-none'
  if (score >= 21) return 'risk-low'
  if (score >= 10) return 'risk-medium'
  return 'risk-high'
})

/** 将表单数据序列化为 JSON 对象 */
const serializeFormData = () => {
  return {
    // 基本信息
    assessor: form.assessor || '',
    assessDate: form.assessDate ? dayjs(form.assessDate).format('YYYY-MM-DD') : '',
    
    // 各项评分
    orientation: { ...form.orientation },
    memory: { ...form.memory },
    attention: { ...form.attention },
    recall: { ...form.recall },
    naming: { ...form.naming },
    repetition: { ...form.repetition },
    reading: { ...form.reading },
    threeStepCommand: { ...form.threeStepCommand },
    writing: { ...form.writing },
    structure: { ...form.structure },
    
    // 总分
    totalScore: totalScore.value,
    
    // 风险程度
    riskLevel: form.riskLevel || '',
    
    // 预防措施
    preventiveMeasures: form.preventiveMeasures || [],
    preventiveMeasuresOther: form.preventiveMeasuresOther || ''
  }
}

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

  // 基本信息
  form.assessor = formData.assessor || ''
  form.assessDate = formData.assessDate ? dayjs(formData.assessDate).toDate() : ''

  // 各项评分
  form.orientation = {
    year: formData.orientation?.year ?? 0,
    season: formData.orientation?.season ?? 0,
    month: formData.orientation?.month ?? 0,
    day: formData.orientation?.day ?? 0,
    weekDay: formData.orientation?.weekDay ?? 0,
    province: formData.orientation?.province ?? 0,
    county: formData.orientation?.county ?? 0,
    town: formData.orientation?.town ?? 0,
    nursingHome: formData.orientation?.nursingHome ?? 0,
    floor: formData.orientation?.floor ?? 0
  }
  form.memory = { score: formData.memory?.score ?? 0 }
  form.attention = { score: formData.attention?.score ?? 0 }
  form.recall = { score: formData.recall?.score ?? 0 }
  form.naming = {
    watch: formData.naming?.watch ?? 0,
    pen: formData.naming?.pen ?? 0
  }
  form.repetition = { score: formData.repetition?.score ?? 0 }
  form.reading = { score: formData.reading?.score ?? 0 }
  form.threeStepCommand = { score: formData.threeStepCommand?.score ?? 0 }
  form.writing = { score: formData.writing?.score ?? 0 }
  form.structure = { score: formData.structure?.score ?? 0 }

  // 风险程度
  form.riskLevel = formData.riskLevel || ''

  // 预防措施
  form.preventiveMeasures = formData.preventiveMeasures || []
  form.preventiveMeasuresOther = formData.preventiveMeasuresOther || ''
}

/** 重置 MMSE 表单数据 */
const resetMMSEForm = () => {
  form.assessor = ''
  form.assessDate = ''

  // 定向力
  form.orientation = {
    year: 0,
    season: 0,
    month: 0,
    day: 0,
    weekDay: 0,
    province: 0,
    county: 0,
    town: 0,
    nursingHome: 0,
    floor: 0
  }

  // 其他评分
  form.memory = { score: 0 }
  form.attention = { score: 0 }
  form.recall = { score: 0 }
  form.naming = { watch: 0, pen: 0 }
  form.repetition = { score: 0 }
  form.reading = { score: 0 }
  form.threeStepCommand = { score: 0 }
  form.writing = { score: 0 }
  form.structure = { score: 0 }

  // 风险程度
  form.riskLevel = ''

  // 预防措施
  form.preventiveMeasures = []
  form.preventiveMeasuresOther = ''
}

/** 加载评估数据 */
const loadAttackRiskData = async (id: number) => {
  try {
    const res = await mmseGetById(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.checkInTime = res.checkInTime || ''
      dataForm.value.contractNumber = res.fileNumber || ''
      dataForm.value.elderAge = res.elderAge || ''

      await selectElderRef.value.upData(res.elderName, res.elderId)
      // 解析 assessmentData
      if (res.assessData) {
        const formData = JSON.parse(res.assessData)
        deserializeFormData(formData)
      }
    }
  } catch (error) {
    message.error('加载评估数据失败')
  }
}

/** 打开弹窗 */
const open = async (tenantId, 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 = "编辑-MMSE评估"
    // 加载 MMSE 数据
    await loadAttackRiskData(id)
  } else {
    title.value = "新增-MMSE评估"

  }
}


const form = reactive({
  // 基本信息
  assessor: '',
  assessDate: '',

  // 定向力 (10分)
  orientation: {
    year: 0,
    season: 0,
    month: 0,
    day: 0,
    weekDay: 0,
    province: 0,
    county: 0,
    town: 0,
    nursingHome: 0,
    floor: 0
  },

  // 记忆力 (3分)
  memory: { score: 0 },

  // 注意力和计算力 (5分)
  attention: { score: 0 },

  // 回忆能力 (3分)
  recall: { score: 0 },

  // 命名能力 (2分)
  naming: { watch: 0, pen: 0 },

  // 复述能力 (1分)
  repetition: { score: 0 },

  // 阅读能力 (1分)
  reading: { score: 0 },

  // 三步命令 (3分)
  threeStepCommand: { score: 0 },

  // 书写能力 (1分)
  writing: { score: 0 },

  // 结构能力 (1分)
  structure: { score: 0 },

  // 风险程度
  riskLevel: '',

  // 预防措施
  preventiveMeasures: [],
  preventiveMeasuresOther: ''
})

// MMSE 不需要下拉选项，使用 radio 和 checkbox 直接评分


defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  if (formLoading.value) {
    return
  }
  formLoading.value = true
  // 提交请求
  try {
    const assessData = serializeFormData()
    const tempParams = {
      ...dataForm.value,
      assessData: JSON.stringify(assessData),
      totalScore: totalScore.value,
      assessor: form.assessor,
      assessDate: form.assessDate ? dayjs(form.assessDate).format('YYYY-MM-DD') : ''
    }

    if (dataForm.value.id) {
      const res = await mmseUpdate(tempParams)
      if (res) {
        message.success(t('common.updateSuccess'))
        dialogVisible.value = false
        // 发送操作成功的事件
        emit('success')
      }
    } else {
      const res = await mmseCreate(tempParams)
      if (res) {
        message.success(t('common.createSuccess'))
        dialogVisible.value = false
        // 发送操作成功的事件
        emit('success')
      }
    }
  } finally {
    setTimeout(() => {
      formLoading.value = false
    }, 500)
  }
}



/** 重置表单 */
const resetForm = () => {
  dataForm.value = {
    id: undefined,
    idCard: '',
    contractNumber: '', //档案号
    elderName: '',//长者姓名
    bedName: '', //床位号
    elderAge: '', //年龄
    elderSex: '', //性别
    checkInTime: '', //入院日期
    elderId: '',
    tenantId: undefined
  }
  formRef.value?.resetFields()

  // 重置 MMSE 表单
  resetMMSEForm()
}

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

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

  // 辅助函数：获取评分状态
  const getScoreMark = (score) => score === 1 ? '☑ 正确 (1分)' : '☐ 错误 (0分)'
  const getMemoryMark = (score) => {
    const marks = ['☐ 0分', '☐ 1分', '☐ 2分', '☐ 3分']
    if (score >= 0 && score <= 3) marks[score] = marks[score].replace('☐', '☑')
    return marks.join('  ')
  }
  const getAttentionMark = (score) => {
    const marks = ['☐ 0分', '☐ 1分', '☐ 2分', '☐ 3分', '☐ 4分', '☐ 5分']
    if (score >= 0 && score <= 5) marks[score] = marks[score].replace('☐', '☑')
    return marks.join('  ')
  }
  const getRecallMark = (score) => {
    const marks = ['☐ 0分', '☐ 1分', '☐ 2分', '☐ 3分']
    if (score >= 0 && score <= 3) marks[score] = marks[score].replace('☐', '☑')
    return marks.join('  ')
  }
  const getThreeStepMark = (score) => {
    const marks = ['☐ 0分', '☐ 1分', '☐ 2分', '☐ 3分']
    if (score >= 0 && score <= 3) marks[score] = marks[score].replace('☐', '☑')
    return marks.join('  ')
  }
  const getNamingMark = (score) => score === 1 ? '☑ 正确 (1分)' : '☐ 错误 (0分)'

  // 构建打印内容
  const printContent = `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>MMSE评估表 - ${dataForm.value.elderName || ''}</title>
      <style>
        @media print {
          @page { size: A4 portrait; margin: 15mm; }
        }
        body { 
          font-family: 'SimSun', 'Microsoft YaHei', serif; 
          font-size: 11pt; 
          line-height: 1.5; 
          color: #333;
        }
        .header { 
          text-align: center; 
          margin-bottom: 20px; 
          border-bottom: 2px solid #333;
          padding-bottom: 10px;
        }
        .header h1 { 
          font-size: 18pt; 
          margin: 0; 
          letter-spacing: 2px;
        }
        .header .sub-title {
          font-size: 12pt;
          color: #666;
          margin-top: 5px;
        }
        .info-section {
          margin-bottom: 15px;
          padding: 10px;
          border: 1px solid #999;
          background: #fafafa;
        }
        .info-row {
          display: flex;
          flex-wrap: wrap;
          gap: 20px;
        }
        .info-item {
          display: flex;
          align-items: center;
        }
        .info-item .label {
          font-weight: bold;
          margin-right: 8px;
          color: #555;
        }
        .info-item .value {
          border-bottom: 1px solid #333;
          min-width: 80px;
          padding: 0 5px;
          text-align: center;
        }
        .score-summary {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 10px 15px;
          background: #f0f0f0;
          border: 2px solid #333;
          margin-bottom: 15px;
        }
        .total-score { 
          font-size: 14pt; 
          font-weight: bold;
        }
        .total-score .score-value {
          color: #d9534f;
          font-size: 18pt;
        }
        .risk-level { 
          font-size: 12pt; 
          font-weight: bold; 
          padding: 5px 15px;
        }
        .risk-none { color: #5cb85c; }
        .risk-low { color: #f0ad4e; }
        .risk-medium { color: #d9534f; }
        .risk-high { color: #d9534f; background: #ffe6e6; padding: 5px 10px; border-radius: 3px; }
        
        .section { 
          margin-bottom: 12px; 
          border: 1px solid #999;
        }
        .section-header { 
          font-weight: bold; 
          background: #e8e8e8; 
          padding: 8px 12px;
          border-bottom: 1px solid #999;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
        .section-title {
          font-size: 12pt;
        }
        .section-score {
          font-size: 11pt;
          color: #666;
        }
        .question {
          padding: 8px 12px;
          border-bottom: 1px dashed #ccc;
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
        }
        .question:last-child {
          border-bottom: none;
        }
        .question-text {
          flex: 1;
          padding-right: 15px;
        }
        .question-number {
          font-weight: bold;
          margin-right: 8px;
          color: #555;
        }
        .question-desc {
          font-size: 10pt;
          color: #666;
          margin-top: 3px;
        }
        .answer-options {
          white-space: nowrap;
          font-size: 10pt;
          color: #555;
        }
        .structure-image {
          text-align: center;
          padding: 10px;
          background: #fafafa;
          margin: 10px 0;
        }
        .structure-image svg {
          width: 200px;
          height: 120px;
        }
        
        .measures-section {
          margin-top: 15px;
          border: 1px solid #999;
        }
        .measures-title {
          font-weight: bold;
          background: #e8e8e8;
          padding: 8px 12px;
          border-bottom: 1px solid #999;
        }
        .measures-content {
          padding: 10px 12px;
        }
        .measure-item {
          margin-bottom: 5px;
          font-size: 10pt;
        }
        .measure-other {
          margin-left: 20px;
          margin-top: 5px;
          border-bottom: 1px solid #333;
          min-width: 200px;
          display: inline-block;
        }
        
        .signature-section {
          margin-top: 30px;
          display: flex;
          justify-content: space-between;
        }
        .signature-item {
          width: 45%;
        }
        .signature-label {
          margin-bottom: 5px;
        }
        .signature-line {
          border-bottom: 1px solid #333;
          height: 30px;
        }
        .date-line {
          border-bottom: 1px solid #333;
          height: 30px;
          width: 150px;
        }
        
        .footer-note {
          margin-top: 20px;
          font-size: 9pt;
          color: #666;
          text-align: center;
          border-top: 1px solid #ccc;
          padding-top: 10px;
        }
      </style>
    </head>
    <body>
      <div class="header">
        <h1>简易精神状态评价量表（MMSE）</h1>
        <div class="sub-title">Mini-Mental State Examination</div>
      </div>
      
      <div class="info-section">
        <div class="info-row">
          <div class="info-item">
            <span class="label">长者姓名：</span>
            <span class="value">${dataForm.value.elderName || ''}</span>
          </div>
          <div class="info-item">
            <span class="label">档案号：</span>
            <span class="value">${dataForm.value.contractNumber || ''}</span>
          </div>
          <div class="info-item">
            <span class="label">床位号：</span>
            <span class="value">${dataForm.value.bedName || ''}</span>
          </div>
        </div>
        <div class="info-row" style="margin-top: 10px;">
          <div class="info-item">
            <span class="label">评估日期：</span>
            <span class="value">${form.assessDate ? dayjs(form.assessDate).format('YYYY-MM-DD') : ''}</span>
          </div>
          <div class="info-item">
            <span class="label">评估人：</span>
            <span class="value">${form.assessor || ''}</span>
          </div>
        </div>
      </div>

      <div class="score-summary">
        <div class="total-score">
          总分：<span class="score-value">${totalScore.value}</span> / 30分
        </div>
      </div>

      <!-- 一、定向力 -->
      <div class="section">
        <div class="section-header">
          <span class="section-title">一、定向力（10分）</span>
          <span class="section-score">得分：${(form.orientation.year || 0) + (form.orientation.season || 0) + (form.orientation.month || 0) + (form.orientation.day || 0) + (form.orientation.weekDay || 0) + (form.orientation.province || 0) + (form.orientation.county || 0) + (form.orientation.town || 0) + (form.orientation.nursingHome || 0) + (form.orientation.floor || 0)} / 10分</span>
        </div>
        <div class="question">
          <div class="question-text">
            <span class="question-number">1.</span>
            <div>
              <div>时间定向（5分）</div>
              <div class="question-desc">今年是哪一年？现在是什么季节？现在是几月份？今天是几号？今天是星期几？</div>
            </div>
          </div>
          <div class="answer-options">
            ${getScoreMark(form.orientation.year)}<br>
            ${getScoreMark(form.orientation.season)}<br>
            ${getScoreMark(form.orientation.month)}<br>
            ${getScoreMark(form.orientation.day)}<br>
            ${getScoreMark(form.orientation.weekDay)}
          </div>
        </div>
        <div class="question">
          <div class="question-text">
            <span class="question-number">2.</span>
            <div>
              <div>地点定向（5分）</div>
              <div class="question-desc">你住在那个省？你住在那个县（区）？你住在那个乡（街道）？咱们现在在哪个养老院？咱们现在在第几层楼？</div>
            </div>
          </div>
          <div class="answer-options">
            ${getScoreMark(form.orientation.province)}<br>
            ${getScoreMark(form.orientation.county)}<br>
            ${getScoreMark(form.orientation.town)}<br>
            ${getScoreMark(form.orientation.nursingHome)}<br>
            ${getScoreMark(form.orientation.floor)}
          </div>
        </div>
      </div>

      <!-- 二、记忆力 -->
      <div class="section">
        <div class="section-header">
          <span class="section-title">二、记忆力（3分）</span>
          <span class="section-score">得分：${form.memory.score || 0} / 3分</span>
        </div>
        <div class="question">
          <div class="question-text">
            <span class="question-number">3.</span>
            <div>
              <div>告诉你三种东西，我说完后，请你重复一遍并记住，待会还会问你（各1分，共3分）</div>
              <div class="question-desc">例如：皮球、国旗、树木</div>
            </div>
          </div>
          <div class="answer-options">
            ${getMemoryMark(form.memory.score || 0)}
          </div>
        </div>
      </div>

      <!-- 三、注意力和计算力 -->
      <div class="section">
        <div class="section-header">
          <span class="section-title">三、注意力和计算力（5分）</span>
          <span class="section-score">得分：${form.attention.score || 0} / 5分</span>
        </div>
        <div class="question">
          <div class="question-text">
            <span class="question-number">4.</span>
            <div>
              <div>100-7=？连续减5次（93、86、79、72、65。各1分，共5分）</div>
              <div class="question-desc">若错了，但下一个答案正确，只记一次错误</div>
            </div>
          </div>
          <div class="answer-options">
            ${getAttentionMark(form.attention.score || 0)}
          </div>
        </div>
      </div>

      <!-- 四、回忆能力 -->
      <div class="section">
        <div class="section-header">
          <span class="section-title">四、回忆能力（3分）</span>
          <span class="section-score">得分：${form.recall.score || 0} / 3分</span>
        </div>
        <div class="question">
          <div class="question-text">
            <span class="question-number">5.</span>
            <div>现在请你说出我刚才告诉你让你记住的那些东西？</div>
          </div>
          <div class="answer-options">
            ${getRecallMark(form.recall.score || 0)}
          </div>
        </div>
      </div>

      <!-- 五、命名能力 -->
      <div class="section">
        <div class="section-header">
          <span class="section-title">五、命名能力（2分）</span>
          <span class="section-score">得分：${(form.naming.watch || 0) + (form.naming.pen || 0)} / 2分</span>
        </div>
        <div class="question">
          <div class="question-text">
            <span class="question-number">6.</span>
            <div>出示手表，问这个是什么东西？</div>
          </div>
          <div class="answer-options">
            ${getNamingMark(form.naming.watch || 0)}
          </div>
        </div>
        <div class="question">
          <div class="question-text">
            <span class="question-number"></span>
            <div>出示钢笔，问这个是什么东西？</div>
          </div>
          <div class="answer-options">
            ${getNamingMark(form.naming.pen || 0)}
          </div>
        </div>
      </div>

      <!-- 六、复述能力 -->
      <div class="section">
        <div class="section-header">
          <span class="section-title">六、复述能力（1分）</span>
          <span class="section-score">得分：${form.repetition.score || 0} / 1分</span>
        </div>
        <div class="question">
          <div class="question-text">
            <span class="question-number">7.</span>
            <div>我现在说一句话，请跟我清楚的重复一遍（四十四只石狮子）！</div>
          </div>
          <div class="answer-options">
            ${getScoreMark(form.repetition.score || 0)}
          </div>
        </div>
      </div>

      <!-- 七、阅读能力 -->
      <div class="section">
        <div class="section-header">
          <span class="section-title">七、阅读能力（1分）</span>
          <span class="section-score">得分：${form.reading.score || 0} / 1分</span>
        </div>
        <div class="question">
          <div class="question-text">
            <span class="question-number">8.</span>
            <div>（闭上你的眼睛）请你念念这句话，并按上面意思去做！</div>
          </div>
          <div class="answer-options">
            ${getScoreMark(form.reading.score || 0)}
          </div>
        </div>
      </div>

      <!-- 八、三步命令 -->
      <div class="section">
        <div class="section-header">
          <span class="section-title">八、三步命令（3分）</span>
          <span class="section-score">得分：${form.threeStepCommand.score || 0} / 3分</span>
        </div>
        <div class="question">
          <div class="question-text">
            <span class="question-number">9.</span>
            <div>
              <div>我给您一张纸请您按我说的去做，现在开始：</div>
              <div class="question-desc">"用右手拿着这张纸，用两只手将它对折起来，放在您的左腿上。"（每个动作1分，共3分）</div>
            </div>
          </div>
          <div class="answer-options">
            ${getThreeStepMark(form.threeStepCommand.score || 0)}
          </div>
        </div>
      </div>

      <!-- 九、书写能力 -->
      <div class="section">
        <div class="section-header">
          <span class="section-title">九、书写能力（1分）</span>
          <span class="section-score">得分：${form.writing.score || 0} / 1分</span>
        </div>
        <div class="question">
          <div class="question-text">
            <span class="question-number">10.</span>
            <div>书写能力要求受试者自己写一句完整的句子</div>
          </div>
          <div class="answer-options">
            ${getScoreMark(form.writing.score || 0)}
          </div>
        </div>
      </div>

      <!-- 十、结构能力 -->
      <div class="section">
        <div class="section-header">
          <span class="section-title">十、结构能力（1分）</span>
          <span class="section-score">得分：${form.structure.score || 0} / 1分</span>
        </div>
        <div class="question">
          <div class="question-text">
            <span class="question-number">11.</span>
            <div>（出示图案）请你照上面图案画下来！</div>
          </div>
          <div class="answer-options">
            ${getScoreMark(form.structure.score || 0)}
          </div>
        </div>
        <div class="structure-image">
          <svg viewBox="0 0 200 120">
            <polygon points="50,10 90,30 90,80 50,100 10,80 10,30" fill="none" stroke="#333" stroke-width="2"/>
            <polygon points="110,10 150,30 150,80 110,100 70,80 70,30" fill="none" stroke="#333" stroke-width="2"/>
          </svg>
        </div>
      </div>

      <!-- 风险程度判断 -->
      <div class="section">
        <div class="section-header">
          <span class="section-title">风险程度判断</span>
        </div>
        <div class="question">
          <div class="question-text">
            <div style="display: flex; gap: 30px; flex-wrap: wrap;">
              <span>${form.riskLevel === 'none' ? '☑' : '☐'} 无风险：MMSE ≥27分</span>
              <span>${form.riskLevel === 'low' ? '☑' : '☐'} 低风险：MMSE 26-21分</span>
              <span>${form.riskLevel === 'medium' ? '☑' : '☐'} 中风险：MMSE 10-20分</span>
              <span>${form.riskLevel === 'high' ? '☑' : '☐'} 高风险：MMSE ≤9分</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 预防措施 -->
      <div class="measures-section">
        <div class="measures-title">预防措施</div>
        <div class="measures-content">
          <div class="measure-item">${form.preventiveMeasures?.includes('diet') ? '☑' : '☐'} 饮食与生活习惯管理</div>
          <div class="measure-item">${form.preventiveMeasures?.includes('environment') ? '☑' : '☐'} 环境优化与安全保障</div>
          <div class="measure-item">${form.preventiveMeasures?.includes('emotion') ? '☑' : '☐'} 情绪与行为干预</div>
          <div class="measure-item">${form.preventiveMeasures?.includes('monitoring') ? '☑' : '☐'} 健康监测</div>
          <div class="measure-item">${form.preventiveMeasures?.includes('personalized') ? '☑' : '☐'} 个性化活动（计算能力训练、方向感知觉训练、记忆力训练等）</div>
          <div class="measure-item">
            ${form.preventiveMeasures?.includes('other') ? '☑' : '☐'} 其他
            ${form.preventiveMeasures?.includes('other') ? '<span class="measure-other">' + (form.preventiveMeasuresOther || '') + '</span>' : ''}
          </div>
        </div>
      </div>



      <div class="footer-note">
        注：MMSE总分30分，≥27分为认知功能正常，26-21分为轻度认知障碍，10-20分为中度认知障碍，≤9分为重度认知障碍
      </div>
    </body>
    </html>
  `

  // 写入内容并打印
  printWindow.document.write(printContent)
  printWindow.document.close()
  
  // 延迟打印，确保样式加载完成
  setTimeout(() => {
    printWindow.print()
  }, 500)
}

</script>

<style scoped lang="scss">
.mmse-form {
  max-width: 1200px;
  margin: 0 auto;
  background: #fff;

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



    .info-row {
      display: flex;
      gap: 40px;
      width: 100%;
      flex-direction: row;
      align-items: center;
      margin-bottom: 10px;

      .info-item {
        display: flex;
        align-items: center;
        gap: 8px;

        .label {
          width: 82px;
          text-align: right;
          margin-right: 4px;
          white-space: nowrap;
        }
      }
    }


  .form-body {
    border: 1px solid #333;
    padding: 15px;
  }

  .section {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }

    .section-title {
      font-weight: bold;
      margin-bottom: 10px;
    }
  }

  .form-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    flex-wrap: wrap;
    gap: 8px;

    .item-number {
      font-weight: bold;
      min-width: 25px;
    }

    .item-label {
      white-space: nowrap;
      min-width: fit-content;
    }

  }

  .other-input {
    width: 200px;
    margin-left: 10px;
  }

  // 调整 Element Plus 组件样式
  :deep(.el-input__inner) {
    height: 28px;
    line-height: 28px;
    border-top: none;
    border-left: none;
    border-right: none;
    border-radius: 0;
    padding: 0 4px;

    &:focus {
      border-color: #409eff;
    }
  }


  :deep(.el-checkbox__label),
  :deep(.el-radio__label) {
    padding-left: 4px;
  }
}
.row{
  margin-bottom: 12px;
  display: flex;
  flex-direction: row;
  align-items: center;
  text{
    text-align: right;
    margin-right: 4px;
    width: 82px;
  }
}

// MMSE 特有样式
.total-score-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;

  .total-score {
    display: flex;
    align-items: baseline;
    gap: 4px;

    .score-label {
      font-size: 16px;
      font-weight: bold;
    }

    .score-value {
      font-size: 28px;
      font-weight: bold;
      color: #409eff;
    }

    .score-max {
      font-size: 14px;
      color: #909399;
    }
  }

  .risk-level {
    font-size: 16px;
    font-weight: bold;
    padding: 8px 16px;
    border-radius: 4px;

    &.risk-none {
      color: #67c23a;
      background: #f0f9eb;
    }

    &.risk-low {
      color: #e6a23c;
      background: #fdf6ec;
    }

    &.risk-medium {
      color: #f56c6c;
      background: #fef0f0;
    }

    &.risk-high {
      color: #f56c6c;
      background: #fef0f0;
      border: 1px solid #f56c6c;
    }
  }
}

.score-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-left: 35px;
  margin-top: 8px;
  width: 100%;

  .score-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 12px;
    background: #fafafa;
    border-radius: 4px;

    span {
      flex: 1;
    }
  }
}

.structure-content {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-left: 35px;
  margin-top: 8px;

  .structure-image {
    .pentagon-svg {
      width: 200px;
      height: 120px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 10px;
    }
  }
}

.risk-section {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;

  .risk-judgment {
    margin-left: 35px;
    margin-top: 10px;

    :deep(.el-radio) {
      display: block;
      margin-bottom: 8px;
      margin-right: 0;
    }
  }
}

.preventive-measures {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-left: 35px;
  margin-top: 8px;

  :deep(.el-checkbox) {
    margin-right: 0;
    height: auto;
    align-items: flex-start;

    .el-checkbox__label {
      white-space: normal;
      line-height: 1.5;
    }
  }
}
</style>
