<template>
  <el-container class="layout-container">
    <el-container class="content-wrapper">
      <el-main class="layout-main">
        <el-scrollbar class="layout-main-scrollbar" :style="layoutMainScrollbarStyle" ref="layoutMainScrollbarRef" @scroll="handleScroll">
          <div class="default-main ba-table-box main-scroll" v-loading="loading">
            <Basein :dataV="patientData" />
            <div class="doctor-tabs-box">
              <div class="institution-name">就诊信息</div>
              <el-tabs type="card" class="demo-tabs">
                <el-tab-pane v-for="(i, index) in resData" :key="index">
                  <template #label>
                    <div class="custom-tabs-label">
                      <span class="time">{{i.MEDICAL_INFORMATION.ENCOUNTER_DATE}}</span>
                      <span class="name">&nbsp;&nbsp;{{i.MEDICAL_INFORMATION.ORGNAME}}</span>
                      <div>
                        <span class="label">诊 断：</span>
                        <span>{{i.MEDICAL_INFORMATION.DIAGNOSENAME}}</span>
                      </div>
                      <div>
                        <span class="label">主 诉：</span>
                        <span>{{i.MEDICAL_INFORMATION.CHIEFCOMPLAINT}}</span>
                      </div>
                      <div>
                        <span class="label">就诊科室：</span>
                        <span>{{i.MEDICAL_INFORMATION.DEPTNAME}}</span>
                      </div>
                      <div style="display: flex;">
                        <span class="label">检查项目：</span>
                        <!-- <span class="content">{{i.EXAM_REPORTS[index].EXAM_ITEMNAME}}</span> -->
                        <span class="content" >{{i.EXAM_REPORTS.map((item: any) => item.EXAM_ITEMNAME).filter((itemName:any) => itemName && itemName.trim() !== '').join('，')}}</span>
                      </div>
                      <div style="display: flex;">
                        <span class="label">检验项目：</span>
                        <!-- <span class="content">{{i.INSPECT_REPORTS.map((item: any) => item.INSPECT_REPORT_ITEMS).join('，')}}</span> -->
                        <span class="content">{{stringProject(i.INSPECT_REPORTS)}}</span>
                      </div>
                    </div>
                  </template>
                  <!-- 检验 -->
                  <div :class="['anchor-box', scrollTop >= 270 ? 'fixed' : '']">
                    <div :class="{ active: index === activeIndex, 'anchor-item': true }" v-for="(item, index) in i.INSPECT_REPORTS" :key="index" @click="scrollToSection(index)">{{item.LAB_ITEMNAME}}</div>
                  </div>
                  <template v-for="(item, index1) in i.INSPECT_REPORTS" :key="index1">
                    <Table :tableData="item" :hrrecords="i.HR_RECORDS" :medicalInformation="i.MEDICAL_INFORMATION" :patientCode="patientData.PATIENT_CODE" from="hrMyTable" :id="`anchor${index}`"/>
                  </template>
                  <Table :examTableData="i.EXAM_REPORTS" :hrrecords="i.HR_RECORDS" :medicalInformation="i.MEDICAL_INFORMATION" :patientCode="patientData.PATIENT_CODE" from="hrMyTable" />
                </el-tab-pane>
              </el-tabs>
            </div>
            
            <el-dialog
              class="ba-operate-dialog"
              :close-on-click-modal="false"
              :model-value="dialogVisible"
              @close="dialogVisible = false"
              width="50%"
            >
              <el-scrollbar v-loading="!dialogVisible" class="ba-table-form-scrollbar">
                  <div>
                    <el-image
                      v-if="fileType === 'image'"
                      :src="reportSrc"
                      fit="cover"
                      :style="{ width: '100%', height: 'auto' }"
                    ></el-image>
                    <embed
                      v-else-if="fileType === 'pdf'"
                      :src="reportSrc"
                      type="application/pdf"
                      width="100%"
                      height="auto"
                    />
                  </div>
              </el-scrollbar>
          </el-dialog>
        </div>
        </el-scrollbar>
        <!-- <div style="text-align: center;padding-top: 15px;">
          <el-button type="primary" :color="'var(--ba-vars-color-main-primary)'" @click="saveHr">保存互认</el-button>
        </div> -->
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import Basein from './components/basein.vue';
import Table from './components/table.vue';
import { getRecogViewHrDetail, saveRecogViewDetail, getNoHrReasonList } from '/@/api/backend/doctor'
import { provide } from 'vue';
import { getFileType } from '/@/utils/common'
import { useRoute } from 'vue-router'
import { layoutMainScrollbarRef, layoutMainScrollbarStyle } from '/@/stores/refs'
import { useSiteConfig } from '/@/stores/siteConfig'
import { ElMessage } from 'element-plus'
import { Session } from '/@/utils/storage'
const reportSrc = ref('')
const fileType = ref('image')
const loading = ref(true)
const siteConfig = useSiteConfig()
const route = useRoute()
defineOptions({
    name: 'hospital/detail',
})
const resData = ref<any>({})
const patientData = ref<any>({})
const dialogVisible = ref(false)
const activeIndex = ref(-1); 
const dialogVisibleFn = (IMAGES: string) => {
    fileType.value = IMAGES && getFileType(IMAGES)
    reportSrc.value = IMAGES
    dialogVisible.value = !dialogVisible.value
}
provide('dialogVisible', dialogVisibleFn)
const tableData = () => {
    const token = (route.query.token ?? '') as string
    getRecogViewHrDetail({
        TOKEN: token
    }).then((res)=> {
        console.log(res)
        resData.value = res.data.data
        patientData.value = res.data.patient
        loading.value = false
    })
}
const getNoHrReasonListFn = () => {
    getNoHrReasonList().then((res) => {
        const list = res.data.list
        let transformedData = list.map((item: { code: any; name: any; }) => {
            return {
                value: item.code,
                label: item.name
            };
        })
        Session.set('noHrReasonList', transformedData)
        tableData()
    })
}


const saveHr = () => {
    const HR_RECORDS = Session.get('HR_RECORDS')
    if(!HR_RECORDS) {
        ElMessage({
            message: '暂无更改的互认记录！',
            type: 'error',
        })
        return
    }
    const params = {
        TOKEN: (route.query.token ?? '') as string,
        HR_RECORDS
    }
    console.log(params, '保存参数')
    saveRecogViewDetail(params).then((res) => {
        console.log(res)
        Session.remove('HR_RECORDS')
        ElMessage({
            message: '保存成功！',
            type: 'success',
        })
    })
}
const stringProject = (INSPECT_REPORTS:any) => {
    const LAB_ITEMDETAILNAME = INSPECT_REPORTS.map((item:any)=> item.INSPECT_REPORT_ITEMS.map((subItem: any) => subItem.LAB_ITEMDETAILNAME))
    return LAB_ITEMDETAILNAME.flat().join(',');
}
const scrollToSection = (index: any) => {
    activeIndex.value = index;
    nextTick(() => {
        const anchorElement = document.getElementById('anchor'+index);
        if (anchorElement) {
            anchorElement.scrollIntoView({ behavior: 'smooth' });
        }
    });
};
const scrollTop = ref(0)
const handleScroll = (top: any) => {
    // const bottom = top + window.innerHeight;
    scrollTop.value = top.scrollTop
    let newIndex = -1;
    resData.value.INSPECT_REPORTS?.forEach((item:object, index:number) => {
        const elementId = `anchor${index}`;
        const element = document.getElementById(elementId);
        if (element) {
            const elementTop = element.offsetTop;
            if (elementTop <= top && elementTop + element.offsetHeight > top) {
                newIndex = index;
                return;
            }
        }
    });

    if (newIndex !== activeIndex.value) {
        activeIndex.value = newIndex;
    }
};
watch(
    () => siteConfig.mainScrollTop,
    (newVal) => {
        console.log(newVal, '最新滚动数据')
        handleScroll(newVal)
    },
    {
        deep:true
    }
)
const beforeUnloadHandler = (event: { returnValue: string; }) => {
    const message = '您有未保存的信息，确定要离开吗？';
    event.returnValue = message; // 用于兼容旧浏览器
    return message;
};
onMounted(() => {
    const aa = layoutMainScrollbarRef.value
    console.log(aa?.update(), '---------')
    const token = (route.query.token ?? '') as string
    // const token = adminInfo.getToken()
    const noHrReasonList = Session.get('noHrReasonList')
    if(token){
        console.log(noHrReasonList, 'huhuhuh')
        if(!noHrReasonList){
            getNoHrReasonListFn()
        }else{
            tableData()
        }
    }
    window.addEventListener('beforeunload', beforeUnloadHandler);
    if(Session.get('HR_RECORDS')){
        Session.remove('HR_RECORDS')
    }
})
onUnmounted(() => {
    window.removeEventListener('beforeunload', beforeUnloadHandler);
});
</script>

<style scoped lang="scss">
.layout-container .layout-main {
    padding: 0 !important;
    overflow: hidden;
    width: 100%;
    height: 100%;
}
.layout-main-scrollbar {
    width: 100%;
    position: relative;
    overflow: hidden;
}
.anchor-box {
  display: flex;
  background: var(--ba-bg-color-overlay);
  padding: 15px;
  font-weight: 800;
  color: var(--ba-vars-color-main-primary);
  .active {
    color: var(--el-color-danger);
    position: relative;
  }
  .active::after {
    content: '';
    display: block;
    height: 2px;
    width: 48px;
    position: absolute;
    bottom: -6px;
    transition: left .25s ease-in-out,opacity .25s,width .25s;
    background: var(--el-color-danger);
  }
  .anchor-item {
    margin-right: 16px;
    cursor: pointer;
  }
  .anchor-item:hover {
    color: var(--ba-vars-color-main-primary);
  }
}
.fixed {
  width: 100%;
  position: fixed;
  top: 0px;
  z-index: 99;
  background: var(--ba-vars-color-tree);
}
.doctor-tabs-box {
  background: var(--ba-bg-color-overlay);
  .institution-name {
    width: 120px;
    padding: 15px;
    color: var(--ba-vars-color-main-primary);
    font-weight: 600;
    font-size: var(--el-font-size-medium);
    border-bottom: 2px solid var(--ba-vars-color-main-primary);
  }
  .custom-tabs-label {
    font-weight: 400;
  }
  .custom-tabs-label .time {
    color: var(--el-color-error);
    font-weight: 600;
  }
  .custom-tabs-label .name {
    color: var(--el-color-main-primary-light);
    font-weight: 600;
  }
  .custom-tabs-label .label {
    font-weight: 800;
  }
  .content {
    color: var(--el-color-error);
    font-weight: 600;
    display: block;
    width: 300px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

</style>
