<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="80px"
    >
      <el-form-item label="长者姓名" prop="elderName">
        <el-input
          v-model="queryParams.elderName"
          placeholder="请输入长者姓名"
          class="!w-240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

<!--      <el-form-item label="评估年份">-->
<!--        <el-date-picker-->
<!--          size="default"-->
<!--          ref="selectRef"-->
<!--          class="!w-240px"-->
<!--          v-model="queryParams.recordMonthRange"-->
<!--          type="year"-->
<!--          :clearable="true"-->
<!--          :editable="false"-->
<!--          placeholder="选择记录年份"-->
<!--          value-format="YYYY"-->
<!--          format="YYYY"-->
<!--          date-format="YYYY"-->
<!--        />-->
<!--      </el-form-item>-->

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <TabBarBtn>
      <template #next>
        <el-button type="primary" @click="handleAdd">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
         <el-button type="success" @click="handleExport">
          <Icon icon="ep:upload" class="mr-5px" /> 导出
        </el-button>
      </template>
    </TabBarBtn>

    <el-table v-loading="loading" :data="list" stripe>
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="长者姓名" prop="elderName" width="110" align="center"/>
      <el-table-column label="性别" prop="elderSex" width="80" align="center">
        <template #default="{ row }">
          {{ getDictLabel(DICT_TYPE.SYSTEM_USER_SEX, row.elderSex) }}
        </template>
      </el-table-column>
      <el-table-column label="年龄" prop="elderAge" width="80" align="center"/>

      <el-table-column label="床号" prop="bedName" width="200" align="center"/>
      <el-table-column label="合同号" prop="contractNumber" width="150" align="center"/>
      <el-table-column label="护理级别" prop="nurseLevelName" width="150" align="center"/>

      <el-table-column label="防噎食评估" prop="asphyxiationRisk" width="130" align="center" >
        <template #default="{ row }">
          <el-tag :type="getRiskType(row.riskData?.asphyxiation?.level)" :class="{ 'cursor-pointer': row.riskData?.asphyxiation?.id }" @click="row.riskData?.asphyxiation?.id && handleOpenAsphyxiation(row.riskData?.asphyxiation)">{{ getRiskLevelText(row.riskData?.asphyxiation?.level || '-') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="防压疮评估" prop="pressureUlcerRisk" width="130" align="center" >
        <template #default="{ row }">
          <el-tag :type="getRiskType(row.riskData?.pressureUlcer?.level)" :class="{ 'cursor-pointer': row.riskData?.pressureUlcer?.id }" @click="row.riskData?.pressureUlcer?.id && handleOpenPressureUlcer(row.riskData?.pressureUlcer)">{{ getRiskLevelText(row.riskData?.pressureUlcer?.level || '-') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="防跌倒评估" prop="fallRisk" width="130" align="center" >
        <template #default="{ row }">
          <el-tag :type="getRiskType(row.riskData?.fall?.level)" :class="{ 'cursor-pointer': row.riskData?.fall?.id }" @click="row.riskData?.fall?.id && handleOpenFall(row.riskData?.fall)">{{ getRiskLevelText(row.riskData?.fall?.level || '-') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="防坠床评估" prop="bedFallRisk" width="130" align="center" >
        <template #default="{ row }">
          <el-tag :type="getRiskType(row.riskData?.bedFall?.level)" :class="{ 'cursor-pointer': row.riskData?.bedFall?.id }" @click="row.riskData?.bedFall?.id && handleOpenBedFall(row.riskData?.bedFall)">{{ getRiskLevelText(row.riskData?.bedFall?.level || '-') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="防烫伤评估" prop="scaldRisk" width="130" align="center" >
        <template #default="{ row }">
          <el-tag :type="getRiskType(row.riskData?.scald?.level)" :class="{ 'cursor-pointer': row.riskData?.scald?.id }" @click="row.riskData?.scald?.id && handleOpenScald(row.riskData?.scald)">{{ getRiskLevelText(row.riskData?.scald?.level || '-') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="防走失评估" prop="wanderingRisk" width="130" align="center" >
        <template #default="{ row }">
          <el-tag :type="getRiskType(row.riskData?.wandering?.level)" :class="{ 'cursor-pointer': row.riskData?.wandering?.id }" @click="row.riskData?.wandering?.id && handleOpenWandering(row.riskData?.wandering)">{{ getRiskLevelText(row.riskData?.wandering?.level || '-') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="防自伤他伤评估" prop="suicideRisk" width="130" align="center" >
        <template #default="{ row }">
          <el-tag :type="getRiskType(row.riskData?.selfHarm?.level)" :class="{ 'cursor-pointer': row.riskData?.selfHarm?.id }" @click="row.riskData?.selfHarm?.id && handleOpenSuicide(row.riskData?.selfHarm)">{{ getRiskLevelText(row.riskData?.selfHarm?.level || '-') }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="防食品药品误食评估" prop="perceptionRisk" width="152" align="center" >
        <template #default="{ row }">
          <el-tag :type="getRiskType(row.riskData?.foodDrug?.level)" :class="{ 'cursor-pointer': row.riskData?.foodDrug?.id }" @click="row.riskData?.foodDrug?.id && handleOpenMental(row.riskData?.foodDrug)">{{ getRiskLevelText(row.riskData?.foodDrug?.level || '-') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="防文娱活动意外" prop="balanceRisk" width="130" align="center" >
        <template #default="{ row }">
          <el-tag :type="getRiskType(row.riskData?.entertainment?.level)" :class="{ 'cursor-pointer': row.riskData?.entertainment?.id }" @click="row.riskData?.entertainment?.id && handleOpenBalance(row.riskData?.entertainment)">{{ getRiskLevelText(row.riskData?.entertainment?.level || '-') }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="记录时间" prop="bedName" width="200" align="center">
        <template #default="{ row }">
          {{formatToDateTime(row.createTime)}}
        </template>
      </el-table-column>
      <el-table-column label="记录人" prop="creator" width="150" align="center"/>

     <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleEdit(scope.row, scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="warning"
            @click="handleView(scope.row,scope.row.id)"
          >
            详情
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 新增/编辑弹窗 -->
  <SafetyRiskNoticeForm ref="formRef" @success="getList" />
  
  <!-- 各项评估详情弹窗 -->
  <AsphyxiationForm ref="asphyxiationFormRef" />
  <PressureSoresForm ref="pressureSoresFormRef" />
  <FallDownForm ref="fallDownFormRef" />
  <FallPreventionForm ref="fallPreventionFormRef" />
  <EmpyrosisForm ref="empyrosisFormRef" />
  <WanderAwayForm ref="wanderAwayFormRef" />
  <CommitSuicideForm ref="commitSuicideFormRef" />
  <MMSEForm ref="mmseFormRef" />
  <AttackForm ref="attackFormRef" />
  <AntiEntertainmentForm ref="equilibriumFormRef" />
  <DailyLifeForm ref="dailyLifeFormRef" />
  <NutritionalRiskForm ref="nutritionalRiskFormRef" />


</template>

<script setup lang="ts">
import { DICT_TYPE, getDictLabel } from '@/utils/dict'
import {
  getSafetyRiskNoticePage,
  deleteSafetyRiskNotice
} from '@/api/elderly/apply/check-in'
import { formatTime } from '@/utils'
import SafetyRiskNoticeForm from './Form.vue'
import AsphyxiationForm from '@/views/elderly/apply/nine-precautions/asphyxiation-by-choking/AddForm.vue'
import PressureSoresForm from '@/views/elderly/apply/nine-precautions/pressure-sores/AddForm.vue'
import FallDownForm from '@/views/elderly/apply/nine-precautions/fall-down/AddForm.vue'
import FallPreventionForm from '@/views/elderly/apply/nine-precautions/fall-prevention-measures/AddForm.vue'
import EmpyrosisForm from '@/views/elderly/apply/nine-precautions/empyrosis/AddForm.vue'
import WanderAwayForm from '@/views/elderly/apply/nine-precautions/wander-away/AddForm.vue'
import CommitSuicideForm from '@/views/elderly/apply/nine-precautions/commit-suicide/AddForm.vue'
import MMSEForm from '@/views/elderly/apply/nine-precautions/MMSE/AddForm.vue'
import AttackForm from '@/views/elderly/apply/nine-precautions/attack/AddForm.vue'
import CommunicationForm from '@/views/elderly/apply/nine-precautions/communication/AddForm.vue'
import AntiEntertainmentForm from '@/views/elderly/apply/nine-precautions/anti-entertainment/AddForm.vue'
import DailyLifeForm from '@/views/elderly/apply/nine-precautions/daily-life/AddForm.vue'
import NutritionalRiskForm from '@/views/elderly/apply/nine-precautions/nutritional-risk/AddForm.vue'
import {useUserStore} from "@/store/modules/user";
import {formatToDateTime} from "@/utils/dateUtil";
const userStore = useUserStore()
defineOptions({ name: 'RiskDisclosureStatement' })

const message = useMessage()
const { t } = useI18n()

// 列表数据
const loading = ref(false)
const list = ref([])
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  elderName: undefined,
  floorName: undefined,
  tenantIds: userStore.orgTenantId
})
const queryFormRef = ref()

// 解析 riskData JSON 字符串
const parseRiskData = (row: any) => {
  if (!row.riskData) return {}
  try {
    return typeof row.riskData === 'string' ? JSON.parse(row.riskData) : row.riskData
  } catch (e) {
    return {}
  }
}

// 获取列表
const getList = async () => {
  loading.value = true
  try {
    const data = await getSafetyRiskNoticePage(queryParams)
    list.value = (data.list || []).map((item: any) => ({
      ...item,
      riskData: parseRiskData(item)
    }))
    total.value = data.total || 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 新增
const formRef = ref()
const handleAdd = () => {
   formRef.value?.open()


}

// 各项评估弹窗引用
const asphyxiationFormRef = ref()
const pressureSoresFormRef = ref()
const fallDownFormRef = ref()
const fallPreventionFormRef = ref()
const empyrosisFormRef = ref()
const wanderAwayFormRef = ref()
const commitSuicideFormRef = ref()
const mmseFormRef = ref()
const attackFormRef = ref()
const communicationFormRef = ref()
const equilibriumFormRef = ref()
const dailyLifeFormRef = ref()
const nutritionalRiskFormRef = ref()

// 各项评估点击处理方法
const handleOpenAsphyxiation = (row: any) => {
  asphyxiationFormRef.value?.open(queryParams.tenantIds[0], row.id, true)
}
const handleOpenPressureUlcer = (row: any) => {
  pressureSoresFormRef.value?.open(queryParams.tenantIds[0], row.id, true)
}
const handleOpenFall = (row: any) => {
  fallDownFormRef.value?.open(queryParams.tenantIds[0], row.id, true)
}
const handleOpenBedFall = (row: any) => {
  fallPreventionFormRef.value?.open(queryParams.tenantIds[0], row.id, true)
}
const handleOpenScald = (row: any) => {
  empyrosisFormRef.value?.open(queryParams.tenantIds[0], row.id, true)
}
const handleOpenWandering = (row: any) => {
  wanderAwayFormRef.value?.open(queryParams.tenantIds[0], row.id, true)
}
const handleOpenSuicide = (row: any) => {
  commitSuicideFormRef.value?.open(queryParams.tenantIds[0], row.id, true)
}
const handleOpenMental = (row: any) => {
  mmseFormRef.value?.open(queryParams.tenantIds[0], row.id, true)
}
const handleOpenAttack = (row: any) => {
  attackFormRef.value?.open(queryParams.tenantIds[0], row.id, true)
}
const handleOpenPerception = (row: any) => {
  communicationFormRef.value?.open(queryParams.tenantIds[0], row.id, true)
}
const handleOpenBalance = (row: any) => {
  equilibriumFormRef.value?.open(queryParams.tenantIds[0], row.id, true)
}
const handleOpenDailyLiving = (row: any) => {
  dailyLifeFormRef.value?.open(queryParams.tenantIds[0], row.id, true)
}
const handleOpenNutrition = (row: any) => {
  nutritionalRiskFormRef.value?.open(queryParams.tenantIds[0], row.id, true)
}


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

/**
 * 根据风险等级获取按钮类型（颜色）
 * @param riskLevel 风险等级：none(无风险)、low(低风险)、medium(中风险)、high(高风险)
 * @returns Element Plus 按钮类型：success(绿)、info(灰)、warning(黄)、danger(红)、primary(蓝)
 */
const getRiskType = (riskLevel: string): string => {
  if (!riskLevel) return 'info'
  const level = riskLevel.trim().toLowerCase()
  if (level === 'none') return 'success'
  if (level === 'low') return 'info'
  if (level === 'medium') return 'warning'
  if (level === 'high') return 'danger'
  return 'primary'
}

// 编辑
const handleEdit = (row: any) => {
  formRef.value?.open(row)
}

// 详情
const handleView = (row: any) => {
  formRef.value?.open(row, true)
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await message.confirm('确认删除该记录吗？')
    await deleteSafetyRiskNotice(row.id)
    message.success('删除成功')
    getList()
  } catch (e) {
    // 用户取消
  }
}

// 初始化
onMounted(() => {
  getList()
})
</script>



<style scoped lang="scss">
</style>
