<template>
  <el-drawer v-model="dialogVisible" :title="title" size="95%" :before-close="handleClosed">
    <div class="assessment-form">
      <div class="form-header">
        <el-form :model="dataForm" :rules="rules" ref="formRef" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="姓名" prop="elderName">
                <SelectElder
                  ref="selectElderRef" :tId="dataForm.tenantId" @elder="elderUp" :disabled="isDetail"
                  v-model="dataForm.elderId" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="床号">
                <el-input v-model="dataForm.bedName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="性别">
                <el-input v-model="dataForm.elderSex" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="年龄">
                <el-input v-model="dataForm.elderAge" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="评估日期">
                <el-date-picker
                  v-model="form.assessDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                  :disabled="isDetail"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- Barthel指数评分表 -->
      <div class="barthel-section">
        <div class="section-title">日常生活活动能力评估表（Barthel指数评分标准）</div>
        <table class="assessment-table">
          <thead>
            <tr>
              <th class="col-item">项目</th>
              <th class="col-score">分数</th>
              <th class="col-content">内容</th>
              <th class="col-result">得分</th>
            </tr>
          </thead>
          <tbody>
            <!-- 1. 大便控制 -->
            <tr>
              <td class="col-item" rowspan="3">1. 大便控制</td>
              <td class="col-score">10</td>
              <td class="col-content">
                <el-radio :label="10" v-model="form.scores[0]" :disabled="isDetail" @change="calculateTotal">无大便失禁，并可自行使用塞剂。</el-radio>
              </td>
              <td class="col-result" rowspan="3">
                <span class="score-display">{{ form.scores[0] }}</span>
              </td>
            </tr>
            <tr>
              <td class="col-score">5</td>
              <td class="col-content">
                <el-radio :label="5" v-model="form.scores[0]" :disabled="isDetail" @change="calculateTotal">偶有失禁（每周不超过一次）或使用塞剂时需人帮助。</el-radio>
              </td>
            </tr>
            <tr>
              <td class="col-score">0</td>
              <td class="col-content">
                <el-radio :label="0" v-model="form.scores[0]" :disabled="isDetail" @change="calculateTotal">需别人处理。</el-radio>
              </td>
            </tr>

            <!-- 2. 小便控制 -->
            <tr>
              <td class="col-item" rowspan="3">2. 小便控制</td>
              <td class="col-score">10</td>
              <td class="col-content">
                <el-radio :label="10" v-model="form.scores[1]" :disabled="isDetail" @change="calculateTotal">日夜皆不会尿失禁，或可自行使用并清理尿套。</el-radio>
              </td>
              <td class="col-result" rowspan="3">
                <span class="score-display">{{ form.scores[1] }}</span>
              </td>
            </tr>
            <tr>
              <td class="col-score">5</td>
              <td class="col-content">
                <el-radio :label="5" v-model="form.scores[1]" :disabled="isDetail" @change="calculateTotal">偶尔会尿失禁（每周不超过一次）或尿急（无法等待便盆或无法及时赶到厕所）或需别人帮助处理尿套。</el-radio>
              </td>
            </tr>
            <tr>
              <td class="col-score">0</td>
              <td class="col-content">
                <el-radio :label="0" v-model="form.scores[1]" :disabled="isDetail" @change="calculateTotal">需别人处理。</el-radio>
              </td>
            </tr>

            <!-- 3. 个人卫生 -->
            <tr>
              <td class="col-item" rowspan="2">3. 个人卫生</td>
              <td class="col-score">5</td>
              <td class="col-content">
                <el-radio :label="5" v-model="form.scores[2]" :disabled="isDetail" @change="calculateTotal">可独立完成洗脸、洗手、刷牙及梳头发。</el-radio>
              </td>
              <td class="col-result" rowspan="2">
                <span class="score-display">{{ form.scores[2] }}</span>
              </td>
            </tr>
            <tr>
              <td class="col-score">0</td>
              <td class="col-content">
                <el-radio :label="0" v-model="form.scores[2]" :disabled="isDetail" @change="calculateTotal">需别人处理。</el-radio>
              </td>
            </tr>

            <!-- 4. 入厕 -->
            <tr>
              <td class="col-item" rowspan="3">4. 入厕</td>
              <td class="col-score">10</td>
              <td class="col-content">
                <el-radio :label="10" v-model="form.scores[3]" :disabled="isDetail" @change="calculateTotal">可自行进出厕所，不会弄脏衣物，并能穿好衣服，使用便盆者，可自行清理便盆。</el-radio>
              </td>
              <td class="col-result" rowspan="3">
                <span class="score-display">{{ form.scores[3] }}</span>
              </td>
            </tr>
            <tr>
              <td class="col-score">5</td>
              <td class="col-content">
                <el-radio :label="5" v-model="form.scores[3]" :disabled="isDetail" @change="calculateTotal">需帮助保持姿势平衡、整理衣物或使用卫生纸。使用便盆者，可自行取放，但须依赖他人清理。</el-radio>
              </td>
            </tr>
            <tr>
              <td class="col-score">0</td>
              <td class="col-content">
                <el-radio :label="0" v-model="form.scores[3]" :disabled="isDetail" @change="calculateTotal">需他人帮助。</el-radio>
              </td>
            </tr>

            <!-- 5. 进食 -->
            <tr>
              <td class="col-item" rowspan="3">5. 进食</td>
              <td class="col-score">10</td>
              <td class="col-content">
                <el-radio :label="10" v-model="form.scores[4]" :disabled="isDetail" @change="calculateTotal">自己在合理的时间内（约10s 吃一口）可用筷子取眼前的食物。若需进食辅具时，应自行穿脱。</el-radio>
              </td>
              <td class="col-result" rowspan="3">
                <span class="score-display">{{ form.scores[4] }}</span>
              </td>
            </tr>
            <tr>
              <td class="col-score">5</td>
              <td class="col-content">
                <el-radio :label="5" v-model="form.scores[4]" :disabled="isDetail" @change="calculateTotal">需别人帮助穿脱进食辅具或只会用汤匙进食。</el-radio>
              </td>
            </tr>
            <tr>
              <td class="col-score">0</td>
              <td class="col-content">
                <el-radio :label="0" v-model="form.scores[4]" :disabled="isDetail" @change="calculateTotal">无法自行取食或耗费时间过长。</el-radio>
              </td>
            </tr>

            <!-- 6. 床和椅转移 -->
            <tr>
              <td class="col-item" rowspan="4">6. 床和椅转移</td>
              <td class="col-score">15</td>
              <td class="col-content">
                <el-radio :label="15" v-model="form.scores[5]" :disabled="isDetail" @change="calculateTotal">可独立完成，包括轮椅的煞车及移开脚踏板。</el-radio>
              </td>
              <td class="col-result" rowspan="4">
                <span class="score-display">{{ form.scores[5] }}</span>
              </td>
            </tr>
            <tr>
              <td class="col-score">10</td>
              <td class="col-content">
                <el-radio :label="10" v-model="form.scores[5]" :disabled="isDetail" @change="calculateTotal">需要稍微的协助（例如：予以轻扶以保持平衡）或需要口头指导。</el-radio>
              </td>
            </tr>
            <tr>
              <td class="col-score">5</td>
              <td class="col-content">
                <el-radio :label="5" v-model="form.scores[5]" :disabled="isDetail" @change="calculateTotal">可自行从床上坐起，但移位时仍需要别人帮助。</el-radio>
              </td>
            </tr>
            <tr>
              <td class="col-score">0</td>
              <td class="col-content">
                <el-radio :label="0" v-model="form.scores[5]" :disabled="isDetail" @change="calculateTotal">需别人帮助方可坐起来或需别人帮助方可移位。</el-radio>
              </td>
            </tr>

            <!-- 7. 行走于平地上 -->
            <tr>
              <td class="col-item" rowspan="4">7. 行走于平地上</td>
              <td class="col-score">15</td>
              <td class="col-content">
                <el-radio :label="15" v-model="form.scores[6]" :disabled="isDetail" @change="calculateTotal">使用或不使用辅具皆可独立行走50m 以上。</el-radio>
              </td>
              <td class="col-result" rowspan="4">
                <span class="score-display">{{ form.scores[6] }}</span>
              </td>
            </tr>
            <tr>
              <td class="col-score">10</td>
              <td class="col-content">
                <el-radio :label="10" v-model="form.scores[6]" :disabled="isDetail" @change="calculateTotal">需要稍微的扶持或口头指导方可行走50m 以上。</el-radio>
              </td>
            </tr>
            <tr>
              <td class="col-score">5</td>
              <td class="col-content">
                <el-radio :label="5" v-model="form.scores[6]" :disabled="isDetail" @change="calculateTotal">虽无法行走，但可独立操纵轮椅（包括转弯、进门、接近桌子）。</el-radio>
              </td>
            </tr>
            <tr>
              <td class="col-score">0</td>
              <td class="col-content">
                <el-radio :label="0" v-model="form.scores[6]" :disabled="isDetail" @change="calculateTotal">需别人帮助方可坐起来或需别人帮助方可移位。</el-radio>
              </td>
            </tr>

            <!-- 8. 穿脱衣服 -->
            <tr>
              <td class="col-item" rowspan="3">8. 穿脱衣服</td>
              <td class="col-score">10</td>
              <td class="col-content">
                <el-radio :label="10" v-model="form.scores[7]" :disabled="isDetail" @change="calculateTotal">可自行穿脱衣服、鞋子及辅具。</el-radio>
              </td>
              <td class="col-result" rowspan="3">
                <span class="score-display">{{ form.scores[7] }}</span>
              </td>
            </tr>
            <tr>
              <td class="col-score">5</td>
              <td class="col-content">
                <el-radio :label="5" v-model="form.scores[7]" :disabled="isDetail" @change="calculateTotal">在别人帮助下，可完成一半以上的上述动作。</el-radio>
              </td>
            </tr>
            <tr>
              <td class="col-score">0</td>
              <td class="col-content">
                <el-radio :label="0" v-model="form.scores[7]" :disabled="isDetail" @change="calculateTotal">不能自行穿脱衣服。</el-radio>
              </td>
            </tr>

            <!-- 9. 上下楼梯 -->
            <tr>
              <td class="col-item" rowspan="3">9. 上下楼梯</td>
              <td class="col-score">10</td>
              <td class="col-content">
                <el-radio :label="10" v-model="form.scores[8]" :disabled="isDetail" @change="calculateTotal">可自行上下楼梯（包括抓扶手、使用拐杖）。</el-radio>
              </td>
              <td class="col-result" rowspan="3">
                <span class="score-display">{{ form.scores[8] }}</span>
              </td>
            </tr>
            <tr>
              <td class="col-score">5</td>
              <td class="col-content">
                <el-radio :label="5" v-model="form.scores[8]" :disabled="isDetail" @change="calculateTotal">需要稍微帮助或口头指导。</el-radio>
              </td>
            </tr>
            <tr>
              <td class="col-score">0</td>
              <td class="col-content">
                <el-radio :label="0" v-model="form.scores[8]" :disabled="isDetail" @change="calculateTotal">无法上下楼梯。</el-radio>
              </td>
            </tr>

            <!-- 10. 洗澡 -->
            <tr>
              <td class="col-item" rowspan="2">10. 洗澡</td>
              <td class="col-score">5</td>
              <td class="col-content">
                <el-radio :label="5" v-model="form.scores[9]" :disabled="isDetail" @change="calculateTotal">可独立完成（不论是盆浴或沐浴）。</el-radio>
              </td>
              <td class="col-result" rowspan="2">
                <span class="score-display">{{ form.scores[9] }}</span>
              </td>
            </tr>
            <tr>
              <td class="col-score">0</td>
              <td class="col-content">
                <el-radio :label="0" v-model="form.scores[9]" :disabled="isDetail" @change="calculateTotal">需要别人帮助。</el-radio>
              </td>
            </tr>

            <!-- 总分 -->
            <tr class="total-row">
              <td class="col-item">总分：</td>
              <td class="col-score"></td>
              <td class="col-content"></td>
              <td class="col-result">
                <span class="total-score">{{ form.totalScore }} 分</span>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 评分结果 -->
        <div class="result-section">
          <div class="result-title">评分结果：</div>
          <div class="result-rules">
            <el-tag :type="form.totalScore < 20 ? 'danger' : ''" class="rule-tag">&lt;20分：生活完全依赖</el-tag>
            <el-tag :type="form.totalScore >= 20 && form.totalScore <= 40 ? 'warning' : ''" class="rule-tag">20～40分：生活需要很大帮助</el-tag>
            <el-tag :type="form.totalScore > 40 && form.totalScore <= 60 ? 'info' : ''" class="rule-tag">40～60分：生活需要帮忙</el-tag>
            <el-tag :type="form.totalScore > 60 ? 'success' : ''" class="rule-tag">&gt;60分：生活基本自理</el-tag>
          </div>
          <div class="current-result" v-if="form.resultLevel">
            <span class="result-label">当前评估结果：</span>
            <el-tag :type="getResultTagType(form.resultLevel)" size="large">
              {{ getResultText(form.resultLevel) }}
            </el-tag>
          </div>
        </div>

        <!-- 评估人签名 -->
        <div class="assessor-section">
          <el-form-item label="评估人签名：" label-width="100px">
            <el-input v-model="form.assessor" :disabled="isDetail" style="width: 300px" />
          </el-form-item>
        </div>
      </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 { computed, ref, reactive } from 'vue'
import dayjs from 'dayjs'
import {
  dailyLifeCreate,
  dailyLifeGetById,
  dailyLifeUpdate
} 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
}

// 表单数据 - 10项评估
const form = reactive({
  scores: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],  // 10项评分
  totalScore: 0,
  resultLevel: '',
  assessDate: '',
  assessor: ''
})

// 计算总得分
const calculateTotal = () => {
  const total = form.scores.reduce((sum, score) => sum + (score || 0), 0)
  form.totalScore = total

  // 自动判断结果等级
  if (total < 20) {
    form.resultLevel = 'complete_dependence'
  } else if (total >= 20 && total <= 40) {
    form.resultLevel = 'large_help'
  } else if (total > 40 && total <= 60) {
    form.resultLevel = 'need_help'
  } else if (total > 60) {
    form.resultLevel = 'basic_independent'
  }
}

// 获取结果等级文本
const getResultText = (resultLevel: string) => {
  switch (resultLevel) {
    case 'complete_dependence': return '生活完全依赖'
    case 'large_help': return '生活需要很大帮助'
    case 'need_help': return '生活需要帮忙'
    case 'basic_independent': return '生活基本自理'
    default: return '-'
  }
}

// 获取结果等级标签类型
const getResultTagType = (resultLevel: string) => {
  switch (resultLevel) {
    case 'complete_dependence': return 'danger'
    case 'large_help': return 'warning'
    case 'need_help': return 'info'
    case 'basic_independent': return 'success'
    default: return ''
  }
}

/** 将表单数据序列化为 JSON 对象 */
const serializeFormData = () => {
  return {
    scores: form.scores || [],
    totalScore: form.totalScore || 0,
    resultLevel: form.resultLevel || ''
  }
}

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

  if (formData.scores && formData.scores.length > 0) {
    form.scores = formData.scores
  } else {
    form.scores = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
  }

  form.totalScore = formData.totalScore || 0
  form.resultLevel = formData.resultLevel || ''
  // assessor 和 assessDate 从 res 直接读取，不从 assessData 中解析
}

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

  form.scores = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
  form.totalScore = 0
  form.resultLevel = ''
  form.assessDate = ''
  form.assessor = ''
}

/** 打开弹窗 */
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 dailyLifeGetById(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 || ''
      form.assessDate = res.assessDate || ''
      form.assessor = res.assessor || ''
      await selectElderRef.value.upData(res.elderName, res.elderId)
      if (res.assessData) {
        const formData = JSON.parse(res.assessData)
        deserializeFormData(formData)
        calculateTotal()
      }
    }
  } catch (error) {
    message.error('加载评估数据失败')
  }
}

defineExpose({ open })

const emit = defineEmits(['success'])

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

  formLoading.value = true
  try {
    const formData = serializeFormData()
    const payload = {
      id: dataForm.value.id,
      elderId: dataForm.value.elderId,
      tenantId: dataForm.value.tenantId,
      assessData: JSON.stringify(formData),
      riskLevel: getResultText(form.resultLevel),
      assessScore: form.totalScore || 0,
      assessor: form.assessor,
      assessDate: form.assessDate ? dayjs(form.assessDate).format('YYYY-MM-DD') : ''
    }

    if (dataForm.value.id) {
      await dailyLifeUpdate(payload)
      message.success(t('common.updateSuccess'))
    } else {
      await dailyLifeCreate(payload)
      message.success(t('common.createSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    message.error('提交失败')
  } finally {
    formLoading.value = false
  }
}

/** 关闭弹窗 */
const handleClosed = () => {
  dialogVisible.value = false
}

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

  // 评估项目数据
  const assessmentItems = [
    { name: '1. 大便控制', options: [{ score: 10, text: '无大便失禁，并可自行使用塞剂' }, { score: 5, text: '偶有失禁（每周不超过一次）或使用塞剂时需人帮助' }, { score: 0, text: '需别人处理' }] },
    { name: '2. 小便控制', options: [{ score: 10, text: '日夜皆不会尿失禁，或可自行使用并清理尿套' }, { score: 5, text: '偶尔会尿失禁（每周不超过一次）或尿急或需别人帮助处理尿套' }, { score: 0, text: '需别人处理' }] },
    { name: '3. 个人卫生', options: [{ score: 5, text: '可独立完成洗脸、洗手、刷牙及梳头发' }, { score: 0, text: '需别人处理' }] },
    { name: '4. 入厕', options: [{ score: 10, text: '可自行进出厕所，不会弄脏衣物，并能穿好衣服，使用便盆者可自行清理便盆' }, { score: 5, text: '需帮助保持姿势平衡、整理衣物或使用卫生纸，使用便盆者可自行取放，但须依赖他人清理' }, { score: 0, text: '需他人帮助' }] },
    { name: '5. 进食', options: [{ score: 10, text: '自己在合理的时间内（约10s吃一口）可用筷子取眼前的食物' }, { score: 5, text: '需别人帮助穿脱进食辅具或只会用汤匙进食' }, { score: 0, text: '无法自行取食或耗费时间过长' }] },
    { name: '6. 床和椅转移', options: [{ score: 15, text: '可独立完成，包括轮椅的煞车及移开脚踏板' }, { score: 10, text: '需要稍微的协助（例如：予以轻扶以保持平衡）或需要口头指导' }, { score: 5, text: '可自行从床上坐起，但移位时仍需要别人帮助' }, { score: 0, text: '需别人帮助方可坐起来或需别人帮助方可移位' }] },
    { name: '7. 行走于平地上', options: [{ score: 15, text: '使用或不使用辅具皆可独立行走50m以上' }, { score: 10, text: '需要稍微的扶持或口头指导方可行走50m以上' }, { score: 5, text: '虽无法行走，但可独立操纵轮椅（包括转弯、进门、接近桌子）' }, { score: 0, text: '需别人帮助方可坐起来或需别人帮助方可移位' }] },
    { name: '8. 穿脱衣服', options: [{ score: 10, text: '可自行穿脱衣服、鞋子及辅具' }, { score: 5, text: '在别人帮助下，可完成一半以上的上述动作' }, { score: 0, text: '不能自行穿脱衣服' }] },
    { name: '9. 上下楼梯', options: [{ score: 10, text: '可自行上下楼梯（包括抓扶手、使用拐杖）' }, { score: 5, text: '需要稍微帮助或口头指导' }, { score: 0, text: '无法上下楼梯' }] },
    { name: '10. 洗澡', options: [{ score: 5, text: '可独立完成（不论是盆浴或沐浴）' }, { score: 0, text: '需要别人帮助' }] }
  ]

  // 构建打印内容
  const printContent = `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>日常生活活动能力评估表 - ${dataForm.value.elderName || ''}</title>
      <style>
        @media print {
          @page { size: A4 portrait; margin: 15mm; }
        }
        body {
          font-family: 'SimSun', 'Microsoft YaHei', serif;
          font-size: 9pt;
          line-height: 1.3;
          color: #333;
        }
        .header {
          text-align: center;
          margin-bottom: 15px;
          border-bottom: 2px solid #333;
          padding-bottom: 10px;
        }
        .header h1 {
          font-size: 14pt;
          margin: 0;
          letter-spacing: 2px;
        }
        .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;
        }

        .assessment-table {
          width: 100%;
          border-collapse: collapse;
          margin-bottom: 15px;
          font-size: 8pt;
        }
        .assessment-table th, .assessment-table td {
          border: 1px solid #333;
          padding: 6px;
          text-align: center;
          vertical-align: middle;
        }
        .assessment-table th {
          background: #e8e8e8;
          font-weight: bold;
        }
        .assessment-table .col-item {
          width: 12%;
          font-weight: bold;
          background: #f5f5f5;
        }
        .assessment-table .col-score {
          width: 6%;
          font-weight: bold;
        }
        .assessment-table .col-content {
          width: 70%;
          text-align: left;
        }
        .assessment-table .col-result {
          width: 12%;
          font-weight: bold;
        }
        .total-row {
          background: #fff3cd;
          font-weight: bold;
        }

        .result-section {
          margin: 15px 0;
          padding: 10px;
          border: 1px solid #999;
          background: #fafafa;
        }
        .result-title {
          font-weight: bold;
          margin-bottom: 10px;
        }
        .result-rules {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          margin-bottom: 10px;
        }
        .result-rule {
          padding: 5px 10px;
          border-radius: 4px;
        }
        .current-result {
          display: flex;
          align-items: center;
          gap: 10px;
          padding-top: 10px;
          border-top: 1px solid #ccc;
        }
        .result-label {
          font-weight: bold;
        }
        .score-value {
          color: #d9534f;
          font-weight: bold;
          font-size: 14pt;
        }

        .assessor-section {
          margin: 15px 0;
          padding: 10px;
          border: 1px solid #999;
          background: #fafafa;
        }
        .assessor-row {
          display: flex;
          gap: 30px;
        }
        .assessor-item {
          display: flex;
          align-items: center;
        }
        .assessor-item .label {
          font-weight: bold;
          margin-right: 8px;
        }
        .assessor-item .value {
          border-bottom: 1px solid #333;
          min-width: 120px;
          padding: 0 5px;
          text-align: center;
        }
      </style>
    </head>
    <body>
      <div class="header">
        <h1>日常生活活动能力评估表（Barthel指数评分标准）</h1>
      </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.elderSex || ''}</span>
          </div>
          <div class="info-item">
            <span class="label">年龄：</span>
            <span class="value">${dataForm.value.elderAge || ''}</span>
          </div>
          <div class="info-item">
            <span class="label">床号：</span>
            <span class="value">${dataForm.value.bedName || ''}</span>
          </div>
          <div class="info-item">
            <span class="label">评估日期：</span>
            <span class="value">${form.assessDate || ''}</span>
          </div>
        </div>
      </div>

      <!-- Barthel指数评分表 -->
      <table class="assessment-table">
        <thead>
          <tr>
            <th class="col-item">项目</th>
            <th class="col-score">分数</th>
            <th class="col-content">内容</th>
            <th class="col-result">得分</th>
          </tr>
        </thead>
        <tbody>
          ${assessmentItems.map((item, index) => {
            const currentScore = form.scores[index] || 0
            return `
              ${item.options.map((opt, optIndex) => `
                <tr>
                  ${optIndex === 0 ? `<td class="col-item" rowspan="${item.options.length}">${item.name}</td>` : ''}
                  <td class="col-score">${opt.score}</td>
                  <td class="col-content">${currentScore === opt.score ? '☑' : '☐'} ${opt.text}</td>
                  ${optIndex === 0 ? `<td class="col-result" rowspan="${item.options.length}">${currentScore}</td>` : ''}
                </tr>
              `).join('')}
            `
          }).join('')}
          <tr class="total-row">
            <td class="col-item">总分：</td>
            <td class="col-score"></td>
            <td class="col-content"></td>
            <td class="col-result">${form.totalScore} 分</td>
          </tr>
        </tbody>
      </table>

      <!-- 评分结果 -->
      <div class="result-section">
        <div class="result-title">评分结果：</div>
        <div class="result-rules">
          <span class="result-rule" style="background: ${form.totalScore < 20 ? '#f8d7da' : '#e8e8e8'}">${form.totalScore < 20 ? '☑' : '☐'} &lt;20分：生活完全依赖</span>
          <span class="result-rule" style="background: ${form.totalScore >= 20 && form.totalScore <= 40 ? '#fff3cd' : '#e8e8e8'}">${form.totalScore >= 20 && form.totalScore <= 40 ? '☑' : '☐'} 20～40分：生活需要很大帮助</span>
          <span class="result-rule" style="background: ${form.totalScore > 40 && form.totalScore <= 60 ? '#d1ecf1' : '#e8e8e8'}">${form.totalScore > 40 && form.totalScore <= 60 ? '☑' : '☐'} 40～60分：生活需要帮忙</span>
          <span class="result-rule" style="background: ${form.totalScore > 60 ? '#d4edda' : '#e8e8e8'}">${form.totalScore > 60 ? '☑' : '☐'} &gt;60分：生活基本自理</span>
        </div>
        ${form.resultLevel ? `
          <div class="current-result">
            <span class="result-label">当前评估结果：</span>
            <span class="score-value">${getResultText(form.resultLevel)}</span>
          </div>
        ` : ''}
      </div>

      <!-- 评估人签名 -->
      <div class="assessor-section">
        <div class="assessor-row">
          <div class="assessor-item">
            <span class="label">评估人签名：</span>
            <span class="value">${form.assessor || ''}</span>
          </div>
        </div>
      </div>
    </body>
    </html>
  `

  // 写入内容并打印
  printWindow.document.write(printContent)
  printWindow.document.close()

  // 延迟打印，确保样式加载完成
  setTimeout(() => {
    printWindow.print()
  }, 500)
}

const rules = {
  elderName: [{ required: true, message: '请选择长者', trigger: 'change' }]
}
</script>

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

  .form-header {
    margin-bottom: 20px;
  }

  .barthel-section {
    margin-bottom: 20px;

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

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

      thead {
        background-color: #f5f7fa;
        font-weight: bold;

        th {
          padding: 12px;
          border: 1px solid #e4e7ed;
          text-align: center;
        }
      }

      tbody {
        tr {
          border-bottom: 1px solid #e4e7ed;

          &:last-child {
            border-bottom: none;
          }

          td {
            padding: 12px;
            border: 1px solid #e4e7ed;
          }

          .col-item {
            width: 15%;
            text-align: center;
            font-weight: bold;
            vertical-align: middle;
          }

          .col-score {
            width: 10%;
            text-align: center;
            vertical-align: middle;
          }

          .col-content {
            width: 65%;
            vertical-align: middle;

            .el-radio {
              white-space: normal;
              line-height: 1.5;
              height: auto;
              margin-right: 0;
            }
          }

          .col-result {
            width: 10%;
            text-align: center;
            vertical-align: middle;

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

        .total-row {
          background-color: #f5f7fa;
          font-weight: bold;

          .total-score {
            font-size: 18px;
            font-weight: bold;
            color: #f56c6c;
          }
        }
      }
    }

    .result-section {
      margin-top: 15px;
      padding: 15px;
      background-color: #f5f7fa;
      border-radius: 4px;

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

      .result-rules {
        margin-bottom: 15px;

        .rule-tag {
          margin-right: 10px;
          margin-bottom: 5px;
        }
      }

      .current-result {
        .result-label {
          font-weight: bold;
          margin-right: 10px;
        }
      }
    }

    .assessor-section {
      margin-top: 20px;
      padding: 15px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
    }
  }

  .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>
