<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
                  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.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-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-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="身高(m)">
                <el-input-number v-model="form.height" :min="0" :max="3" :precision="2" :step="0.01" :disabled="isDetail" style="width: 100%" @change="calculateBMI" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="体重(Kg)">
                <el-input-number v-model="form.weight" :min="0" :max="200" :precision="1" :step="0.5" :disabled="isDetail" style="width: 100%" @change="calculateBMI" />
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="form.bmi">
              <el-form-item label="BMI">
                <span class="bmi-value">{{ form.bmi.toFixed(1) }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 营养风险评估表 -->
      <div class="nutritional-section">


        <!-- 初筛部分 -->
        <div class="subsection-title">初筛</div>
        <table class="assessment-table">
          <thead>
            <tr>
              <th class="col-item">项目</th>
              <th class="col-score-0">0分</th>
              <th class="col-score-1">1分</th>
              <th class="col-score-2">2分</th>
              <th class="col-score-3">3分</th>
            </tr>
          </thead>
          <tbody>
          <!-- 6. 近三个月有无饮食量变化 -->
          <tr>
            <td class="col-item">1. 近三个月有无饮食量变化</td>
            <td class="col-score">
              <el-radio :label="0" v-model="form.initialScores[5]" :disabled="isDetail" @change="calculateScores">严重增加或减少</el-radio>
            </td>
            <td class="col-score">
              <el-radio :label="1" v-model="form.initialScores[5]" :disabled="isDetail" @change="calculateScores">增加或减少</el-radio>
            </td>
            <td class="col-score">
              <el-radio :label="2" v-model="form.initialScores[5]" :disabled="isDetail" @change="calculateScores">无变化</el-radio>
            </td>
            <td class="col-score">—</td>
          </tr>

          <!-- 2. 近3个月体重变化 -->
          <tr>
            <td class="col-item">2. 近3个月体重变化</td>
            <td class="col-score">
              <el-radio :label="0" v-model="form.initialScores[1]" :disabled="isDetail" @change="calculateScores">减少或增加≥3Kg</el-radio>
            </td>
            <td class="col-score">
              <el-radio :label="1" v-model="form.initialScores[1]" :disabled="isDetail" @change="calculateScores">不知道</el-radio>
            </td>
            <td class="col-score">
              <el-radio :label="2" v-model="form.initialScores[1]" :disabled="isDetail" @change="calculateScores">1Kg≤减少&lt;3Kg<br/>或1Kg≤增加&lt;3Kg</el-radio>
            </td>
            <td class="col-score">
              <el-radio :label="3" v-model="form.initialScores[1]" :disabled="isDetail" @change="calculateScores">0Kg&lt;减少&lt;1Kg<br/>或0Kg&lt;增加&lt;1Kg</el-radio>
            </td>
          </tr>
          <!-- 3. 活动能力 -->
          <tr>
            <td class="col-item">3. 活动能力</td>
            <td class="col-score">
              <el-radio :label="0" v-model="form.initialScores[2]" :disabled="isDetail" @change="calculateScores">卧床</el-radio>
            </td>
            <td class="col-score">
              <el-radio :label="1" v-model="form.initialScores[2]" :disabled="isDetail" @change="calculateScores">需要依赖工具活动</el-radio>
            </td>
            <td class="col-score">
              <el-radio :label="2" v-model="form.initialScores[2]" :disabled="isDetail" @change="calculateScores">独立户外活动</el-radio>
            </td>
            <td class="col-score">—</td>
          </tr>
          <!-- 4. 牙齿状况 -->
          <tr>
            <td class="col-item">4. 牙齿状况</td>
            <td class="col-score">
              <el-radio :label="0" v-model="form.initialScores[3]" :disabled="isDetail" @change="calculateScores">全口或半口缺</el-radio>
            </td>
            <td class="col-score">
              <el-radio :label="1" v-model="form.initialScores[3]" :disabled="isDetail" @change="calculateScores">用义齿</el-radio>
            </td>
            <td class="col-score">
              <el-radio :label="2" v-model="form.initialScores[3]" :disabled="isDetail" @change="calculateScores">正常</el-radio>
            </td>
            <td class="col-score">—</td>
          </tr>

            <!-- 5. 神经精神疾病 -->
            <tr>
              <td class="col-item">5. 神经精神疾病</td>
              <td class="col-score">
                <el-radio :label="0" v-model="form.initialScores[4]" :disabled="isDetail" @change="calculateScores">严重认知障碍或抑郁</el-radio>
              </td>
              <td class="col-score">
                <el-radio :label="1" v-model="form.initialScores[4]" :disabled="isDetail" @change="calculateScores">轻度认知障碍或抑郁</el-radio>
              </td>
              <td class="col-score">
                <el-radio :label="2" v-model="form.initialScores[4]" :disabled="isDetail" @change="calculateScores">无认知障碍或抑郁</el-radio>
              </td>
              <td class="col-score">—</td>
            </tr>
          <!-- 1. BMI -->
          <tr>
            <td class="col-item">6. BMI</td>
            <td class="col-score">
              <el-radio :label="0" v-model="form.initialScores[0]" :disabled="isDetail" @change="calculateScores">BMI&lt;19<br/>或 BMI≥28</el-radio>
            </td>
            <td class="col-score">
              <el-radio :label="1" v-model="form.initialScores[0]" :disabled="isDetail" @change="calculateScores">19≤BMI&lt;21<br/>或 26≤BMI&lt;28</el-radio>
            </td>
            <td class="col-score">
              <el-radio :label="2" v-model="form.initialScores[0]" :disabled="isDetail" @change="calculateScores">21≤BMI&lt;23<br/>或24≤BMI&lt;26</el-radio>
            </td>
            <td class="col-score">
              <el-radio :label="3" v-model="form.initialScores[0]" :disabled="isDetail" @change="calculateScores">23≤BMI≤24</el-radio>
            </td>
          </tr>


          </tbody>
        </table>

        <!-- 初筛提示 -->
        <div class="initial-tip">
          <p>总分14分，&lt;12分提示有营养不良风险，继续以下评估；≥12分提示无营养不良风险，无需以下评估。</p>
          <p class="score-display">初筛分数（小计满分14分）：<span class="score-value">{{ form.initialScore }}</span> 分</p>
        </div>

        <!-- 评估部分 -->
        <div class="subsection-title">评估</div>
        <table class="assessment-table">
          <thead>
            <tr>
              <th class="col-item">项目</th>
              <th class="col-score-0">0分</th>
              <th class="col-score-05">0.5分</th>
              <th class="col-score-1">1分</th>
              <th class="col-score-2">2分</th>
            </tr>
          </thead>
          <tbody>
            <!-- 7. 患慢性病数>3种 -->
            <tr>
              <td class="col-item">7. 患慢性病数&gt;3种</td>
              <td class="col-score">
                <el-radio :label="0" v-model="form.assessScores[0]" :disabled="isDetail" @change="calculateScores">是</el-radio>
              </td>
              <td class="col-score">—</td>
              <td class="col-score">
                <el-radio :label="1" v-model="form.assessScores[0]" :disabled="isDetail" @change="calculateScores">否</el-radio>
              </td>
              <td class="col-score">—</td>
            </tr>

            <!-- 8. 服药时间在一个月以上的药物种类>3种 -->
            <tr>
              <td class="col-item">8. 服药时间在一个月以上的药物种类&gt;3种</td>
              <td class="col-score">
                <el-radio :label="0" v-model="form.assessScores[1]" :disabled="isDetail" @change="calculateScores">是</el-radio>
              </td>
              <td class="col-score">—</td>
              <td class="col-score">
                <el-radio :label="1" v-model="form.assessScores[1]" :disabled="isDetail" @change="calculateScores">否</el-radio>
              </td>
              <td class="col-score">—</td>
            </tr>

            <!-- 9. 是否独居 -->
            <tr>
              <td class="col-item">9. 是否独居</td>
              <td class="col-score">
                <el-radio :label="0" v-model="form.assessScores[2]" :disabled="isDetail" @change="calculateScores">是</el-radio>
              </td>
              <td class="col-score">—</td>
              <td class="col-score">
                <el-radio :label="1" v-model="form.assessScores[2]" :disabled="isDetail" @change="calculateScores">否</el-radio>
              </td>
              <td class="col-score">—</td>
            </tr>

            <!-- 10. 睡眠时间 -->
            <tr>
              <td class="col-item">10. 睡眠时间</td>
              <td class="col-score">
                <el-radio :label="0" v-model="form.assessScores[3]" :disabled="isDetail" @change="calculateScores">&lt;5h/d</el-radio>
              </td>
              <td class="col-score">—</td>
              <td class="col-score">
                <el-radio :label="1" v-model="form.assessScores[3]" :disabled="isDetail" @change="calculateScores">≥5h/d</el-radio>
              </td>
              <td class="col-score">—</td>
            </tr>

            <!-- 11. 户外独立活动时间 -->
            <tr>
              <td class="col-item">11. 户外独立活动时间</td>
              <td class="col-score">
                <el-radio :label="0" v-model="form.assessScores[4]" :disabled="isDetail" @change="calculateScores">&lt;1h/d</el-radio>
              </td>
              <td class="col-score">—</td>
              <td class="col-score">
                <el-radio :label="1" v-model="form.assessScores[4]" :disabled="isDetail" @change="calculateScores">≥1h/d</el-radio>
              </td>
              <td class="col-score">—</td>
            </tr>

            <!-- 12. 文化程度 -->
            <tr>
              <td class="col-item">12. 文化程度</td>
              <td class="col-score">
                <el-radio :label="0" v-model="form.assessScores[5]" :disabled="isDetail" @change="calculateScores">小学及以下</el-radio>
              </td>
              <td class="col-score">—</td>
              <td class="col-score">
                <el-radio :label="1" v-model="form.assessScores[5]" :disabled="isDetail" @change="calculateScores">中学及以上</el-radio>
              </td>
              <td class="col-score">—</td>
            </tr>

            <!-- 13. 自我感觉经济状况 -->
            <tr>
              <td class="col-item">13. 自我感觉经济状况</td>
              <td class="col-score">
                <el-radio :label="0" v-model="form.assessScores[6]" :disabled="isDetail" @change="calculateScores">差</el-radio>
              </td>
              <td class="col-score">
                <el-radio :label="0.5" v-model="form.assessScores[6]" :disabled="isDetail" @change="calculateScores">一般</el-radio>
              </td>
              <td class="col-score">
                <el-radio :label="1" v-model="form.assessScores[6]" :disabled="isDetail" @change="calculateScores">良好</el-radio>
              </td>
              <td class="col-score">—</td>
            </tr>

            <!-- 14. 进食能力 -->
            <tr>
              <td class="col-item">14. 进食能力</td>
              <td class="col-score">
                <el-radio :label="0" v-model="form.assessScores[7]" :disabled="isDetail" @change="calculateScores">依靠别人</el-radio>
              </td>
              <td class="col-score">—</td>
              <td class="col-score">
                <el-radio :label="1" v-model="form.assessScores[7]" :disabled="isDetail" @change="calculateScores">自行进食稍有困难</el-radio>
              </td>
              <td class="col-score">
                <el-radio :label="2" v-model="form.assessScores[7]" :disabled="isDetail" @change="calculateScores">自行进食</el-radio>
              </td>
            </tr>

            <!-- 15. 一天餐次 -->
            <tr>
              <td class="col-item">15. 一天餐次</td>
              <td class="col-score">
                <el-radio :label="0" v-model="form.assessScores[8]" :disabled="isDetail" @change="calculateScores">1次</el-radio>
              </td>
              <td class="col-score">—</td>
              <td class="col-score">
                <el-radio :label="1" v-model="form.assessScores[8]" :disabled="isDetail" @change="calculateScores">2次</el-radio>
              </td>
              <td class="col-score">
                <el-radio :label="2" v-model="form.assessScores[8]" :disabled="isDetail" @change="calculateScores">3次及以上</el-radio>
              </td>
            </tr>

            <!-- 16. 每天摄入奶类/豆制品/鱼肉类 -->
            <tr>
              <td class="col-item">16. 每天摄入奶类：<br/>每天摄入豆制品：<br/>每天摄入鱼/肉/蛋类食品</td>
              <td class="col-score">
                <el-radio :label="0" v-model="form.assessScores[9]" :disabled="isDetail" @change="calculateScores">0-1项</el-radio>
              </td>
              <td class="col-score">
                <el-radio :label="0.5" v-model="form.assessScores[9]" :disabled="isDetail" @change="calculateScores">2项</el-radio>
              </td>
              <td class="col-score">
                <el-radio :label="1" v-model="form.assessScores[9]" :disabled="isDetail" @change="calculateScores">3项</el-radio>
              </td>
              <td class="col-score">—</td>
            </tr>

            <!-- 17. 每天烹调油摄入量 -->
            <tr>
              <td class="col-item">17. 每天烹调油摄入量</td>
              <td class="col-score">
                <el-radio :label="0" v-model="form.assessScores[10]" :disabled="isDetail" @change="calculateScores">≥25g</el-radio>
              </td>
              <td class="col-score">—</td>
              <td class="col-score">
                <el-radio :label="1" v-model="form.assessScores[10]" :disabled="isDetail" @change="calculateScores">&lt;25g</el-radio>
              </td>
              <td class="col-score">—</td>
            </tr>

            <!-- 18. 是否每天吃蔬菜水果500g以上 -->
            <tr>
              <td class="col-item">18. 是否每天吃蔬菜水果500g及以上</td>
              <td class="col-score">
                <el-radio :label="0" v-model="form.measureScores[0]" :disabled="isDetail" @change="calculateScores">否</el-radio>
              </td>
              <td class="col-score">—</td>
              <td class="col-score">
                <el-radio :label="1" v-model="form.measureScores[0]" :disabled="isDetail" @change="calculateScores">是</el-radio>
              </td>
              <td class="col-score">—</td>
            </tr>

            <!-- 19. 小腿围 -->
            <tr>
              <td class="col-item">19. 小腿围</td>
              <td class="col-score">
                <el-radio :label="0" v-model="form.measureScores[1]" :disabled="isDetail" @change="calculateScores">&lt;31cm</el-radio>
              </td>
              <td class="col-score">—</td>
              <td class="col-score">
                <el-radio :label="1" v-model="form.measureScores[1]" :disabled="isDetail" @change="calculateScores">≥31cm</el-radio>
              </td>
              <td class="col-score">—</td>
            </tr>

            <!-- 20. 腰围 -->
            <tr>
              <td class="col-item">20. 腰围</td>
              <td class="col-score" colspan="2">
                <div class="waist-row">
                  <span class="waist-label">男：</span>
                  <el-radio :label="0" v-model="form.waistScore" :disabled="isDetail" @change="onWaistChange">&gt;90cm</el-radio>
                </div>
                <div class="waist-row">
                  <span class="waist-label">女：</span>
                  <el-radio :label="2" v-model="form.waistScore" :disabled="isDetail" @change="onWaistChange">&gt;80cm</el-radio>
                </div>
              </td>
              <td class="col-score" colspan="2">
                <div class="waist-row">
                  <el-radio :label="1" v-model="form.waistScore" :disabled="isDetail" @change="onWaistChange">≤90cm</el-radio>
                </div>
                <div class="waist-row">
                  <el-radio :label="3" v-model="form.waistScore" :disabled="isDetail" @change="onWaistChange">≤80cm</el-radio>
                </div>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 测量输入 -->
        <div class="measure-inputs">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="小腿围(cm)：">
                <el-input-number v-model="form.calfCircumference" :min="0" :max="100" :precision="1" :disabled="isDetail" style="width: 150px" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="腰围(cm)：">
                <el-input-number v-model="form.waistCircumference" :min="0" :max="200" :precision="1" :disabled="isDetail" style="width: 150px" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 年龄调整 -->
        <div class="age-adjust">
          <p>年龄超过70岁总分加1分，即年龄调整增加的分值：<span class="score-value">{{ form.ageAdjust }}</span>分，年龄&lt;70岁：0分，年龄≥70岁：1分</p>
        </div>

        <!-- 分数汇总 -->
        <div class="score-summary">
          <div class="summary-item">
            <span class="label">初筛分数（小计满分14分）：</span>
            <span class="value">{{ form.initialScore }} 分</span>
          </div>
          <div class="summary-item">
            <span class="label">评估分数（小计满分16分）：</span>
            <span class="value">{{ form.assessScore + form.measureScore }} 分</span>
          </div>
          <div class="summary-item">
            <span class="label">年龄调整（≥70岁加1分）：</span>
            <span class="value">{{ form.ageAdjust }} 分</span>
          </div>
          <div class="summary-item">
            <span class="label">量表总分（满分30分）：</span>
            <span class="value total">{{ form.totalScore }} 分</span>
          </div>
        </div>

        <!-- 评分标准 -->
        <div class="scoring-standard">
          <div class="standard-title">评分标准：</div>
          <div class="standard-content">
            <p>若初筛总分≥12分提示无营养不良风险，无需评估；</p>
            <p>若初筛总分&lt;12分提示有营养不良风险，继续评估；</p>
            <p>若营养不良风险评估总分（初筛+评估）≥24分，表示营养状况良好；</p>
            <p>若营养不良风险评估总分（初筛+评估）17分～24分（不含24分），表示有营养不良风险；</p>
            <p>若营养不良风险评估总分（初筛+评估）≤17分，表示有营养不良。</p>
          </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>
      <div style="flex: auto">
        <el-button v-if="!isDetail" type="primary" @click="submitForm">保存</el-button>
        <el-button v-if="!isDetail" @click="handleClosed">取消</el-button>
        <el-button v-if="isDetail" @click="handleClosed">关闭</el-button>
       <el-button v-if="isDetail" type="primary" @click="handleExport">打印</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { useAppStore } from '@/store/modules/app'
import { useUserStore } from '@/store/modules/user'
import {
  nutritionalRiskCreate,
  nutritionalRiskUpdate,
  nutritionalRiskGetById,
  NutritionalRiskFormData
} from '@/api/social-work'
import {getTenantId} from "@/utils/auth";

const message = useMessage()
const userStore = useUserStore()
const appStore = useAppStore()
const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const title = ref('新增营养风险评估')
const isDetail = ref(false)
const formRef = ref()
const selectElderRef = ref()

const dataForm = reactive({
  id: undefined as number | undefined,
  elderId: undefined as number | undefined,
  tenantId: appStore.getTenantId,
  elderName: '',
  elderSex: '',
  bedName: '',
  elderAge: ''
})

const form = reactive({
  assessDate: '',
  height: undefined as number | undefined,
  weight: undefined as number | undefined,
  bmi: undefined as number | undefined,
  // 初筛分数（6项，每项0-3分）
  initialScores: [undefined, undefined, undefined, undefined, undefined, undefined] as (number | undefined)[],
  // 评估分数（11项）
  assessScores: [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined] as (number | undefined)[],
  // 测量分数（2项：18.蔬菜水果, 19.小腿围）
  measureScores: [undefined, undefined] as (number | undefined)[],
  // 腰围分数（0:男>90cm, 1:男≤90cm, 2:女>80cm, 3:女≤80cm）
  waistScore: undefined as number | undefined,
  // 测量值
  calfCircumference: undefined as number | undefined,
  waistCircumference: undefined as number | undefined,
  // 分数汇总
  initialScore: 0,
  assessScore: 0,
  measureScore: 0,
  ageAdjust: 0,
  totalScore: 0,
  resultLevel: '',
  assessor: ''
})

const calculateBMI = () => {
  if (form.height && form.weight) {
    form.bmi = form.weight / (form.height * form.height)
    // 根据BMI自动计算第1题分数
    if (form.bmi < 19 || form.bmi >= 28) {
      form.initialScores[0] = 0
    } else if ((form.bmi >= 19 && form.bmi < 21) || (form.bmi >= 26 && form.bmi < 28)) {
      form.initialScores[0] = 1
    } else if ((form.bmi >= 21 && form.bmi < 23) || (form.bmi >= 24 && form.bmi < 26)) {
      form.initialScores[0] = 2
    } else if (form.bmi >= 23 && form.bmi <= 24) {
      form.initialScores[0] = 3
    }
    calculateScores()
  }
}

const calculateScores = () => {
  // 计算初筛分数（满分14分）
  form.initialScore = form.initialScores.reduce((sum, score) => sum + (score || 0), 0)

  // 计算评估分数（满分15分）- 11项
  form.assessScore = form.assessScores.reduce((sum, score) => sum + (score || 0), 0)

  // 计算测量分数（满分3分：18题1分 + 19题1分 + 20题1分）
  let measureScore = form.measureScores.reduce((sum, score) => sum + (score || 0), 0)
  // 第20题腰围分数（0或1分）
  if (form.waistScore !== undefined) {
    // 0:男>90cm(0分), 1:男≤90cm(1分), 2:女>80cm(0分), 3:女≤80cm(1分)
    measureScore += (form.waistScore === 1 || form.waistScore === 3) ? 1 : 0
  }
  form.measureScore = measureScore

  // 年龄调整（≥70岁加1分）
  const age = parseInt(dataForm.elderAge) || 0
  form.ageAdjust = age >= 70 ? 1 : 0

  // 计算总分
  form.totalScore = form.initialScore + form.assessScore + form.measureScore + form.ageAdjust

  // 判断结果等级
  if (form.initialScore >= 12) {
    // 初筛通过，无营养不良风险
    form.resultLevel = 'good'
  } else {
    // 初筛未通过，根据总分判断（结果等级仅由总分决定，不受BMI/腰围影响）
    if (form.totalScore >= 24) {
      form.resultLevel = 'good' // 营养状况良好
    } else if (form.totalScore > 17 && form.totalScore < 24) {
      form.resultLevel = 'at_risk' // 有营养不良风险
    } else {
      form.resultLevel = 'malnutrition' // 有营养不良
    }
  }
}

// 腰围选择变化处理（男女互斥）
const onWaistChange = () => {
  calculateScores()
}

const getResultTagType = (level: string) => {
  const typeMap: Record<string, string> = {
    'good': 'success',
    'at_risk': 'warning',
    'malnutrition': 'danger'
  }
  return typeMap[level] || 'info'
}

const getResultText = (level: string) => {
  const textMap: Record<string, string> = {
    'good': '营养状况良好',
    'at_risk': '有营养不良风险',
    'malnutrition': '有营养不良'
  }
  return textMap[level] || level
}

const resetForm = () => {
  dataForm.id = undefined
  dataForm.elderId = undefined
  dataForm.elderName = ''
  dataForm.elderSex = ''
  dataForm.elderAge = ''

  form.assessDate = ''
  form.height = undefined
  form.weight = undefined
  form.bmi = undefined
  form.initialScores = [undefined, undefined, undefined, undefined, undefined, undefined]
  form.assessScores = [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]
  form.measureScores = [undefined, undefined]
  form.waistScore = undefined
  form.calfCircumference = undefined
  form.waistCircumference = undefined
  form.initialScore = 0
  form.assessScore = 0
  form.measureScore = 0
  form.ageAdjust = 0
  form.totalScore = 0
  form.resultLevel = ''
  form.assessor = ''
}

const elderUp = (e: any) => {
  dataForm.elderName = e.elderName
  dataForm.elderId = e.id
  dataForm.elderSex = e.elderSex === 1 ? '男' : '女'
  dataForm.bedName = e.bedName || ''
  dataForm.elderAge = e.elderAge
  // 年龄变化时重新计算
  calculateScores()
}

const open = async (id?: number) => {
  resetForm()
  title.value = '新增营养风险评估'
  isDetail.value = false
  dialogVisible.value = true
  dataForm.tenantId = getTenantId()
  await nextTick()
  selectElderRef.value?.reset()
}

const openEdit = async (row: any, id: number) => {
  resetForm()
  title.value = '编辑营养风险评估'
  isDetail.value = false
  dialogVisible.value = true
  await nextTick()
  await loadData(row, id)
}

const openDetail = async (row: any, id: number) => {
  resetForm()
  title.value = '营养风险评估详情'
  isDetail.value = true
  dialogVisible.value = true
  await nextTick()
  await loadData(row, id)
}

const loadData = async (row: any, id: number) => {
  try {
    const res = await nutritionalRiskGetById(id)
    if (res) {
      Object.assign(dataForm, {
        id: res.id,
        elderId: res.elderId,
        elderName: res.elderName,
        elderSex: res.elderSex,
        elderAge: res.elderAge
      })

      // 解析assessData
      if (res.assessData) {
        const assessData = JSON.parse(res.assessData)
        Object.assign(form, assessData)
        // 从assessData中解析分数（优先使用assessData中的值）
        form.initialScore = assessData.initialScore ?? res.initialScore ?? 0
        form.assessScore = assessData.assessScore ?? res.assessScore ?? 0
        form.measureScore = assessData.measureScore ?? res.measureScore ?? 0
        form.totalScore = assessData.totalScore ?? res.totalScore ?? 0
      }

      form.assessor = res.assessor || ''
      form.assessDate = res.assessDate || ''
      form.ageAdjust = res.ageAdjust || 0
      form.resultLevel = res.riskLevel || ''
      dataForm.tenantId = res.tenantId || ''

      await selectElderRef.value.upData(res.elderName, res.elderId)
    }
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

const submitForm = async () => {
  if (!dataForm.elderId) {
    message.error('请选择长者')
    return
  }

  const assessData = {
    assessDate: form.assessDate,
    height: form.height,
    weight: form.weight,
    bmi: form.bmi,
    tenantId: dataForm.tenantId,
    initialScores: form.initialScores,
    assessScores: form.assessScores,
    measureScores: form.measureScores,
    waistScore: form.waistScore,
    calfCircumference: form.calfCircumference,
    waistCircumference: form.waistCircumference,
    initialScore: form.initialScore,
    assessScore: form.assessScore,
    measureScore: form.measureScore,
    ageAdjust: form.ageAdjust,
    totalScore: form.totalScore,
    riskLevel: form.resultLevel
  }

  const submitData: NutritionalRiskFormData = {
    id: dataForm.id,
    elderId: dataForm.elderId,
    tenantId: dataForm.tenantId,
    assessData: JSON.stringify(assessData),
    assessor: form.assessor,
    riskLevel: form.resultLevel,
    assessScore: form.totalScore,
    assessDate: form.assessDate
  }

  try {
    if (dataForm.id) {
      await nutritionalRiskUpdate(submitData)
      message.success('更新成功')
    } else {
      await nutritionalRiskCreate(submitData)
      message.success('创建成功')
    }
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('提交失败:', error)
    message.error('提交失败')
  }
}

const handleClosed = () => {
  dialogVisible.value = false
}

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

  // 初筛项目数据
  const initialItems = [
    { name: '1. 近三个月有无饮食量变化', options: [{ score: 0, text: '严重增加或减少' }, { score: 1, text: '增加或减少' }, { score: 2, text: '无变化' }, { score: null, text: '—' }] },
    { name: '2. 近3个月体重变化', options: [{ score: 0, text: '减少或增加≥3Kg' }, { score: 1, text: '不知道' }, { score: 2, text: '1Kg≤减少<3Kg 或 1Kg≤增加<3Kg' }, { score: 3, text: '0Kg<减少<1Kg 或 0Kg<增加<1Kg' }] },
    { name: '3. 活动能力', options: [{ score: 0, text: '卧床' }, { score: 1, text: '需要依赖工具活动' }, { score: 2, text: '独立户外活动' }, { score: null, text: '—' }] },
    { name: '4. 牙齿状况', options: [{ score: 0, text: '全口或半口缺' }, { score: 1, text: '用义齿' }, { score: 2, text: '正常' }, { score: null, text: '—' }] },
    { name: '5. 神经精神疾病', options: [{ score: 0, text: '严重认知障碍或抑郁' }, { score: 1, text: '轻度认知障碍或抑郁' }, { score: 2, text: '无认知障碍或抑郁' }, { score: null, text: '—' }] },
    { name: '6. BMI', options: [{ score: 0, text: 'BMI<19 或 BMI≥28' }, { score: 1, text: '19≤BMI<21 或 26≤BMI<28' }, { score: 2, text: '21≤BMI<23 或 24≤BMI<26' }, { score: 3, text: '23≤BMI≤24' }] }
  ]

  // 评估项目数据
  const assessItems = [
    { name: '7. 患慢性病数>3种', options: [{ score: 0, text: '是' }, { score: null, text: '—' }, { score: 1, text: '否' }, { score: null, text: '—' }] },
    { name: '8. 服药时间在一个月以上的药物种类>3种', options: [{ score: 0, text: '是' }, { score: null, text: '—' }, { score: 1, text: '否' }, { score: null, text: '—' }] },
    { name: '9. 是否独居', options: [{ score: 0, text: '是' }, { score: null, text: '—' }, { score: 1, text: '否' }, { score: null, text: '—' }] },
    { name: '10. 睡眠时间', options: [{ score: 0, text: '<5h/d' }, { score: null, text: '—' }, { score: 1, text: '≥5h/d' }, { score: null, text: '—' }] },
    { name: '11. 户外独立活动时间', options: [{ score: 0, text: '<1h/d' }, { score: null, text: '—' }, { score: 1, text: '≥1h/d' }, { score: null, text: '—' }] },
    { name: '12. 文化程度', options: [{ score: 0, text: '小学及以下' }, { score: null, text: '—' }, { score: 1, text: '中学及以上' }, { score: null, text: '—' }] },
    { name: '13. 自我感觉经济状况', options: [{ score: 0, text: '差' }, { score: 0.5, text: '一般' }, { score: 1, text: '良好' }, { score: null, text: '—' }] },
    { name: '14. 进食能力', options: [{ score: 0, text: '依靠别人' }, { score: null, text: '—' }, { score: 1, text: '自行进食稍有困难' }, { score: 2, text: '自行进食' }] },
    { name: '15. 一天餐次', options: [{ score: 0, text: '1次' }, { score: null, text: '—' }, { score: 1, text: '2次' }, { score: 2, text: '3次及以上' }] },
    { name: '16. 每天摄入奶类/豆制品/鱼肉类', options: [{ score: 0, text: '0-1项' }, { score: 0.5, text: '2项' }, { score: 1, text: '3项' }, { score: null, text: '—' }] },
    { name: '17. 每天烹调油摄入量', options: [{ score: 0, text: '≥25g' }, { score: null, text: '—' }, { score: 1, text: '<25g' }, { score: null, text: '—' }] },
    { name: '18. 是否每天吃蔬菜水果500g及以上', options: [{ score: 0, text: '否' }, { score: null, text: '—' }, { score: 1, text: '是' }, { score: null, text: '—' }] },
    { name: '19. 小腿围', options: [{ score: 0, text: '<31cm' }, { score: null, text: '—' }, { score: 1, text: '≥31cm' }, { score: null, text: '—' }] },
    { name: '20. 腰围', options: [{ score: '男>90cm/女>80cm', text: '0分' }, { score: null, text: '—' }, { score: '男≤90cm/女≤80cm', text: '1分' }, { score: null, text: '—' }] }
  ]

  // 构建打印内容
  const tenantName = userStore.getTenantName || '' // 当前登录的机构名称
  const printContent =`
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>营养风险评估表 - ${dataForm.elderName || ''}</title>
      <style>
        @media print {
          @page { size: A4 portrait; margin: 15mm; }
        }
        body {
          font-family: 'SimSun', 'Microsoft YaHei', serif;
          font-size: 8pt;
          line-height: 1.2;
          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: 60px;
          padding: 0 5px;
          text-align: center;
        }

        .subsection-title {
          font-size: 11pt;
          font-weight: bold;
          margin: 15px 0 10px 0;
          padding: 5px 10px;
          background: #e8e8e8;
          border-left: 4px solid #409eff;
        }

        .assessment-table {
          width: 100%;
          border-collapse: collapse;
          margin-bottom: 15px;
          font-size: 7.5pt;
        }
        .assessment-table th, .assessment-table td {
          border: 1px solid #333;
          padding: 4px;
          text-align: center;
          vertical-align: middle;
        }
        .assessment-table th {
          background: #e8e8e8;
          font-weight: bold;
        }
        .assessment-table .col-item {
          width: 20%;
          font-weight: bold;
          background: #f5f5f5;
          text-align: left;
        }
        .assessment-table .col-score {
          width: 20%;
        }

        .initial-tip {
          margin: 10px 0;
          padding: 10px;
          border: 1px solid #999;
          background: #fff3cd;
          font-size: 9pt;
        }
        .score-value {
          color: #d9534f;
          font-weight: bold;
          font-size: 12pt;
        }

        .score-summary {
          margin: 15px 0;
          padding: 10px;
          border: 1px solid #999;
          background: #fafafa;
        }
        .summary-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 5px;
        }
        .summary-item .label {
          font-weight: bold;
        }
        .summary-item .value {
          font-weight: bold;
        }
        .summary-item .value.total {
          color: #d9534f;
          font-size: 14pt;
        }

        .scoring-standard {
          margin: 15px 0;
          padding: 10px;
          border: 1px solid #999;
          background: #fafafa;
        }
        .standard-title {
          font-weight: bold;
          margin-bottom: 8px;
        }
        .standard-content {
          font-size: 8pt;
          line-height: 1.5;
        }
        .standard-content p {
          margin: 3px 0;
        }
        .current-result {
          margin-top: 10px;
          padding-top: 10px;
          border-top: 1px solid #ccc;
        }
        .result-label {
          font-weight: bold;
          margin-right: 10px;
        }

        .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="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.elderName || ''}</span>
          </div>
          <div class="info-item">
            <span class="label">性别：</span>
            <span class="value">${dataForm.elderSex || ''}</span>
          </div>
          <div class="info-item">
            <span class="label">年龄：</span>
            <span class="value">${dataForm.elderAge || ''}</span>
          </div>
          <div class="info-item">
            <span class="label">床位号：</span>
            <span class="value">${dataForm.bedName || ''}</span>
          </div>
          <div class="info-item">
            <span class="label">评估日期：</span>
            <span class="value">${form.assessDate || ''}</span>
          </div>
          <div class="info-item">
            <span class="label">身高：</span>
            <span class="value">${form.height || ''} m</span>
          </div>
          <div class="info-item">
            <span class="label">体重：</span>
            <span class="value">${form.weight || ''} Kg</span>
          </div>
          <div class="info-item">
            <span class="label">BMI：</span>
            <span class="value">${form.bmi ? form.bmi.toFixed(1) : ''}</span>
          </div>
        </div>
      </div>

      <!-- 初筛部分 -->
      <div class="subsection-title">初筛（满分14分）</div>
      <table class="assessment-table">
        <thead>
          <tr>
            <th class="col-item">项目</th>
            <th class="col-score">0分</th>
            <th class="col-score">1分</th>
            <th class="col-score">2分</th>
            <th class="col-score">3分</th>
          </tr>
        </thead>
        <tbody>
          ${initialItems.map((item, index) => `
            <tr>
              <td class="col-item">${item.name}</td>
              ${item.options.map(opt => `
                <td class="col-score">${form.initialScores[index] === opt.score ? '☑' : '☐'} ${opt.text}</td>
              `).join('')}
            </tr>
          `).join('')}
        </tbody>
      </table>

      <div class="initial-tip">
        <p>总分14分，<12分提示有营养不良风险，继续以下评估；≥12分提示无营养不良风险，无需以下评估。</p>
        <p>初筛分数（小计满分14分）：<span class="score-value">${form.initialScore}</span> 分</p>
      </div>

      <!-- 评估部分 -->
      <div class="subsection-title">评估（满分16分）</div>
      <table class="assessment-table">
        <thead>
          <tr>
            <th class="col-item">项目</th>
            <th class="col-score">0分</th>
            <th class="col-score">0.5分</th>
            <th class="col-score">1分</th>
            <th class="col-score">2分</th>
          </tr>
        </thead>
        <tbody>
          ${assessItems.map((item, index) => `
            <tr>
              <td class="col-item">${item.name}</td>
              ${item.options.map((opt, optIndex) => {
                let isSelected = false
                if (index < 11) {
                  isSelected = form.assessScores[index] === opt.score
                } else if (index === 11) {
                  isSelected = form.measureScores[0] === opt.score
                } else if (index === 12) {
                  isSelected = form.measureScores[1] === opt.score
                } else if (index === 13) {
                  // 腰围特殊处理
                  if (optIndex === 0) isSelected = form.waistScore === 0 || form.waistScore === 2
                  if (optIndex === 2) isSelected = form.waistScore === 1 || form.waistScore === 3
                }
                return `<td class="col-score">${isSelected ? '☑' : '☐'} ${opt.text}</td>`
              }).join('')}
            </tr>
          `).join('')}
        </tbody>
      </table>

      <!-- 测量值 -->
      <div class="info-section">
        <div class="info-row">
          <div class="info-item">
            <span class="label">小腿围：</span>
            <span class="value">${form.calfCircumference || ''} cm</span>
          </div>
          <div class="info-item">
            <span class="label">腰围：</span>
            <span class="value">${form.waistCircumference || ''} cm</span>
          </div>
        </div>
      </div>

      <!-- 分数汇总 -->
      <div class="score-summary">
        <div class="summary-item">
          <span class="label">初筛分数（小计满分14分）：</span>
          <span class="value">${form.initialScore} 分</span>
        </div>
        <div class="summary-item">
          <span class="label">评估分数（小计满分16分）：</span>
          <span class="value">${form.assessScore + form.measureScore} 分</span>
        </div>
        <div class="summary-item">
          <span class="label">年龄调整（≥70岁加1分）：</span>
          <span class="value">${form.ageAdjust} 分</span>
        </div>
        <div class="summary-item">
          <span class="label">量表总分（满分30分）：</span>
          <span class="value total">${form.totalScore} 分</span>
        </div>
      </div>

      <!-- 评分标准 -->
      <div class="scoring-standard">
        <div class="standard-title">评分标准：</div>
        <div class="standard-content">
          <p>若初筛总分≥12分提示无营养不良风险，无需评估；</p>
          <p>若初筛总分<12分提示有营养不良风险，继续评估；</p>
          <p>若营养不良风险评估总分（初筛+评估）≥24分，表示营养状况良好；</p>
          <p>若营养不良风险评估总分（初筛+评估）17分～24分（不含24分），表示有营养不良风险；</p>
          <p>若营养不良风险评估总分（初筛+评估）≤17分，表示有营养不良。</p>
        </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' }]
}

defineExpose({
  open,
  openEdit,
  openDetail
})
</script>

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

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

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

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

    .section-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 15px;
      color: #333;
      text-align: center;
      border-bottom: 2px solid #409eff;
      padding-bottom: 10px;
    }

    .subsection-title {
      font-size: 16px;
      font-weight: bold;
      margin: 20px 0 10px 0;
      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;
        }

        .col-item {
          width: 20%;
        }

        .col-score-0,
        .col-score-05,
        .col-score-1,
        .col-score-2,
        .col-score-3 {
          width: 20%;
        }
      }

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

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

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

          .col-item {
            padding-left: 30px;
            text-align: left;
            font-weight: bold;
            vertical-align: middle;
          }

          .col-score {
            padding-left: 30px;
            text-align: left;
            vertical-align: middle;

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

            .waist-row {
              margin-bottom: 5px;

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

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

    .initial-tip {
      margin: 15px 0;
      padding: 15px;
      background-color: #f5f7fa;
      border-radius: 4px;

      p {
        margin: 5px 0;
      }

      .score-display {
        font-weight: bold;
      }

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

    .measure-inputs {
      margin: 15px 0;
      padding: 15px;
      background-color: #f5f7fa;
      border-radius: 4px;
    }

    .age-adjust {
      margin: 15px 0;
      padding: 15px;
      background-color: #f5f7fa;
      border-radius: 4px;

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

    .score-summary {
      margin: 20px 0;
      padding: 20px;
      background-color: #f5f7fa;
      border-radius: 4px;
      border: 2px solid #409eff;

      .summary-item {
        margin: 10px 0;
        font-size: 16px;

        .label {
          font-weight: bold;
        }

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

          &.total {
            color: #f56c6c;
            font-size: 20px;
          }
        }
      }
    }

    .scoring-standard {
      margin: 20px 0;
      padding: 20px;
      background-color: #f5f7fa;
      border-radius: 4px;

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

      .standard-content {
        p {
          margin: 5px 0;
          line-height: 1.6;
        }
      }

      .current-result {
        margin-top: 15px;
        padding-top: 15px;
        border-top: 1px solid #e4e7ed;

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