<template>
  <div style="height: 10%;display: flex">
    <div>
      <el-date-picker v-model="dateRange"
                      style="width: 220px"
                      :clearable="false"
                      type="daterange"/>
      <br>
      <hr>
      <el-button @click="query" type="primary">查询</el-button>
      <el-button @click="appendCopy" type="success">复制 / 追加</el-button>
      <el-button @click="copyClick" type="success">确认复制</el-button>
      <br>
    </div>
    <div class="describe">
      <el-button v-if="isEmr" type="primary" @click="copyOutcome('病理结果')">
        病理结果
      </el-button>

      <el-button v-if="isEmr" type="primary" @click="copyOutcome('细菌培养结果')">
        细菌培养结果
      </el-button>

      <div class="pat-info">
        <div>
          <test-describe front="姓名"
                         :text="inspectionHeader?.ptnt_NAME"/>
        </div>
        <div>
          <test-describe front="性别"
                         :text="filterSex(inspectionHeader?.ptnt_SEX)"/>
        </div>
        <div>
          <test-describe front="年龄"
                         :text="inspectionHeader.ptnt_AGE + filterAgeUnit(inspectionHeader.ptnt_AGE_UNIT) "/>
        </div>
        <div>
          <test-describe front="住院号"
                         :text="inspectionHeader.ptnt_NO"/>
        </div>
        <div>
          <test-describe front="科室"
                         :text="inspectionHeader.dept_NAME"/>
        </div>
        <div>
          <test-describe front="床号"
                         :text="inspectionHeader.ptnt_BED_NO"/>
        </div>
        <div>
          <test-describe front="标本类型"
                         :text="inspectionHeader.smpl_NAME "/>
        </div>
        <div>
          <test-describe front="申请项目"
                         :text="inspectionHeader?.aply_CNTN"/>
        </div>
      </div>
      <div class="test-date">
        <div>
          <test-describe front="接收时间"
                         :text="inspectionHeader.aply_DATE"/>
        </div>
        <div>
          <test-describe front="检验时间"
                         :text="inspectionHeader.ordr_CREATE_DATE"/>
        </div>
        <div>
          <test-describe front="报告时间"
                         :text="inspectionHeader.audt_TIME"/>
        </div>
        <div>
          <test-describe front="送检医生"
                         :text="inspectionHeader.test_USR_NAME"/>
        </div>
        <div>
          <test-describe front="检验人"
                         :text="inspectionHeader.ordr_USR_NAME"/>
        </div>
        <div>
          <test-describe front="审核人"
                         :text="inspectionHeader.audt_USR_NAME"/>
        </div>
      </div>
    </div>
  </div>
  <div class="container">
    <el-auto-resizer>
      <template #default="{ height, width }">
        <div style="display: flex">
          <div class="sidebar">
            <vxe-table :height="height"
                       :row-config="{isHover : true, isCurrent: true,height: 24}"
                       show-header-overflow
                       show-overflow
                       :scroll-x="{gt: 20}"
                       :scroll-y="{gt: 50,enabled: true}"
                       class="vxe-padding_zero"
                       @cell-click="sidebarRow"
                       :data="sidebarList">
              <vxe-column title="名称" field="aply_CTNT"/>
              <vxe-column title="时间" field="ordr_CREATE_DATE" width="180"/>
            </vxe-table>

          </div>
          <div class="main">
            <el-table :data="mainList"
                      :height="height"
                      row-key="itm_ORDR"
                      ref="tableRef"
                      @row-click="testRowClick"
                      :expand-row-keys="expands">
              <el-table-column label="选择" type="selection"/>
              <el-table-column type="expand" width="20">
                <template #default="{row,$index}">
                  <el-table :data="row.bacteriaResults[0].antibioticResults"
                            :ref="(el) => setRefMap(el, $index)"
                            @row-click="drugTable"
                            v-if="row.bacteriaResults.length > 0">
                    <el-table-column label="选择" type="selection"/>
                    <el-table-column label="抗菌药物" prop="anti_NAME_CN"/>
                    <el-table-column label="抗菌药物编码" prop="anti_ABB"/>
                    <el-table-column label="MIC值" prop="anti_MIC"/>
                    <el-table-column label="敏感性" prop="anti_VALUE"/>
                  </el-table>
                </template>
              </el-table-column>
              <el-table-column label="检验项目" prop="itm_NAME" width="450"/>
              <el-table-column label="结果">
                <template #default="{row}">
                  {{ result(row) }}
                </template>
              </el-table-column>
              <el-table-column label="单位" prop="itm_UNIT"/>
              <el-table-column label="说明" prop="itm_ALERT">
                <template #default="{row}">
                  <span v-html="getItemAlert(row.itm_ALERT, row.itm_STR_VALUE, row.itm_VALUE)"></span>
                </template>
              </el-table-column>
              <el-table-column label="参考值" prop="range"/>
            </el-table>
          </div>
        </div>
      </template>
    </el-auto-resizer>
  </div>
</template>

<script setup name='EmrTest'>
import {
  queryInspectionDetail,
  queryInspectionsIndex
} from '@/api/inspections'
import {onMounted, ref} from "vue";
import {xcMessage} from '@/utils/xiaochan-element-plus'
import TestDescribe from "@/components/zhu-yuan-yi-sheng/emr/auxiliary-tools/TestDescribe.vue";
import {currentAndAFewDaysAgo, getDateRangeFormatDate} from '@/utils/date'
import {
  elementReplication,
  emrCopyFunc
} from '@/views/hospitalization/zhu-yuan-yi-sheng/electronic-medical-record/emr-editor/emr-init'
import {copyStrFunc} from "@/utils/public";

const {patNo, isEmr} = defineProps({
  patNo: String,
  isEmr: {
    type: Boolean,
    default: true
  }
})


const emits = defineEmits(['close'])
const sidebarList = ref()
const mainList = ref()
const tableRef = ref()
const drugSensitivityRef = ref()
const inspectionHeader = ref({
  aply_CNTN: ''
})
const dateRange = ref([])

const refMap = {}
const setRefMap = (el, item) => {
  refMap[`drug${item}`] = el
}

const query = async () => {
  let {startTime, endTime} = getDateRangeFormatDate(dateRange.value)
  const param = {
    type: 1,
    content: patNo,
    start: startTime,
    end: endTime,
  }
  queryInspectionsIndex(param).then((res) => {
    sidebarList.value = res
  })
}
const expands = ref([])
let currentReportForm = {}

const sidebarRow = ({row}) => {
  currentReportForm = row
  queryInspectionDetail(row.ordr_ID).then((res) => {
    mainList.value = res['inspectionItems']
    inspectionHeader.value = res['inspectionHeader']
    mainList.value.forEach(item => {
      if (item.bacteriaResults.length > 0) {
        expands.value.push(item.itm_ORDR)
      }
    })
  })
}

const testRowClick = (row) => {
  let temp = tableRef.value.getSelectionRows()
  tableRef.value.toggleRowSelection(row, !temp.includes(row))
}

const drugTable = (row) => {
  let temp = drugSensitivityRef.value.getSelectionRows()
  drugSensitivityRef.value.toggleRowSelection(row, !temp.includes(row))
}

let copyStr = ''
const appendCopy = () => {
  let temp = tableRef.value.getSelectionRows()
  let data = currentReportForm.aply_CTNT + ":"

  temp.forEach(item => {
    data += `${item.itm_NAME}${result(item)}${item.itm_UNIT}${getItemStr(item.itm_ALERT, item.itm_STR_VALUE, item.itm_VALUE)}，`
  })

  for (let key in refMap) {
    let item = refMap[key]
    let tempList = item.getSelectionRows()
    tempList.forEach(item => {
      data += `${item.anti_NAME_CN}${item.anti_ABB}${item.anti_MIC}${item.anti_VALUE}，`
    })
  }

  copyStr += '   ' + data
  xcMessage.success('追加成功。')
}

const copyClick = () => {
  if (isEmr) {
    emrCopyFunc(copyStr)
  } else {
    copyStrFunc(copyStr)
  }
  emits('close')
}

const copyOutcome = (name) => {
  elementReplication(copyStr, name)
}

const result = (row) => {
  if (row.bacteriaResults.length > 0) {
    return row.bacteriaResults[0].bac_NAME_CN
  }
  return `${row.itm_VALUE} ${row.itm_STR_VALUE}`
}

function filterSex(val) {
  switch (val) {
    case '0':
      return '未填'
    case '1':
      return '男'
    case '2':
      return '女'
    case '3':
      return '未知'
  }
  return ''
}

function filterAgeUnit(val) {
  switch (val) {
    case '0':
      return '岁'
    case '1':
      return '月'
    case '2':
      return '天'
    case '3':
      return '时'
  }
  return ''
}

function getItemAlert(val, strValue, value) {
  if (strValue !== '' || value === '') return ''
  switch (val) {
    case 'L':
      return '<span style="color:#F56C6C;font-weight:bold">↓</span>'
    case 'H':
      return '<span style="color:#F56C6C;font-weight:bold">↑</span>'
  }
  return '<span style="color:#67C23A;font-weight:bold">正常</span>'
}

function getItemStr(val, strValue, value) {
  if (strValue !== '' || value === '') return ''
  switch (val) {
    case 'L':
      return '↓'
    case 'H':
      return '↑'
  }
  return '正常'
}

onMounted(async () => {
  dateRange.value = await currentAndAFewDaysAgo()
  await query()
  // todo 检验接口没有返回危急值。
  // let res = await getCriticalValueByPatInfo(patInfo.value.inpatientNo, patInfo.value.admissTimes)
})

</script>

<style scoped lang="scss">
.container {
  width: 100%;
  height: 90%;
}

.sidebar {
  width: 420px;
}

.main {
  width: 100%;
  height: 100%;
}

.describe {
  width: 100%;
  margin-left: 20px;
  font-size: 12px;

  .pat-info {
    display: flex;

    div {
      padding: 5px;
    }
  }

  .test-date {
    display: flex;

    div {
      padding: 5px;
    }
  }

}
</style>
