<template>
  <div id="check-window" style="width:100%;">
    <el-row class="tac" :gutter="10">
      <el-col :span="4">
        <el-menu
          default-active="1"
          class="el-menu-vertical-demo"
          style="height: 200px">
          <el-submenu :index="`year`" v-for="year in Object.keys(timeGroup)">
            <template slot="title">{{ year }}年</template>
            <el-submenu
              :index="`${year}-${month}`"
              v-for="month in Object.keys(timeGroup[year])">
              <template slot="title">{{ month }}月</template>
              <el-submenu
                :index="`${year}-${month}-${day}`"
                v-for="day in Object.keys(timeGroup[year][month])">
                <template slot="title">{{ day }}日</template>
                <el-menu-item
                  :index="`${year}-${month}-${day}-${obrIdAndTime.time}`"
                  v-for="obrIdAndTime in timeGroup[year][month][day]"
                  @click="current.obrId = obrIdAndTime.obrId">
                  {{ obrIdAndTime.time }}
                </el-menu-item>
              </el-submenu>
            </el-submenu>
          </el-submenu>
        </el-menu>
      </el-col>

      <el-col :span="20" style="overflow-y: scroll">
        <el-descriptions
          class="margin-top"
          title="详细检测报告"
          :column="3"
          border>
          <el-descriptions-item
            v-for="item in fillReportItem(reportItemLabelList)"
            :key="item.key"
            :label="item.label">
            <span v-if="current.obr[item.key] && item.key !== 'signs'">{{
              current.obr[item.key]
            }}</span>
            <span v-else-if="item.key === 'signs'">{{
              mapSigns(current.obr[item.key])
            }}</span>
            <span v-else>{{ '' }}</span>
          </el-descriptions-item>
        </el-descriptions>

        <div id="patient-check-projects-table">
          <el-table width="100%" stripe :data="current.obxList">
            <el-table-column
              label="医技观察项目"
              align="center"
              prop="mecTechObsProject"></el-table-column>
            <el-table-column
              label="医技项目名称"
              align="center"
              prop="mecTechObsName"></el-table-column>
            <el-table-column
              label="观察值"
              align="center"
              prop="obsProjectDetail"></el-table-column>
            <el-table-column
              label="项目结果信息"
              align="center"
              prop="projectInfo"></el-table-column>
            <el-table-column
              label="单位代码"
              align="center"
              prop="unitCode"></el-table-column>
            <el-table-column
              label="单位名称"
              align="center"
              prop="result"></el-table-column>
            <el-table-column
              label="参值范围"
              align="center"
              prop="result"></el-table-column>
            <el-table-column
              label="高低标志"
              align="center"
              prop="sign"></el-table-column>
            <el-table-column
              label="微生物观察分类"
              align="center"
              prop="obsClassification"></el-table-column>
            <el-table-column
              label="检验方法"
              align="center"
              prop="testMethod"></el-table-column>
          </el-table>
          <el-pagination
            :page-count.sync="obxPaginationParams.pageNum"
            :total="obxPaginationParams.total"
            :page-size="obxPaginationParams.pageSize" @current-change="handleCurrentPageChange">
          </el-pagination>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import service from '@/utils/request'

export default {
  name: 'checkWindow',
  props: {
    param: {
      type: Object,
      default: () => {
        return { id: '' }
      },
    },
  },
  data() {
    return {
      current: {
        obrId: '',
        obrAllList: [],
        obr: {},
        obxAllList: [],
        obxList: [],
      },
      timeGroup: {},
      reportItemLabelList: [
        // { key: 'reportNo', label: '报告单号' },
        // { key: "medTechProCode", label: "医技号" },
        { key: 'medTechProName', label: '医技项目名称' },
        // { key: 'reportClass', label: '报告单类别名称' },
        { key: 'reportCompleteTime', label: '报告完成时间' },
        { key: 'signs', label: '危机标志' },
        { key: 'sampleReceivedDate', label: '样本收到日期' },
        { key: 'checkpoint', label: '检查部位或样本' },
        { key: 'executeDepartmentName', label: '执行科室名称' },
        // { key: "applyDoctorName", label: "申请医生" },
        // { key: "testingDoctorName", label: "检验医生信息名称" },
        { key: 'reviewDoctorName', label: '审核医生' },
        { key: 'reportDate', label: '报告单日期' },
      ],
      obxPaginationParams:{
        pageNum: 1, //当前页数
        pageSize: 5, //每页数据数量
        total: 0 //总共数据量
      },
      testPatId: 24502 //测试用的patId  测试值：24502, 24503, 24504, 24656
    }
  },
  watch: {
    'current.obrId'(newValue) {
      this.current.obr = this.current.obrAllList.find(
        (item) => item.id === newValue
      )
      this.current.obxList = this.current.obxAllList.filter(
        (item) => item.obrId === newValue
      )
    },
    'current.obxList'(newValue) {
      // 将obxList每个obx对象的sign替换成对应意义
      if(newValue) {
      // console.log(newValue)

      const rs = newValue.map(item => {
        if(item) {
        console.log(item)

        item.sign = this.mapHighSign(item.sign)
        }
      })
        console.log(rs)
      }
    }
  },
  methods: {
    // 获取当前患者的所有检查项目，同时生成菜单栏需要的时间数据
    getObrAllListAndGenerateTime() {
      // this.testPatId要改为this.$props.param.id
      // this.$props.param.id = this.testPatId //后续数据库更新后需要把这行代码注释掉
      service({
        url: `/work/request/patid/${this.$props.param.id}`,
      }).then((response) => {
        this.current.obrAllList = response.rows
        // 得到obrAllList的数据后接着生成timeGroup
        this.handleObrList(response.rows)
      })
    },
    // 获取所有检查项目的所有检测结果，通过检测项目标识obrId来取出对应检测结果，默认获取第一页的数据
    getObxAllList() {
      // this.testPatId要改为this.$props.param.id
      // this.$props.param.id = this.testPatId //后续数据库更新后需要把这行代码注释掉
      service({
        url: `/work/result/patid/${this.$props.param.id}`,
        params: {
          ...this.obxPaginationParams
        }
      }).then((response) => {
        this.current.obxAllList = response.rows
        this.obxPaginationParams.total = response.total
              if(this.current.obrId!=='') {

         this.current.obxList = this.current.obxAllList.filter(item => item.obrId === this.current.obrId)
        }
      })
    },
    // 分页组件页面变化时请求对应页的检测结果
    handleCurrentPageChange(newPage) {
      this.obxPaginationParams.pageNum = newPage
      this.getObxAllList()

    },
    fillReportItem(reportItemLabelList) {
      const filledList = [...reportItemLabelList]

      const remainder = filledList.length % 3
      if (remainder !== 0) {
        const num = 3 - remainder

        for (let i = num; i > 0; i--) {
          filledList.push({ key: ``, label: '' })
        }
      }
      return filledList
    },
    /**
     * 映射危机标志的对应含义
     * @param {string} signs 危机标志数值
     * @return {string} 危机标志对应含义
     */
    mapSigns(signs) {
      switch (signs) {
        case '0':
          return '正常'
        case '1':
          return '危机'
        default:
          return ''
      }
    },
    /**
     * 映射高低标志的对应含义
     * @param {string} sign 高低标志
     * @return {string} 高低标志对应含义
     */
    mapHighSign(sign) {
      switch (sign) {
        case '0':
          return '正常'
        case '1':
          return '偏低'
        case '2':
          return '偏高'
        default:
          return ''
      }
    },
    /**
     * 处理字符串日期
     * @param {string} dateString 字符串日期
     * @example
     * ```
     * dateString取值2024-07-23 12:28:42时，
     * 函数将返回{year: '2024', month: '07', day: '23', time: '12:28:42'}
     * ```
     * @return {{year: string, month: string, day: string, time: string}}
     */
    handleDate(dateString) {
      //先把年月日和当天时间分离 2024-07-23 12:28:42->['2024-07-23','12:28:42']
      const [yearMonthDay, time] = dateString.split(' ')

      //接着把年月日分离 '2024-07-23'->['2024','07','23']
      const [year, month, day] = yearMonthDay.split('-')

      return { year, month, day, time }
    },
    /**
     * 处理日期数组
     * @param {{obrId:string,reportCompleteTime:{year: string, month: string, day: string, time: string}}[]} orcIdAndTimeList
     * @return {Record<string,Record<string,Record<string,string[]>>>}
     * @example
     * ```
     * dates取值[
      {obrId:'223',reportCompleteTime:{ year: '2024', month: '07', day: '23', time: '18:23:23' }},
      {obrId:'223',reportCompleteTime:{ year: '2024', month: '07', day: '23', time: '20:23:23' }},
      {obrId:'223',reportCompleteTime:{ year: '2024', month: '08', day: '24', time: '12:23:23' }},
      {obrId:'223',reportCompleteTime:{ year: '2023', month: '04', day: '08', time: '14:23:23' }}
    ],
      函数返回
    {
      '2023': { '04': { '08': [{orcId: '233',time:'14:23:23'}] } },
      '2024': {
         '07': { '23': [{orcId: '233',time: '18:23:23'},{orcId: '233',time: '20:23:23'}] },
         '08': { '24': [{orcId: '233',time: '12:23:23'}]  }
      }
     * ```
     */
    organizeDates(orcIdAndTimeList) {
      const result = {}
      orcIdAndTimeList.forEach((item) => {
        const { year, month, day, time } = item.reportCompleteTime
        if (!result[year]) {
          result[year] = {}
        }
        if (!result[year][month]) {
          result[year][month] = {}
        }
        if (!result[year][month][day]) {
          result[year][month][day] = []
        }
        result[year][month][day].push({ obrId: item.obrId, time: time })
      })
      return result
    },
    /**
     * 处理current.obrAllList
     * @param {Array} obrAllList
     */
    handleObrList(obrAllList) {
      // 从current.obrAllList获取对象{obrId: '',reportCompleteTime: {year, month, day, time}}数组
      const orcIdAndTimeList = obrAllList.map((item) => {

        const handledDate = this.handleDate(item.reportCompleteTime)
        return { obrId: item.id, reportCompleteTime: handledDate }
      })


      this.timeGroup = this.organizeDates(orcIdAndTimeList)
    },
  },
  // 当弹窗组件创建时请求当前患者所有检查项目信息
  created() {
    this.getObrAllListAndGenerateTime()
    this.getObxAllList()
  },
}
</script>

<style scoped>
#patient-check-projects-table {
  min-height: 300px;
  margin-top: 5vh;
}
</style>
