<template>
  <el-drawer v-model="dialogVisible" :title="title" size="90%" :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
                   v-model="dataForm.elderId"
                    ref="selectElderRef" :tId="dataForm.tenantId" @elder="elderUp" :disabled="isDetail"
                   />
              </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-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.bedName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 评估表 -->
      <div class="risk-factors-section">
        <div class="section-title">文娱活动风险评估表</div>

        <div class="table-wrapper">
          <table class="assessment-table">
            <thead>
              <tr>
                <th class="col-factor">评估项目</th>
                <th class="col-standard">评估内容及评分标准</th>
                <th class="col-score">得分</th>
              </tr>
            </thead>
            <tbody>
              <!-- 身体健康状况基础疾病 -->
              <tr>
                <td class="col-factor" rowspan="4">身体健康状况基础疾病</td>
                <td class="col-standard">
                  <el-radio-group v-model="form.assessment.scores[0]" :disabled="isDetail" @change="calculateTotal">
                    <el-radio :label="7">两项疾病以上(>2项)=2分+不适合=5分</el-radio>
                    <el-radio :label="1">两项疾病以下(≤2项)=1分+适合=0分</el-radio>
                    <el-radio :label="4">两项疾病以上(>2项)2分+身体适合0分=2分</el-radio>
                    <el-radio :label="6">两项疾病以下(≤2项)1分+身体不适合5分=6分</el-radio>
                  </el-radio-group>
                </td>
                <td class="col-score" rowspan="4">{{ form.assessment.scores[0] ?? '-' }}</td>
              </tr>
              <tr></tr>
              <tr></tr>
              <tr></tr>

              <!-- 跌倒风险与行动能力 -->
              <tr>
                <td class="col-factor" rowspan="3">跌倒风险与行动能力</td>
                <td class="col-standard">
                  <el-radio-group v-model="form.assessment.scores[1]" :disabled="isDetail" @change="calculateTotal">
                    <el-radio :label="8">高风险=5分+完全依赖=3分</el-radio>
                    <el-radio :label="3">中风险=1分+需要协助=2分</el-radio>
                    <el-radio :label="0">低风险=0分+正常=0分</el-radio>
                  </el-radio-group>
                </td>
                <td class="col-score" rowspan="3">{{ form.assessment.scores[1] ?? '-' }}</td>
              </tr>
              <tr></tr>
              <tr></tr>

              <!-- 走失风险与认知能力 -->
              <tr>
                <td class="col-factor" rowspan="3">走失风险与认知能力</td>
                <td class="col-standard">
                  <el-radio-group v-model="form.assessment.scores[2]" :disabled="isDetail" @change="calculateTotal">
                    <el-radio :label="8">高风险=5分+确诊认知功能障碍=3分</el-radio>
                    <el-radio :label="3">中风险=1分+疑似认知功能障碍=2分</el-radio>
                    <el-radio :label="0">低风险=0分+无认知功能障碍=0分</el-radio>
                  </el-radio-group>
                </td>
                <td class="col-score" rowspan="3">{{ form.assessment.scores[2] ?? '-' }}</td>
              </tr>
              <tr></tr>
              <tr></tr>

              <!-- 心理健康状况 -->
              <tr>
                <td class="col-factor" rowspan="3">心理健康状况</td>
                <td class="col-standard">
                  <el-radio-group v-model="form.assessment.scores[3]" :disabled="isDetail" @change="calculateTotal">
                    <el-radio :label="6">状况很差=3分+抑郁=3分</el-radio>
                    <el-radio :label="3">状况较差=1分+冷漠=2分</el-radio>
                    <el-radio :label="0">状况良好(正常)=0</el-radio>
                  </el-radio-group>
                </td>
                <td class="col-score" rowspan="3">{{ form.assessment.scores[3] ?? '-' }}</td>
              </tr>
              <tr></tr>
              <tr></tr>

              <!-- 他伤及自伤风险 -->
              <tr>
                <td class="col-factor">他伤及自伤风险</td>
                <td class="col-standard">
                  <el-radio-group v-model="form.assessment.scores[4]" :disabled="isDetail" @change="calculateTotal">
                    <el-radio :label="0">轻度风险=0</el-radio>
                    <el-radio :label="1">中度风险=1</el-radio>
                    <el-radio :label="5">重度风险=5</el-radio>
                  </el-radio-group>
                </td>
                <td class="col-score">{{ form.assessment.scores[4] ?? '-' }}</td>
              </tr>

              <!-- 参加活动老年人之间是否发生过矛盾冲突 -->
              <tr>
                <td class="col-factor">参加活动老年人之间是否发生过矛盾冲突</td>
                <td class="col-standard">
                  <el-radio-group v-model="form.assessment.scores[5]" :disabled="isDetail" @change="calculateTotal">
                    <el-radio :label="3">是=3</el-radio>
                    <el-radio :label="0">否=0</el-radio>
                  </el-radio-group>
                </td>
                <td class="col-score">{{ form.assessment.scores[5] ?? '-' }}</td>
              </tr>

              <!-- 评估总分 -->
              <tr>
                <td class="col-factor" colspan="2" style="text-align: center; font-weight: bold;">评估总分</td>
                <td class="col-score">{{ form.assessment.totalScore }}</td>
              </tr>

              <!-- 综合风险评级 -->
              <tr>
                <td class="col-factor" colspan="2" style="text-align: center; font-weight: bold;">综合风险评级</td>
                <td class="col-score">{{ getRiskText(form.riskLevel) }}</td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 评价标准 -->
        <div class="evaluation-standard">
          <div class="standard-title">评价标准：</div>
          <div class="standard-content">
            0分为无风险；≤7分为低风险；8-11分为中风险；≥12分为高风险。
          </div>
        </div>

        <!-- 备注 -->
        <div class="remarks-section">
          <div class="remarks-title">备注：</div>
          <div class="remarks-content">
            <div class="remark-item">1、制定适合不同风险等级的老年人活动，并做好风险防范措施；</div>
            <div class="remark-item">2、选择安全的文娱活动场所，地面应要防滑、平整，墙壁边角和家具边应做好防护处理；</div>
            <div class="remark-item">3、准确评估老年人的活动耐受力，忌做刺激性强的、运动强度高的活动；</div>
            <div class="remark-item">4、文娱活动时间不宜过长，建议1小时以内为宜；</div>
            <div class="remark-item">5、参加活动时，必须要有工作人员陪同。</div>
          </div>
        </div>

        <!-- 风险程度判断 -->
        <div class="risk-level-section">
          <div class="risk-level-title">风险程度判断：</div>
          <div class="risk-level-options">
            <div class="risk-option" :class="{ active: form.riskLevel === 'none' }">
              <el-radio v-model="form.riskLevel" label="none" :disabled="isDetail">
                无风险：0分
              </el-radio>
            </div>
            <div class="risk-option" :class="{ active: form.riskLevel === 'low' }">
              <el-radio v-model="form.riskLevel" label="low" :disabled="isDetail">
                低风险：I级
              </el-radio>
            </div>
            <div class="risk-option" :class="{ active: form.riskLevel === 'medium' }">
              <el-radio v-model="form.riskLevel" label="medium" :disabled="isDetail">
                中风险：II级
              </el-radio>
            </div>
            <div class="risk-option" :class="{ active: form.riskLevel === 'high' }">
              <el-radio v-model="form.riskLevel" label="high" :disabled="isDetail">
                高风险：III级、IV级
              </el-radio>
            </div>
            <div class="risk-option score-display">
              <span class="score-label">评估总得分：</span>
              <span class="score-value">{{ form.assessment.totalScore }} 分</span>
            </div>
          </div>
        </div>

        <!-- 评估记录 -->
        <div class="assessment-records">
          <div class="record-section">
            <div class="record-header">评估记录</div>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="评估人">
                  <el-input v-model="form.assessment.assessor" placeholder="请输入评估人" :disabled="isDetail" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="评估日期">
                  <el-date-picker
                    v-model="form.assessment.assessDate"
                    type="date"
                    placeholder="选择日期"
                    value-format="YYYY-MM-DD"
                    :disabled="isDetail"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
          
            </el-row>
          </div>
        </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 { useUserStore } from '@/store/modules/user'
import {
  entertainmentCreate, entertainmentGetById, entertainmentUpdate,
  fallDownPage, wanderAwayPage, ngasrPage,
} from "@/api/social-work";

const message = useMessage()
const userStore = useUserStore()
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 = async (e: any) => {
  console.log(e)
  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

  // 新增模式下，自动查询长者的跌倒/走失/他伤自伤风险评估，并自动选中对应值
  if (!isDetail.value && e.id) {
    await loadElderRiskData(e.id)
  }
}

// 从最新一条评估记录中解析 riskLevel
const parseRiskLevel = (record: any): string => {
  if (!record) return ''
  // 优先取顶层 riskLevel
  if (record.riskLevel) return record.riskLevel
  // 其次尝试从 assessData 中解析
  if (record.assessData) {
    try {
      const assessData = JSON.parse(record.assessData)
      if (assessData.riskLevel) return assessData.riskLevel
    } catch (err) {
      // ignore
    }
  }
  return ''
}

// 根据评估日期或创建时间获取最新一条记录
const getLatestRecord = (list: any[]): any => {
  if (!list || list.length === 0) return null
  const sorted = [...list].sort((a, b) => {
    const dateA = a.assessDate || a.createdAt || ''
    const dateB = b.assessDate || b.createdAt || ''
    return new Date(dateB).getTime() - new Date(dateA).getTime()
  })
  return sorted[0]
}

// 加载长者风险数据：跌倒风险、走失风险、他伤自伤风险
const loadElderRiskData = async (elderId: string) => {
  try {
    const params = { pageNo: 1, pageSize: 100, elderId: elderId }

    // 1. 查询跌倒风险评估
    try {
      const res = await fallDownPage(params)
      if (res && res.list && res.list.length > 0) {
        const latest = getLatestRecord(res.list)
        const riskLevel = parseRiskLevel(latest)
        if (riskLevel === 'high') {
          form.assessment.scores[1] = 8
        } else if (riskLevel === 'medium') {
          form.assessment.scores[1] = 3
        } else {
          form.assessment.scores[1] = 0
        }
      }
    } catch (err) {
      console.error('获取跌倒风险评估失败', err)
    }

    // 2. 查询走失风险评估
    try {
      const res = await wanderAwayPage(params)
      if (res && res.list && res.list.length > 0) {
        const latest = getLatestRecord(res.list)
        const riskLevel = parseRiskLevel(latest)
        if (riskLevel === 'high') {
          form.assessment.scores[2] = 8
        } else if (riskLevel === 'medium') {
          form.assessment.scores[2] = 3
        } else {
          form.assessment.scores[2] = 0
        }
      }
    } catch (err) {
      console.error('获取走失风险评估失败', err)
    }

    // 3. 查询他伤自伤风险评估（NGASR）
    try {
      const res = await ngasrPage(params)
      if (res && res.list && res.list.length > 0) {
        const latest = getLatestRecord(res.list)
        const riskLevel = parseRiskLevel(latest)
        if (riskLevel === 'high') {
          form.assessment.scores[4] = 5
        } else if (riskLevel === 'medium') {
          form.assessment.scores[4] = 1
        } else {
          form.assessment.scores[4] = 0
        }
      }
    } catch (err) {
      console.error('获取他伤自伤风险评估失败', err)
    }

    // 重新计算总分和风险等级
    calculateTotal()
  } catch (e) {
    console.error('获取风险数据失败', e)
  }
}

// 表单数据
const form = reactive({
  assessment: {
    assessDate: '',
    assessor: '',
    scores: new Array(6).fill(0),
    totalScore: 0
  },
  riskLevel: ''
})

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

  // 自动判断风险等级 (0分为无风险，≤7分为低风险；8-11分为中风险；≥12分为高风险)
  if (total === 0) {
    form.riskLevel = 'none'
  } else if (total <= 7) {
    form.riskLevel = 'low'
  } else if (total >= 8 && total <= 11) {
    form.riskLevel = 'medium'
  } else if (total >= 12) {
    form.riskLevel = 'high'
  }
}

// 获取风险等级文本
const getRiskText = (riskLevel: string) => {
  switch (riskLevel) {
    case 'none': return '无风险'
    case 'low': return '低风险'
    case 'medium': return '中风险'
    case 'high': return '高风险'
    default: return '-'
  }
}

// 获取风险等级标签类型
const getRiskTagType = (riskLevel: string) => {
  switch (riskLevel) {
    case 'none': return 'info'
    case 'low': return 'success'
    case 'medium': return 'warning'
    case 'high': return 'danger'
    default: return ''
  }
}

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

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

  if (formData.assessment) {
    form.assessment.assessDate = formData.assessment.assessDate || ''
    form.assessment.assessor = formData.assessment.assessor || ''
    form.assessment.scores = formData.assessment.scores || new Array(6).fill(0)
    form.assessment.totalScore = formData.assessment.totalScore || 0
  }
  form.riskLevel = formData.riskLevel || ''
}

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

  form.assessment = {
    assessDate: '',
    assessor: '',
    scores: new Array(6).fill(0),
    totalScore: 0
  }
  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 entertainmentGetById(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.assessor) {
        form.assessment.assessor = res.assessor
      }
      if (res.assessDate) {
        form.assessment.assessDate = res.assessDate
      }
      
      if (res.assessData) {
        const formData = JSON.parse(res.assessData)
        deserializeFormData(formData)
        // assessData中的assessor和assessDate会覆盖独立字段的值（如果存在）
      }
    }
  } 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,
      elderName: dataForm.value.elderName,
      elderSex: dataForm.value.elderSex,
      elderAge: dataForm.value.elderAge,
      bedName: dataForm.value.bedName,
      assessData: JSON.stringify(formData),
      riskLevel: form.riskLevel,
      assessScore: form.assessment.totalScore || 0,
      assessor: form.assessment.assessor,
      assessDate: form.assessment.assessDate ? dayjs(form.assessment.assessDate).format('YYYY-MM-DD') : ''
    }

    if (dataForm.value.id) {
      await entertainmentUpdate(payload)
      message.success(t('common.updateSuccess'))
    } else {
      await entertainmentCreate(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 = [
    { 
      factor: '身体健康状况基础疾病', 
      options: [
        { label: '两项疾病以上(>2项)=2分+不适合=5分', value: 5 },
        { label: '两项疾病以下(≤2项)=1分+适合=0分', value: 1 },
        { label: '两项疾病以上(>2项)2分+身体适合0分=2分', value: 2 },
        { label: '两项疾病以下(≤2项)1分+身体不适合5分=6分', value: 6 }
      ], 
      score: form.assessment.scores[0] 
    },
    { 
      factor: '跌倒风险与行动能力', 
      options: [
        { label: '高风险=5分+完全依赖=3分', value: 8 },
        { label: '中风险=1分+需要协助=2分', value: 3 },
        { label: '低风险=0分+正常=0分', value: 0 }
      ], 
      score: form.assessment.scores[1] 
    },
    { 
      factor: '走失风险与认知能力', 
      options: [
        { label: '高风险=5分+确诊认知功能障碍=3分', value: 8 },
        { label: '中风险=1分+疑似认知功能障碍=2分', value: 3 },
        { label: '低风险=0分+无认知功能障碍=0分', value: 0 }
      ], 
      score: form.assessment.scores[2] 
    },
    { 
      factor: '心理健康状况', 
      options: [
        { label: '状况很差=3分+抑郁=3分', value: 6 },
        { label: '状况较差=1分+冷漠=2分', value: 3 },
        { label: '状况良好(正常)=0', value: 0 }
      ], 
      score: form.assessment.scores[3] 
    },
    { 
      factor: '他伤及自伤风险', 
      options: [
        { label: '轻度风险=0', value: 0 },
        { label: '中度风险=1', value: 1 },
        { label: '重度风险=5', value: 5 }
      ], 
      score: form.assessment.scores[4] 
    },
    { 
      factor: '参加活动老年人之间是否发生过矛盾冲突', 
      options: [
        { label: '是=3', value: 3 },
        { label: '否=0', value: 0 }
      ], 
      score: form.assessment.scores[5] 
    }
  ]

  // 构建打印内容
  const tenantName = userStore.getTenantName || '' // 当前登录的机构名称
  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: 10pt;
          line-height: 1.4;
          color: #333;
        }
        .header {
          text-align: center;
          margin-bottom: 15px;
          border-bottom: 2px solid #333;
          padding-bottom: 10px;
        }
        .header h1 {
          font-size: 16pt;
          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;
        }
        .assessment-table th, .assessment-table td {
          border: 1px solid #333;
          padding: 8px;
          text-align: left;
          vertical-align: top;
        }
        .assessment-table th {
          background: #e8e8e8;
          font-weight: bold;
          text-align: center;
        }
        .assessment-table .col-factor {
          width: 15%;
          text-align: center;
          font-weight: bold;
          background: #f5f5f5;
        }
        .assessment-table .col-standard {
          width: 70%;
        }
        .assessment-table .col-score {
          width: 15%;
          text-align: center;
          font-weight: bold;
        }

        .risk-judgment-section {
          margin: 15px 0;
          padding: 10px;
          border: 1px solid #999;
        }
        .risk-judgment-title {
          font-weight: bold;
          margin-bottom: 10px;
        }
        .risk-options {
          display: flex;
          flex-wrap: wrap;
          gap: 15px;
        }
        .risk-option {
          display: inline-block;
        }

        .record-section {
          margin: 15px 0;
          padding: 10px;
          border: 1px solid #999;
        }
        .record-title {
          font-weight: bold;
          margin-bottom: 10px;
          border-bottom: 1px solid #ccc;
          padding-bottom: 5px;
        }
        .record-row {
          display: flex;
          gap: 30px;
          margin-bottom: 8px;
        }
        .record-item {
          display: flex;
          align-items: center;
        }
        .record-item .label {
          font-weight: bold;
          margin-right: 8px;
        }
        .record-item .value {
          border-bottom: 1px solid #333;
          min-width: 180px;
          padding: 0 5px;
          text-align: center;
        }
        .score-value {
          color: #d9534f;
          font-weight: bold;
          font-size: 14pt;
        }

        .prevention-section {
          margin: 15px 0;
          border: 1px solid #999;
        }
        .prevention-title {
          font-weight: bold;
          background: #e8e8e8;
          padding: 8px 12px;
          border-bottom: 1px solid #999;
        }
        .prevention-content {
          padding: 10px 12px;
        }
        .prevention-item {
          margin-bottom: 8px;
          font-size: 10pt;
        }
      </style>
    </head>
    <body>
      <div class="tenant-name" style="text-align: end;width: 100%;font-size: 16px; font-weight: bold; margin-bottom: 10px;">${tenantName}</div>
      <div class="header">
        <h1>防文娱活动意外评估表</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>
      </div>

      <!-- 危险因素评估表 -->
      <table class="assessment-table">
        <thead>
          <tr>
            <th class="col-factor">危险因素</th>
            <th class="col-standard">评估标准（分）</th>
            <th class="col-score">得分</th>
          </tr>
        </thead>
        <tbody>
          ${assessmentItems.map(item => `
            <tr>
              <td class="col-factor">${item.factor}</td>
              <td class="col-standard">
                ${item.options.map(opt => `${item.score === opt.value ? '☑' : '☐'} ${opt.label}=${opt.value}`).join('&nbsp;&nbsp;&nbsp;&nbsp;')}
              </td>
              <td class="col-score">${item.score}</td>
            </tr>
          `).join('')}
        </tbody>
      </table>

      <!-- 评价标准 -->
      <div class="evaluation-standard-section">
        <div class="evaluation-title">评价标准：0分为无风险；≤7分为低风险；8-11分为中风险；≥12分为高风险。</div>
      </div>

      <!-- 备注 -->
      <div class="remarks-section">
        <div class="remarks-title">备注：</div>
        <div class="remarks-content">
          <div class="remark-item">1、制定适合不同风险等级的老年人活动，并做好风险防范措施；</div>
          <div class="remark-item">2、选择安全的文娱活动场所，地面应要防滑、平整，墙壁边角和家具边应做好防护处理；</div>
          <div class="remark-item">3、准确评估老年人的活动耐受力，忌做刺激性强的、运动强度高的活动；</div>
          <div class="remark-item">4、文娱活动时间不宜过长，建议1小时以内为宜；</div>
          <div class="remark-item">5、参加活动时，必须要有工作人员陪同。</div>
        </div>
      </div>

      <!-- 风险程度判断 -->
      <div class="risk-judgment-section">
        <div class="risk-judgment-title">风险程度判断：</div>
        <div class="risk-options">
          <span class="risk-option">${form.riskLevel === 'none' ? '☑' : '☐'} 无风险：0分</span>
          <span class="risk-option">${form.riskLevel === 'low' ? '☑' : '☐'} 低风险：I级</span>
          <span class="risk-option">${form.riskLevel === 'medium' ? '☑' : '☐'} 中风险：II级</span>
          <span class="risk-option">${form.riskLevel === 'high' ? '☑' : '☐'} 高风险：III级、IV级</span>
          <span class="risk-option score-display"><strong>评估总得分：${form.assessment.totalScore} 分</strong></span>
        </div>
      </div>

      <!-- 评估记录 -->
      <div class="record-section">
        <div class="record-title">评估记录</div>
        <div class="record-row">
          <div class="record-item">
            <span class="label">评估人签名：</span>
            <span class="value">${form.assessment.assessor || ''}</span>
          </div>
          <div class="record-item">
            <span class="label">评估日期：</span>
            <span class="value">${form.assessment.assessDate || ''}</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;
  }

  .risk-factors-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;
    }

    .table-wrapper {
          border: 1px solid #f0f0f0;
          border-radius: 4px;
          overflow: hidden;
        }

        .assessment-table {
          width: 100%;
          border-collapse: collapse;

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

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

            th {
              border-bottom: 1px solid #f0f0f0;
            }
          }

          tbody {
            tr:last-child {
              td {
                border-bottom: none;
              }
            }
          }

          .col-factor {
            width: 20%;
            text-align: center;
            font-weight: bold;
            border-right: 1px solid #e4e7ed;
          }

          .col-standard {
            width: 65%;
            text-align: left;
            border-right: 1px solid #e4e7ed;

            .el-radio-group {
              display: flex;
              flex-wrap: wrap;
              gap: 20px;

              .el-radio {
                margin-right: 0;
                height: 24px;
              }
            }

            &.empty-row {
              padding: 4px;
            }
          }

          .col-score {
            width: 15%;
            text-align: center;
            font-weight: bold;
            color: #409eff;
            font-size: 16px;
          }
        }

        .evaluation-standard {
          margin-top: 15px;
          padding: 15px;
          background-color: #f5f7fa;
          border-radius: 4px;
          border: 1px solid #e4e7ed;

          .standard-title {
            font-weight: bold;
            margin-bottom: 5px;
          }

          .standard-content {
            color: #606266;
          }
        }

        .remarks-section {
          margin-top: 15px;
          padding: 15px;
          background-color: #fff;
          border: 1px solid #e4e7ed;
          border-radius: 4px;

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

          .remarks-content {
            .remark-item {
              margin-bottom: 5px;
              color: #606266;
              line-height: 1.6;
            }
          }
        }

        .risk-level-section {
          margin-top: 20px;
          padding: 15px;
          background-color: #f5f7fa;
          border: 1px solid #e4e7ed;
          border-radius: 4px;

          .risk-level-title {
            font-size: 14px;
            font-weight: bold;
            margin-bottom: 10px;
            color: #333;
          }

          .risk-level-options {
            display: flex;
            flex-wrap: wrap;
            gap: 30px;
            align-items: center;

            .risk-option {
              .el-radio {
                margin-right: 0;
              }

              &.score-display {
                margin-left: auto;
                display: flex;
                align-items: center;
                gap: 8px;

                .score-label {
                  font-weight: bold;
                  color: #333;
                }

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

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

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

  .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 {
      display: flex;
      flex-direction: column;
      gap: 10px;

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

  .evaluation-standard-section {
    margin-top: 20px;
    padding: 15px;
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
    border-radius: 4px;

    .evaluation-title {
      font-weight: bold;
      color: #333;
    }
  }

  .remarks-section {
    margin-top: 20px;
    padding: 15px;
    background-color: #fff;
    border: 1px solid #e4e7ed;
    border-radius: 4px;

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

    .remarks-content {
      .remark-item {
        margin-bottom: 8px;
        color: #606266;
        line-height: 1.6;
      }
    }
  }
      .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>
