<template>
  <el-drawer
    v-model="dialogVisible"
    :title="dialogTitle"
    size="70%"
    class="risk-disclosure-statement-form"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :destroy-on-close="true"
    @close="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="dataForm"
      label-width="120px"
      :rules="dataRule"
      v-loading="loading"
      :disabled="isView"
    >
      <!-- 长者搜索 - 参照 ProcessForm.vue 中的 SelectElder 使用方式 -->
      <div class="section-title">长者信息</div>
      <el-row :gutter="0">
        <el-col :span="12">
          <el-form-item label="长者姓名" prop="elderId">
            <SelectElder
              ref="selectElderRef"
              v-model="dataForm.elderId"
              @elder="handleSelectElder"
              type="1"
              :tId="dataForm.tenantId"
              :disabled="isEdit || isView"
            />
          </el-form-item>
        </el-col>
<!--        <el-col :span="12">-->
<!--          <el-form-item label="证件号码">-->
<!--            <TgInput v-model="dataForm.idCard" disabled />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
      </el-row>

      <!-- 长者详情展示 - 对应图片中的表一表头信息 -->
      <div  class="elder-detail-wrap">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="姓名">{{ elderDetail.elderName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ getDictLabel(DICT_TYPE.SYSTEM_USER_SEX, elderDetail.elderSex) || '-' }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ elderDetail.elderAge || '-' }}岁</el-descriptions-item>
          <el-descriptions-item label="床号">{{ elderDetail.bedName || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 服务安全风险告知书内容 -->
      <div class="section-title">服务安全风险知情告知书</div>
      <div class="notice-content">
        <p class="notice-header">尊敬的老年人／相关第三方／监护人：</p>
        <p class="notice-text">
          您好！感谢您对本机构的信任和支持。
        </p>
        <p class="notice-text">
          经我院评估您或您相关第三方的身体状况，您或您亲属在我院养老期间，存在下列服务安全风险。为保证对您或您相关第三方的服务质量，特向您告知！我院将针对老年人的情况做好相关防范措施，请您理解、配合、并支持相关工作措施的落实。
        </p>

        <!-- 风险项目表格 -->
        <div class="risk-table-wrapper">
          <table class="risk-table">
            <thead>
              <tr>
                <th class="col-index">序号</th>
                <th class="col-project">项目</th>
                <th class="col-level">风险程度</th>
                <th class="col-remark">备注</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in riskTableItems" :key="index">
                <td class="col-index">{{ index + 1 }}</td>
                <td class="col-project">{{ item.name }}：</td>
                <td class="col-level">
                  <el-select
                    v-model="item.recordId"
                    placeholder="请选择"
                    style="width: 180px"
                    :disabled="isView"
                    @change="(val: any) => handleRiskLevelChange(item, val)"
                  >
                    <el-option
                      v-for="option in getRiskOptions(item.key)"
                      :key="option.value"
                      :label="option.label"
                      :value="option.value"
                    />
                  </el-select>
                </td>
                <td class="col-remark">
                  <span class="remark-text">风险程度：</span>
                  <el-checkbox v-model="item.lowChecked" :disabled="isView" size="small">低危</el-checkbox>
                  <el-checkbox v-model="item.mediumChecked" :disabled="isView" size="small">中危</el-checkbox>
                  <el-checkbox v-model="item.highChecked" :disabled="isView" size="small">高危</el-checkbox>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 预计下次评估日期 -->
        <div class="next-assess-date">
          <span class="date-label">预计下次评估日期：</span>
          <el-date-picker
            v-model="dataForm.firstRisk"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="选择日期"
            style="width: 150px"
            :disabled="isView"
          />
          <span class="date-value">{{ dataForm.firstRisk ? formatDate(dataForm.firstRisk) : '无' }}</span>
        </div>

        <!-- 告知签名区域 -->
        <div class="signature-section">
          <div class="signature-title">告知签名：</div>
          <p class="signature-desc">
            通过对老年人的整体评估，老年人有可能发生以上风险，其风险及防范措施已向老年人或相关第三方进行了如实告知。
          </p>
          <p class="signature-declare">
            （老年人或相关第三方声明：本人已知悉并签字确认。）
          </p>
          
          <div class="signature-item">
            <span class="signature-label">经办人（护理人员）：</span>

          </div>
          
          <div class="signature-item">
            <span class="signature-label">老年人或相关第三方签名：</span>

          </div>
        </div>
      </div>

 
    </el-form>

    <template #footer>
      <el-button v-if="!isView" @click="handleClosed">取消</el-button>
      <el-button v-if="!isView" type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
      <el-button v-if="isView" @click="handleClosed">关闭</el-button>
      <el-button v-if="isView" type="success" @click="handleExport">打印</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { DICT_TYPE, getDictLabel } from '@/utils/dict'
import { getElderInfoById } from '@/api/elderly/elder/elderly-Info'
import {
  addSafetyRiskNotice,
  updateSafetyRiskNotice,
  getSafetyRiskNoticeById
} from '@/api/elderly/apply/check-in'
import { getTenantId } from '@/utils/auth'
import { useUserStore } from '@/store/modules/user'
import {
  asphyxiationPage,
  pressureSoresPage,
  fallDownPage,
  fallPreventionPage,
  burnPreventionPage,
  wanderAwayPage,
  ngasrPage,
  entertainmentPage,
  mmseGetPage
} from '@/api/social-work'
const message = useMessage() // 消息弹窗
const userStore = useUserStore()

defineOptions({ name: 'RiskDisclosureStatementForm' })

const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const dialogTitle = ref('新增服务安全风险知情告知书')
const loading = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const isView = ref(false)
const formRef = ref()
const selectElderRef = ref()

// 长者详情
const elderDetail = ref<any>({})

// 风险项目表格数据 - name 用于匹配接口
const riskTableItems = ref([
  { key: 'asphyxiation', name: '防噎食评估', api: asphyxiationPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false },
  { key: 'pressureUlcer', name: '防压疮评估', api: pressureSoresPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false },
  { key: 'fall', name: '防跌倒风险评估', api: fallDownPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false },
  { key: 'bedFall', name: '防坠床评估', api: fallPreventionPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false },
  { key: 'scald', name: '防烫伤评估', api: burnPreventionPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false },
  { key: 'wandering', name: '防走失风险评估', api: wanderAwayPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false },
  { key: 'selfHarm', name: '防自伤和他伤', api: ngasrPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false },
  { key: 'foodDrug', name: '防食品药品误食评估', api: mmseGetPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false },
  { key: 'entertainment', name: '防文娱活动意外', api: entertainmentPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false }
])

// 接口返回的风险数据选项（模拟数据，实际从接口获取）
const riskOptionsMap = ref<Record<string, any[]>>({
  asphyxiation: [],
  pressureUlcer: [],
  fall: [],
  bedFall: [],
  scald: [],
  wandering: [],
  selfHarm: [],
  foodDrug: [],
  entertainment: []
})

// 获取风险选项（从接口数据）
const getRiskOptions = (key: string) => {
  // 如果接口返回了数据，使用接口数据
  const options = riskOptionsMap.value[key]
  if (options && options.length > 0) {
    return options
  }
  // 默认选项
  return []
}

// 加载长者风险数据（动态调用各九防接口）
// preserveSelection: 是否保留已保存的选择（用于编辑模式）
const loadElderRiskData = async (elderId: string, preserveSelection = false) => {
  try {
    // 遍历每个风险项目，动态调用对应的接口
    for (const item of riskTableItems.value) {
      if (item.api && typeof item.api === 'function') {
        try {
          const params = {
            pageNo: 1,
            pageSize: 100,
            elderId: elderId
          }
          const res = await item.api(params)
          if (res && res.list && res.list.length > 0) {
            // 解析所有记录，从 assessData 中获取 riskLevel
            const options: any[] = []
            res.list.forEach((record: any) => {
              let riskLevel = record.riskLevel || 'none'
              let assessDate = record.assessDate || ''
              // 尝试从 assessData 解析 riskLevel
              if (record.assessData) {
                try {
                  const assessData = JSON.parse(record.assessData)
                  if (assessData.riskLevel) {
                    riskLevel = assessData.riskLevel
                  }
                  // 优先使用 assessData 中的 assessDate
                  if (assessData.assessDate) {
                    assessDate = assessData.assessDate
                  }
                } catch (e) {
                  console.error('解析 assessData 失败', e)
                }
              }
              // 构建选项标签：风险等级 + 评估日期
              const dateStr = assessDate ? ` (${assessDate})` : ''
              options.push({
                label: getRiskLevelLabel(riskLevel) + dateStr,
                value: record.id, // 使用记录ID作为value，确保唯一性
                riskLevel: riskLevel, // 存储riskLevel用于后续使用
                recordId: record.id,
                assessDate: assessDate
              })
            })
            // 按评估日期降序排序，最新的排在前面
            options.sort((a, b) => {
              const dateA = a.assessDate ? new Date(a.assessDate).getTime() : 0
              const dateB = b.assessDate ? new Date(b.assessDate).getTime() : 0
              return dateB - dateA
            })
            // 设置选项数据
            riskOptionsMap.value[item.key] = options

            // 如果不是保留选择模式，则默认选中日期最新的一条记录
            if (!preserveSelection) {
              const latestRecord = options[0]
              item.recordId = latestRecord.recordId // 存储选中的记录ID
              item.riskLevel = latestRecord.riskLevel // 存储riskLevel用于显示和提交
            } else {
              // 保留选择模式下，根据已保存的 recordId 从 options 中找到对应的选项并更新 riskLevel
              const selectedOption = options.find((opt: any) => opt.value === item.recordId)
              if (selectedOption) {
                item.riskLevel = selectedOption.riskLevel // 更新 riskLevel 为最新的值
              }
            }
          } else {
            // 如果没有数据且不是保留选择模式，清空当前项的选择
            if (!preserveSelection) {
              item.recordId = null
              item.riskLevel = ''
            }
          }
        } catch (err) {
          console.error(`获取${item.name}数据失败`, err)
        }
      }
    }
  } catch (e) {
    console.error('获取风险数据失败', e)
  }
}

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

// 根据风险等级更新复选框状态
const updateRiskCheckboxes = (item: any, riskLevel: string) => {
  item.lowChecked = riskLevel === 'low'
  item.mediumChecked = riskLevel === 'medium'
  item.highChecked = riskLevel === 'high'
}

// 处理风险等级选择变化
const handleRiskLevelChange = (item: any, recordId: any) => {
  // 从选项中查找对应的riskLevel
  const options = getRiskOptions(item.key)
  const selectedOption = options.find((opt: any) => opt.value === recordId)
  if (selectedOption) {
    item.riskLevel = selectedOption.riskLevel
    // 根据风险等级更新复选框
    //updateRiskCheckboxes(item, selectedOption.riskLevel)
  }
}

// 表单数据
const dataForm = reactive({
  id: undefined,
  elderId: '',
  idCard: '',
  tenantId: undefined,
  // 风险项目数据 (JSON格式存储到 riskData)
  riskData: '',
  otherRisk: '',
  // 预计下次评估日期
  nextAssessDate: '',
  // 首次告知签名
  firstRisk: '',
  firstNurseSign: '',
  firstElderSign: '',
  firstSignDate: '',
  // 第二次告知签名
  secondRisk: '',
  secondNurseSign: '',
  secondElderSign: '',
  secondSignDate: '',
  secondChangeRisk: '',
  secondRiskLevel: '',
  // 其他
  remark: '',
  nurseSign: '',
  elderSign: '',
  signDate: ''
})

// 表单校验规则
const dataRule = {
  elderId: [{ required: true, message: '长者不能为空', trigger: 'change' }]
}

// 选择长者 - 参照 ProcessForm.vue 中的使用方式
const handleSelectElder = async (item: any) => {
  if (item && item.id) {
    dataForm.elderId = item.id
    dataForm.idCard = item.idCard || ''
    // 清空之前的风险数据和选项
    riskOptionsMap.value = {
      asphyxiation: [],
      pressureUlcer: [],
      fall: [],
      bedFall: [],
      scald: [],
      wandering: [],
      selfHarm: [],
      foodDrug: [],
      entertainment: []
    }
    riskTableItems.value.forEach(tableItem => {
      tableItem.recordId = null
      tableItem.riskLevel = ''
      tableItem.lowChecked = false
      tableItem.mediumChecked = false
      tableItem.highChecked = false
    })
    // 获取长者详情
    try {
      const res = await getElderInfoById(item.id)
      elderDetail.value = res
      // 加载长者的风险评估数据
      await loadElderRiskData(item.id)
    } catch (e) {
      console.error('获取长者详情失败', e)
    }
  }
}

// 打开弹窗
const open = async (row?: any, viewMode = false) => {
  dialogVisible.value = true
  isEdit.value = false
  isView.value = viewMode
  dialogTitle.value = viewMode ? '查看服务安全风险知情告知书' : '新增服务安全风险知情告知书'
  resetForm()
  dataForm.tenantId = getTenantId()

  if (row && row.id) {
    isEdit.value = !viewMode
    dialogTitle.value = viewMode ? '查看服务安全风险知情告知书' : '编辑服务安全风险知情告知书'
    loading.value = true
    try {
      const res = await getSafetyRiskNoticeById(row.id)
      Object.assign(dataForm, res)
      // 解析风险项目
      if (res.riskData) {
        const parsedData = JSON.parse(res.riskData)
        // 解析风险表格数据
        riskTableItems.value = riskTableItems.value.map(item => {
          const saved = parsedData[item.key]
          if (saved) {
            return {
              ...item,
              recordId: saved.recordId || saved.id || null, // 恢复选中的记录ID（兼容旧数据）
              riskLevel: saved.level || '',
              lowChecked: saved.remark?.low || false,
              mediumChecked: saved.remark?.medium || false,
              highChecked: saved.remark?.high || false
            }
          }
          return item
        })
        // 解析其他风险
        if (parsedData.otherRisk !== undefined) {
          dataForm.otherRisk = parsedData.otherRisk
        }

        // 加载选项数据，但不覆盖已保存的选择
        await loadElderRiskData(res.elderId, true)
      }
      // 获取长者详情
      if (res.elderId) {
        const elderRes = await getElderInfoById(res.elderId)
        elderDetail.value = elderRes
        // 调用 SelectElder 组件的 upData 方法来设置值，但不触发 elder 事件（避免重复加载风险数据）
        selectElderRef.value?.upData?.(res.elderName, res.elderId, false)
      }
    } catch (e) {
      console.error('获取详情失败', e)
    } finally {
      loading.value = false
    }
  }
}

// 日期格式化
const formatDate = (date: any) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`
}

// 重置表单
const resetForm = () => {
  Object.assign(dataForm, {
    id: undefined,
    elderId: '',
    idCard: '',
    tenantId: getTenantId(),
    riskData: '',
    otherRisk: '',
    nextAssessDate: '',
    firstRisk: '',
    firstNurseSign: '',
    firstElderSign: '',
    firstSignDate: '',
    secondRisk: '',
    secondNurseSign: '',
    secondElderSign: '',
    secondSignDate: '',
    secondChangeRisk: '',
    secondRiskLevel: '',
    remark: '',
    nurseSign: '',
    elderSign: '',
    signDate: ''
  })
  elderDetail.value = {}
  riskTableItems.value = [
    { key: 'asphyxiation', name: '防噎食评估', api: asphyxiationPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false },
    { key: 'pressureUlcer', name: '防压疮评估', api: pressureSoresPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false },
    { key: 'fall', name: '防跌倒风险评估', api: fallDownPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false },
    { key: 'bedFall', name: '防坠床评估', api: fallPreventionPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false },
    { key: 'scald', name: '防烫伤评估', api: burnPreventionPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false },
    { key: 'wandering', name: '防走失风险评估', api: wanderAwayPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false },
    { key: 'selfHarm', name: '防自伤和他伤', api: ngasrPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false },
    { key: 'foodDrug', name: '防食品药品误食评估', api: mmseGetPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false },
    { key: 'entertainment', name: '防文娱活动意外', api: entertainmentPage, recordId: null as any, riskLevel: '', lowChecked: false, mediumChecked: false, highChecked: false }
  ]
  riskOptionsMap.value = {
    asphyxiation: [],
    pressureUlcer: [],
    fall: [],
    bedFall: [],
    scald: [],
    wandering: [],
    selfHarm: [],
    foodDrug: [],
    entertainment: []
  }
}

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

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return

  submitLoading.value = true
  try {
    // 处理风险项目数据 - 将表格数据转换为存储格式
    const riskDataObj: Record<string, any> = {}
    riskTableItems.value.forEach(item => {
      riskDataObj[item.key] = {
        id: item.recordId, // 选中的评估记录ID
        level: item.riskLevel, // 风险等级
        // 备注信息
        remark: {
          low: item.lowChecked,
          medium: item.mediumChecked,
          high: item.highChecked
        }
      }
    })
    
    const submitData = {
      ...dataForm,
      riskData: JSON.stringify(riskDataObj)
    }

    if (isEdit.value) {
      await updateSafetyRiskNotice(submitData)
    } else {
      await addSafetyRiskNotice(submitData)
    }
    message.success('操作成功')
    dialogVisible.value = false
    emit('success')
  } catch (e) {
    console.error('提交失败', e)
  } finally {
    submitLoading.value = false
  }
}

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

  // 获取长者信息
  const elderName = elderDetail.value.elderName || ''
  const elderSex = getDictLabel(DICT_TYPE.SYSTEM_USER_SEX, elderDetail.value.elderSex) || ''
  const elderAge = elderDetail.value.elderAge || ''
  const bedName = elderDetail.value.bedName || ''
  const nurseLevelName = elderDetail.value.nurseLevelName || ''
  const tenantName = userStore.getTenantName || '' // 当前登录的机构名称

  // 构建风险表格HTML
  let riskTableHtml = ''
  riskTableItems.value.forEach((item, index) => {
    const riskLevelText = getRiskLevelText(item.riskLevel)
    const lowChecked = item.lowChecked ? '☑' : '☐'
    const mediumChecked = item.mediumChecked ? '☑' : '☐'
    const highChecked = item.highChecked ? '☑' : '☐'
    
    riskTableHtml += `
      <tr>
        <td style="border: 1px solid #333; padding: 8px; text-align: center;">${index + 1}</td>
        <td style="border: 1px solid #333; padding: 8px;">${item.name}</td>
        <td style="border: 1px solid #333; padding: 8px; text-align: center;">${riskLevelText}</td>
        <td style="border: 1px solid #333; padding: 8px;">
          <span>风险程度：</span>
          <span>${lowChecked}低危</span>
          <span style="margin-left: 10px;">${mediumChecked}中危</span>
          <span style="margin-left: 10px;">${highChecked}高危</span>
        </td>
      </tr>
    `
  })

  // 预计下次评估日期
  const nextAssessDate = dataForm.nextAssessDate ? formatDate(dataForm.nextAssessDate) : '无'

  // 构建打印内容
  const printContent = `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>服务安全风险知情告知书</title>
      <style>
        body { font-family: 'SimSun', serif; font-size: 14px; line-height: 1.6; }
        .print-container { width: 210mm; margin: 0 auto; padding: 20mm; }
        .title { text-align: center; font-size: 22px; font-weight: bold; margin-bottom: 20px; }
        .subtitle { text-align: center; font-size: 16px; margin-bottom: 30px; }
        .info-row { display: flex; margin-bottom: 10px; }
        .info-item { flex: 3; }
        .section-title { font-weight: bold; margin: 20px 0 10px; }
        .content-text { text-indent: 2em; margin-bottom: 10px; }
        table { width: 100%; border-collapse: collapse; margin: 15px 0; }
        th { background-color: #f5f5f5; font-weight: bold; }
        .signature-section { margin-top: 30px; }
        .signature-title { font-weight: bold; margin-bottom: 10px; }
        .signature-item { margin: 15px 0; }
        .signature-line { display: inline-block; width: 200px; border-bottom: 1px solid #333; margin-left: 10px; }
        .next-date { margin: 15px 0; padding: 10px; background-color: #f5f5f5; }
        @media print { body { margin: 0; } .print-container { padding: 10mm; } }
      </style>
    </head>
    <body>
      <div class="print-container">
        <div class="tenant-name" style="text-align: end;width: 100%;font-size: 16px; font-weight: bold; margin-bottom: 10px;">${tenantName}</div>
        <div class="title">服务安全风险知情告知书</div>
        
        <div class="info-row">
          <div class="info-item">姓名：${elderName}</div>
          <div class="info-item" style="flex: 2">性别：${elderSex}</div>
          <div class="info-item" style="flex: 2">年龄：${elderAge}岁</div>
          <div class="info-item">床号：${bedName}</div>
          <div class="info-item">护理级别：${nurseLevelName}</div>
        </div>

        <div class="section-title">尊敬的老年人／相关第三方／监护人：</div>
        <div class="content-text">您好！感谢您对本机构的信任和支持。</div>
        <div class="content-text">
          经我院评估您或您相关第三方的身体状况，您或您亲属在我院养老期间，存在下列服务安全风险。
          为保证对您或您相关第三方的服务质量，特向您告知！我院将针对老年人的情况做好相关防范措施，
          请您理解、配合、并支持相关工作措施的落实。
        </div>

        <table>
          <thead>
            <tr>
              <th style="border: 1px solid #333; padding: 8px; width: 60px;">序号</th>
              <th style="border: 1px solid #333; padding: 8px;">项目</th>
              <th style="border: 1px solid #333; padding: 8px; width: 100px;">风险程度</th>
              <th style="border: 1px solid #333; padding: 8px;">备注</th>
            </tr>
          </thead>
          <tbody>
            ${riskTableHtml}
          </tbody>
        </table>

        <div class="next-date">
          <strong>预计下次评估日期：</strong>${dataForm.firstRisk}
        </div>

        <div class="signature-section">
          <div class="signature-title">告知签名：</div>
          <div class="content-text">
            通过对老年人的整体评估，老年人有可能发生以上风险，其风险及防范措施已向老年人或相关第三方进行了如实告知。
          </div>
          <div style="color: #666; font-size: 12px; margin-bottom: 20px;">
            （老年人或相关第三方声明：本人已知悉并签字确认。）
          </div>
          
          <div class="signature-item">
            <span>经办人（护理人员）：</span>
          
          </div>
          
          <div class="signature-item">
            <span>老年人或相关第三方签名：</span>
           
          </div>
        </div>

        ${dataForm.remark ? `<div class="section-title">其他备注：</div><div>${dataForm.remark}</div>` : ''}
      </div>
      <script>
        window.onload = function() {
          setTimeout(function() {
            window.print();
          }, 500);
        };
      <\/script>
    </body>
    </html>
  `

  printWindow.document.write(printContent)
  printWindow.document.close()
}

// 获取风险等级文本
const getRiskLevelText = (level: string): string => {
  const levelMap: Record<string, string> = {
    'none': '无风险',
    'low': '低风险',
    'medium': '中风险',
    'high': '高风险'
  }
  return levelMap[level] || level || '-'
}

defineExpose({ open })
</script>

<style scoped lang="scss">
.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 20px 0 15px;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}

.elder-detail-wrap {
  margin: 15px 0;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.notice-content {
  padding: 15px;
  background-color: #fafafa;
  border-radius: 4px;
  margin-bottom: 20px;

  .notice-header {
    font-weight: bold;
    margin-bottom: 10px;
  }

  .notice-text {
    text-indent: 2em;
    line-height: 1.8;
    margin-bottom: 10px;
  }
}

// 风险表格样式
.risk-table-wrapper {
  margin: 20px 0;
  overflow-x: auto;

  .risk-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;

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

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

    .col-index {
      width: 60px;
    }

    .col-project {
      width: 180px;
      text-align: left;
      padding-left: 15px;
    }

    .col-level {
      width: 140px;
    }

    .col-remark {
      width: auto;
      text-align: left;
      padding-left: 15px;

      .remark-text {
        margin-right: 10px;
        color: #606266;
      }

      :deep(.el-checkbox) {
        margin-right: 15px;
      }
    }
  }
}

// 预计下次评估日期
.next-assess-date {
  display: flex;
  align-items: center;
  margin: 20px 0;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;

  .date-label {
    font-weight: bold;
    margin-right: 15px;
    color: #333;
  }

  .date-value {
    margin-left: 15px;
    color: #606266;
  }
}

// 签名区域
.signature-section {
  margin-top: 30px;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 4px;
  border: 1px solid #ebeef5;

  .signature-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
    color: #333;
  }

  .signature-desc {
    text-indent: 2em;
    line-height: 1.8;
    margin-bottom: 10px;
    color: #606266;
  }

  .signature-declare {
    text-indent: 2em;
    margin-bottom: 25px;
    color: #909399;
    font-size: 13px;
  }

  .signature-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .signature-label {
      font-weight: bold;
      white-space: nowrap;
      color: #333;
    }

    .signature-line {
      flex: 1;
      height: 1px;
      border-bottom: 1px solid #333;
      margin-left: 10px;
      min-width: 200px;
    }
  }
}

.other-risk {
  margin-top: 15px;
}
</style>
