<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>
        <table class="assessment-table">
          <thead>
            <tr>
              <th class="col-factor">危险因素</th>
              <th class="col-score-header">是</th>
              <th class="col-score-header">否</th>
              <th class="col-result">得分</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, itemIndex) in riskFactors" :key="itemIndex">
              <td class="col-factor">{{ item.name }}</td>
              <td class="col-score-header">
                <el-radio-group v-model="form.assessment.scores[itemIndex]" :disabled="isDetail" @change="calculateTotal">
                  <el-radio :label="item.yesScore">{{ item.yesScore }}分</el-radio>
                </el-radio-group>
              </td>
              <td class="col-score-header">
                <el-radio-group v-model="form.assessment.scores[itemIndex]" :disabled="isDetail" @change="calculateTotal">
                  <el-radio :label="item.noScore">{{ item.noScore }}分</el-radio>
                </el-radio-group>
              </td>
              <td class="col-result">{{ form.assessment.scores[itemIndex] }}</td>
            </tr>
          </tbody>
        </table>

        <!-- 风险程度判断 -->
        <div class="risk-judgment">
          <span class="judgment-title">风险程度判断：</span>
          <el-radio-group v-model="form.riskLevel" :disabled="isDetail">
            <el-radio label="none">无风险：≤1分</el-radio>
            <el-radio label="low">低风险：2分</el-radio>
            <el-radio label="medium">中风险：3分</el-radio>
            <el-radio label="high">高风险：≥4分</el-radio>
          </el-radio-group>
        </div>
      </div>

      <!-- 评估记录 -->
      <div class="assessment-records">
        <div class="record-section">
          <div class="record-header">评估记录</div>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="评估日期：" label-width="120px">
                <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-col :span="6">
              <el-form-item label="评估人签名：" label-width="120px">
                <el-input v-model="form.assessment.assessor" :disabled="isDetail" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="评估总得分：" label-width="120px">
                <span class="score-text">{{ form.assessment.totalScore }} 分</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="风险等级结果：" label-width="120px">
                <el-tag :type="getRiskTagType(form.riskLevel)">
                  {{ getRiskText(form.riskLevel) }}
                </el-tag>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 预防措施 -->
      <div class="prevention-section">
        <div class="section-title">预防措施：</div>
        <el-checkbox-group v-model="form.preventionMeasures" :disabled="isDetail" class="prevention-group">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-checkbox label="加勤巡视，随时发现安全隐患">加勤巡视，随时发现安全隐患</el-checkbox>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-checkbox label="睡觉时拉起两侧床栏如需下床请将床栏放下，切勿翻越床栏">睡觉时拉起两侧床栏如需下床请将床栏放下，切勿翻越床栏</el-checkbox>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-checkbox label="常检查床的牢固性，发现不稳定时立即对床进行加固">常检查床的牢固性，发现不稳定时立即对床进行加固</el-checkbox>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-checkbox label="发现老人睡在床边缘时，应将老人调整到床中央">发现老人睡在床边缘时，应将老人调整到床中央</el-checkbox>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-checkbox label="翻身时叮嘱老人动作要慢，幅度要小确保安全">翻身时叮嘱老人动作要慢，幅度要小确保安全</el-checkbox>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-checkbox label="将生活用品、尿壶便器等放于易拿之处">将生活用品、尿壶便器等放于易拿之处</el-checkbox>
            </el-col>
          </el-row>
        </el-checkbox-group>
      </div>


    </div>

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

<script lang="ts" setup>
import { computed, ref, reactive } from 'vue'
import dayjs from 'dayjs'
import {
  fallPreventionCreate,
  fallPreventionGetById,
  fallPreventionUpdate
} from "@/api/social-work";

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

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

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

// 危险因素定义
const riskFactors = [
  { name: '最近一年曾有不明原因的坠床或跌倒经历', yesScore: 1, noScore: 0 },
  { name: '意识障碍', yesScore: 1, noScore: 0 },
  { name: '近期有癫痫病史', yesScore: 1, noScore: 0 },
  { name: '视力障碍', yesScore: 1, noScore: 0 },
  { name: '活动障碍，肢体偏瘫', yesScore: 3, noScore: 0 },
  { name: '年龄大于或等于 65 岁', yesScore: 1, noScore: 0 },
  { name: '体能虚弱', yesScore: 3, noScore: 0 },
  { name: '头晕、眩晕、体位性低血压', yesScore: 2, noScore: 0 },
  { name: '服用影响意识或行动的药物，如催眠剂、镇静安神药物，利尿剂、抗癫痫剂、麻醉止痛剂', yesScore: 1, noScore: 0 },
  { name: '吸毒、酗酒史', yesScore: 1, noScore: 0 },
  { name: '住院中无人陪伴', yesScore: 1, noScore: 0 },
  { name: '睡气垫床', yesScore: 1, noScore: 0 }
]

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

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

  // 自动判断风险等级
  if (total <= 1) {
    form.riskLevel = 'none'
  } else if (total === 2) {
    form.riskLevel = 'low'
  } else if (total === 3) {
    form.riskLevel = 'medium'
  } else if (total >= 4) {
    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 'success'
    case 'low': return 'info'
    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
    },
    preventionMeasures: form.preventionMeasures || [],
    riskLevel: form.riskLevel
  }
}

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

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

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

  form.assessment = {
    assessDate: '',
    assessor: '',
    scores: new Array(12).fill(0),
    totalScore: 0
  }
  form.preventionMeasures = []
  form.riskLevel = ''
}

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

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

defineExpose({ open })

const emit = defineEmits(['success'])

/** 提交表单 */
const submitForm = async () => {
  if (!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),
      assessScore: form.assessment.totalScore || 0,
      riskLevel: form.riskLevel,
      assessor: form.assessment.assessor,
      assessDate: form.assessment.assessDate ? dayjs(form.assessment.assessDate).format('YYYY-MM-DD') : ''
    }

    if (dataForm.value.id) {
      await fallPreventionUpdate(payload)
      message.success(t('common.updateSuccess'))
    } else {
      await fallPreventionCreate(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 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: center;
          vertical-align: middle;
        }
        .assessment-table th {
          background: #e8e8e8;
          font-weight: bold;
        }
        .assessment-table .col-factor {
          width: 60%;
          text-align: left;
          font-weight: bold;
          background: #f5f5f5;
        }
        .assessment-table .col-score-header {
          width: 15%;
        }
        .assessment-table .col-result {
          width: 10%;
          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: 100px;
          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="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-score-header">是</th>
            <th class="col-score-header">否</th>
            <th class="col-result">得分</th>
          </tr>
        </thead>
        <tbody>
          ${riskFactors.map((item, index) => `
            <tr>
              <td class="col-factor">${item.name}</td>
              <td class="col-score-header">${form.assessment.scores[index] === item.yesScore ? '☑' : '☐'} ${item.yesScore}分</td>
              <td class="col-score-header">${form.assessment.scores[index] === item.noScore ? '☑' : '☐'} ${item.noScore}分</td>
              <td class="col-result">${form.assessment.scores[index]}</td>
            </tr>
          `).join('')}
        </tbody>
      </table>

      <!-- 风险程度判断 -->
      <div class="risk-judgment-section">
        <div class="risk-judgment-title">风险程度判断：</div>
        <div class="risk-options">
          <span class="risk-option">${form.riskLevel === 'none' ? '☑' : '☐'} 无风险：≤1分</span>
          <span class="risk-option">${form.riskLevel === 'low' ? '☑' : '☐'} 低风险：2分</span>
          <span class="risk-option">${form.riskLevel === 'medium' ? '☑' : '☐'} 中风险：3分</span>
          <span class="risk-option">${form.riskLevel === 'high' ? '☑' : '☐'} 高风险：≥4分</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.assessDate || ''}</span>
          </div>
          <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 score-value">${form.assessment.totalScore} 分</span>
          </div>
          <div class="record-item">
            <span class="label">风险等级结果：</span>
            <span class="value">${getRiskText(form.riskLevel)}</span>
          </div>
        </div>
      </div>

      <!-- 预防措施 -->
      <div class="prevention-section">
        <div class="prevention-title">预防措施</div>
        <div class="prevention-content">
          <div class="prevention-item">${form.preventionMeasures?.includes('加勤巡视，随时发现安全隐患') ? '☑' : '☐'} 加勤巡视，随时发现安全隐患</div>
          <div class="prevention-item">${form.preventionMeasures?.includes('睡觉时拉起两侧床栏如需下床请将床栏放下，切勿翻越床栏') ? '☑' : '☐'} 睡觉时拉起两侧床栏如需下床请将床栏放下，切勿翻越床栏</div>
          <div class="prevention-item">${form.preventionMeasures?.includes('常检查床的牢固性，发现不稳定时立即对床进行加固') ? '☑' : '☐'} 常检查床的牢固性，发现不稳定时立即对床进行加固</div>
          <div class="prevention-item">${form.preventionMeasures?.includes('发现老人睡在床边缘时，应将老人调整到床中央') ? '☑' : '☐'} 发现老人睡在床边缘时，应将老人调整到床中央</div>
          <div class="prevention-item">${form.preventionMeasures?.includes('翻身时叮嘱老人动作要慢，幅度要小确保安全') ? '☑' : '☐'} 翻身时叮嘱老人动作要慢，幅度要小确保安全</div>
          <div class="prevention-item">${form.preventionMeasures?.includes('将生活用品、尿壶便器等放于易拿之处') ? '☑' : '☐'} 将生活用品、尿壶便器等放于易拿之处</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;
    }

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

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

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

      .col-factor {
        width: 50%;
        text-align: left;
      }

      .col-score-header {
        width: 20%;
      }

      .col-result {
        width: 10%;
        font-weight: bold;
        color: #409eff;
      }
    }

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

      .judgment-title {
        font-weight: bold;
        margin-right: 15px;
      }
    }
  }

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