<template>
  <div class="page-check-data h-full">
    <div class="flex items-center h-12 py-2 px-4 bg-white">
      <div class="flex-1 space-x-4">
        <el-tag class="cursor-copy" size="large" v-copy:click="route.query.sn">
          <span class="align-middle select-none"
            >数据批次号:{{ route.query.sn }}</span
          >
          <CopyDocument class="inline-block align-middle ml-2 w-4 h-4" />
        </el-tag>
        <el-tag
          v-if="detail.archivesId"
          class="cursor-copy"
          size="large"
          v-copy:click="detail.archivesId || '-'"
        >
          <span class="align-middle select-none"
            >关联档案号:{{ detail.archivesId || "-" }}</span
          >
          <CopyDocument class="inline-block align-middle ml-2 w-4 h-4" />
        </el-tag>
        <span class="align-middle">左屏：</span>
        <el-select v-model="leftView" class="w-32">
          <el-option
            v-for="(item, index) in viewOptions"
            :key="index"
            :value="item.val"
            :label="item.label"
            :disabled="rightView == item.val"
          ></el-option>
        </el-select>
        <span class="align-middle">右屏：</span>
        <el-select v-model="rightView" class="w-32">
          <el-option
            v-for="(item, index) in viewOptions"
            :key="index"
            :value="item.val"
            :label="item.label"
            :disabled="leftView == item.val"
          ></el-option>
        </el-select>
        <template v-if="rightView == 4 && pdfResultList.length > 1">
          <el-select v-model="curPdfTemplate" filterable>
            <el-option
              v-for="(item, index) in pdfResultList"
              :key="index"
              :label="item.pdfTemplate?.template.name"
              :value="index"
            ></el-option>
          </el-select>
        </template>
      </div>
      <div>
        <el-button type="primary" link @click="router.back()">
          <Fold class="h-4 w-4 mr-2" />
          <span>返回</span>
        </el-button>
      </div>
    </div>
    <div class="data-container">
      <el-row class="h-full">
        <el-col
          v-show="containerView.includes(1)"
          :style="{
            order: containerView.findIndex(v => v == 1)
          }"
          :span="containerView.length > 1 ? 12 : 24"

          class="h-full overflow-y-auto"
        >
          <div
            v-if="detail.files.length > 1 && curFileType != 'img'"
            class="h-8 flex justify-center items-center space-x-4"
          >
            <div
              class="flex items-center text-blue-500 hover:text-blue-700 cursor-pointer"
              @click="curFileIdx--"
            >
              <ArrowLeft class="h-4 w-4" /><span>上一份</span>
            </div>
            <span>{{ curFileIdx + 1 }}/{{ detail.files.length }}</span>
            <div
              class="flex items-center text-blue-500 hover:text-blue-700 cursor-pointer"
              @click="curFileIdx++"
            >
              <span>下一份</span><ArrowRight class="h-4 w-4" />
            </div>
          </div>
          <template v-if="curFileType == 'pdf'">
            <Webview
              :url="formatFileUrlProtocol(detail.files[curFileIdx].fileUrl)"
              class="w-full h-full"
            />
          </template>
          <template v-else-if="curFileType == 'img'">
            <div v-for="(item, index) in detail.files" :key="index">
              <img
                :src="formatFileUrlProtocol(item.fileUrl)"
                alt=""
                class="w-full h-fit select-none"
              />

            </div>
          </template>
          <template v-else-if="curFileType == 'json'">
            <json-viewer
              v-if="detail.files[curFileIdx].jsonData"
              :value="detail.files[curFileIdx].jsonData"
              :show-array-index="false"
              boxed
              expanded
              preview-mode
            >
            </json-viewer>
          </template>
          <el-empty
            v-else
            description="未上传原始数据或者不支持的文件类型"
          ></el-empty>
        </el-col>
        <el-col
          v-show="containerView.includes(2)"
          :style="{
            order: containerView.findIndex(v => v == 2)
          }"
          :span="containerView.length > 1 ? 12 : 24"
          class="h-full overflow-y-auto"
        >
          <el-card
            v-for="(item, index) in transferRawJson"
            :key="index"
            class="mb-4"
            shadow="never"
          >
            <div class="p-2 text-blue-600">检查数据</div>
            <el-table :data="item.bodyData">
              <el-table-column
                label="身体物质/部位"
                prop="name"
              ></el-table-column>
              <el-table-column
                label="检查项目"
                prop="itemName"
              ></el-table-column>
              <el-table-column label="结果" prop="value"></el-table-column>
              <el-table-column
                label="参考范围"
                prop="reference"
              ></el-table-column>
              <el-table-column label="单位" prop="unit"></el-table-column>
            </el-table>
            <div class="mt-2 p-2 text-yellow-600">异常项目</div>
            <el-table :data="item.abnormalData">
              <el-table-column
                label="异常项目"
                prop="name"
                width="200"
              ></el-table-column>
              <el-table-column label="结果">
                <template #default="{ row }">
                  <div v-if="row.value" class="space-x-2 space-y-2">
                    <el-tag
                      v-for="(val, valKey) in row.value"
                      :key="valKey"
                      type="warning"
                    >
                      <span>{{ valKey }}</span
                      >:
                      <span>{{ val }}</span>
                    </el-tag>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col
          v-show="containerView.includes(3)"
          :style="{
            order: containerView.findIndex(v => v == 3)
          }"
          :span="containerView.length > 1 ? 12 : 24"
          class="h-full overflow-y-auto"
        >
          <el-scrollbar>
            <json-viewer
              v-if="detail.resultRawJson"
              :value="detail.resultRawJson"
              :show-array-index="false"
              boxed
              expanded
              preview-mode
            >
            </json-viewer>
          </el-scrollbar>
        </el-col>
        <el-col
          v-show="containerView.includes(4)"
          :style="{
            order: containerView.findIndex(v => v == 4)
          }"
          :span="containerView.length > 1 ? 12 : 24"
          class="h-full"
        >
          <Webview
            v-if="pdfResultList[curPdfTemplate]?.pdfTransferResultUrl"
            :url="
              formatFileUrlProtocol(
                pdfResultList[curPdfTemplate]?.pdfTransferResultUrl
              )
            "
            class="w-full h-full"
          />
          <el-empty v-else description="暂无分析报告"></el-empty>
        </el-col>
        <el-col
          v-show="containerView.includes(8)"
          :style="{
            order: containerView.findIndex(v => v == 8)
          }"
          :span="containerView.length > 1 ? 12 : 24"
          class="h-full overflow-y-auto"
        >
          <component
            v-if="[4].includes(detail.type) && CompCheckData"
            :is="CompCheckData"
          ></component>
        </el-col>
        <el-col
          v-show="containerView.includes(5)"
          :style="{
            order: containerView.findIndex(v => v == 5)
          }"
          :span="containerView.length > 1 ? 12 : 24"
          class="h-full overflow-y-auto"
        >
          <component
            v-if="[6, 7].includes(detail.type) && VisitsFillData"
            :is="VisitsFillData"
          ></component>
        </el-col>
        <el-col
          v-show="containerView.includes(6)"
          :style="{
            order: containerView.findIndex(v => v == 6)
          }"
          :span="containerView.length > 1 ? 12 : 24"
          class="h-full overflow-y-auto"
        >

          <component
            v-if="[2].includes(detail.type) && MonitoringData"
            :is="MonitoringData"
          ></component>
        </el-col>
        <el-col
          v-show="containerView.includes(7)"
          :style="{
            order: containerView.findIndex(v => v == 7)
          }"
          :span="containerView.length > 1 ? 12 : 24"
          class="h-full overflow-y-auto"
        >

          <component
            v-if="[3].includes(detail.type) && DiseaseVisitData"
            :is="DiseaseVisitData"
            :form-show="true"
          ></component>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import {
  computed,
  watch,
  ref,
  reactive,
  onMounted,
  shallowRef,
  provide,
  defineAsyncComponent
} from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  CopyDocument,
  Fold,
  ArrowLeft,
  ArrowRight
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { request, parseJsonData, findScope } from "@/utils";
import JsonViewer from "vue-json-viewer";
import Webview from "@/components/WebView.vue";
import dayjs from "dayjs";
// import VisitsFillData from './components/VisitsFillData.vue';
const VisitsFillData = defineAsyncComponent(() =>
  import("./components/VisitsFillData.vue")
);
const DiseaseVisitData = defineAsyncComponent(() =>
  import("./components/DiseaseVisitData.vue")
);
const MonitoringData = defineAsyncComponent(() =>
  import("@/views/dataCenter/components/MonitoringData.vue")
);
const CompCheckData = defineAsyncComponent(() =>
  import("@/views/dataCenter/components/CompCheckData.vue")
);
const [route, router] = [useRoute(), useRouter()];
const sn = provide("sn", route.query.sn);
const leftView = ref(1);
const rightView = ref(2);
const containerView = computed(() => {
  return [leftView.value, rightView.value].filter(v => v > 0);
});

const viewOptions = ref([]);
const originViewOptions = [
  {
    label: "隐藏视图",
    val: -1
  },
  {
    label: "原始数据",
    val: 1
  }
];
const viewOptionsMap = {
  1: [
    {
      label: "处理后的数据",
      val: 2
    },
    // {
    //   label: "分析结果",
    //   val: 3
    // },
    // {
    //   label: "分析报告",
    //   val: 4
    // }
  ],
  2: [
    {
      label: "处理后的数据",
      val: 6
    }
  ],
  3: [
    {
      label: "处理后的数据",
      val: 7
    }
  ],
  4: [
    {
      label: "处理后的数据",
      val: 8
    }
  ],
  6: [
    {
      label: "填写数据",
      val: 5
    }
  ],
  7: [
    {
      label: "填写数据",
      val: 5
    }
  ]
};
const defaultView = {
  1: 2,
  2: 6,
  3: 7,
  4: 8,
  6: 5,
  7: 5,
};
const curFileIdx = ref(0);
watch(
  () => curFileIdx.value,
  idx => {
    if (idx < 0) {
      curFileIdx.value = detail.value.files.length - 1;
    } else if (idx > detail.value.files.length - 1) {
      curFileIdx.value = 0;
    }
  }
);
const detail = ref({
  sn: "",
  archivesId: "",
  transferRawJson: [],
  files: []
});
const curFileType = computed(() => {
  const curFile = detail.value.files[curFileIdx.value];
  if (curFile) {
    const afterFix = curFile.fileUrl.split(".").at(-1).toLocaleLowerCase();
    if (
      [
        "gif",
        "png",
        "jpg",
        "jpeg",
        "webp",
        "svg",
        "psd",
        "bmp",
        "tif"
      ].includes(afterFix)
    )
      return "img";
    return afterFix;
  }
  return "";
});
const archivesId = ref()
const transferRawJson = ref([]);
const transferRawJsonFormId = ref();
const transferRawJsonDiseaseId = ref();
const formatFileUrlProtocol = url => url.replace(/^https?:/, location.protocol);
const getDetail = async () => {
  const { data } = await request.get(`/medicalData/detail`, {
    params: {
      sn: route.query.sn
    }
  });
  for (const file of data.detail.files) {
    if (file.fileUrl.split(".").at(-1) == "json") {
      const jsonData = await request.get(file.fileUrl);
      console.log(jsonData);
      file.jsonData = jsonData;
    }
  }
  try {
    data.detail.resultRawJson = parseJsonData(data.detail.resultRawJson, []);
    const temp = parseJsonData(data.detail.transferRawJson);
    transferRawJson.value = temp?.answers || temp || [];
    transferRawJsonFormId.value = temp?.formId;
    transferRawJsonDiseaseId.value = temp?.diseaseId;
  } catch (error) {
    console.log(error);
  }
  viewOptions.value = [
    ...originViewOptions,
    ...(viewOptionsMap[data.detail.type] || [])
  ];
  rightView.value = defaultView[data.detail.type];

  detail.value = data.detail;
  archivesId.value = data.detail.archivesId;
  if ([2].includes(data.detail.type)) {
    leftView.value = -1;
    transferRawJson.value[0].bodyData.forEach(v => {
      v.date = dayjs(v.date * 1000).format("YYYY-MM-DD HH:mm:ss");
    });
  }
  getPdfResultList(detail.value);
};
provide("transferRawJson", transferRawJson);
provide("formId", transferRawJsonFormId);
provide("archivesId", archivesId);
provide("transferRawJsonDiseaseId", transferRawJsonDiseaseId);
provide("getDetail", getDetail);

const curPdfTemplate = ref(0);
const pdfResultList = ref([]);
const getPdfResultList = async row => {
  const { data } = await request.get(
    `/idcService/mechanism/medicalData/pdfResult/list`,
    {
      params: { sn: row.sn }
    }
  );
  pdfResultList.value = data.list || [];
};
onMounted(() => {
  getDetail();
});
</script>

<style lang="scss">
.el-scrollbar__view {
  height: 100%;
  .main-content.page-check-data {
    margin: 0;
  }
}
.page-check-data {
  .data-container {
    height: calc(100% - 48px);
    width: 100%;
  }
}
</style>
