<script lang="ts" setup>
import { IotOpeationFillApi } from '@/api/pms/iotopeationfill'
import { IotStatApi } from '@/api/pms/stat'
import { useUserStore } from '@/store/modules/user'
import Rdkb from '@/views/pms/stat/rdkb.vue'
import Rhkb from '@/views/pms/stat/rhkb.vue'
import Rykb from '@/views/pms/stat/rykb.vue'
import Stat from './stat.vue'

const user = useUserStore().getUser

const company = ref<string>('')
const companyLoading = ref(true)
const iframeUrl = ref('')
const iframeLoading = ref(false)
let iframeRequestId = 0

const reportUrls: Record<string, string> = {
  jt: 'https://report.deepoil.cc/webroot/decision/v10/entry/access/dbc9cf73-81ce-43f1-9923-45cdfa5d5d3a?preview=true&page_number=1'
}

const currentCompany = computed(() => company.value?.toLowerCase())
const currentView = computed(() => {
  if (companyLoading.value) return 'loading'
  if (currentCompany.value === 'rd') return 'rd'
  if (currentCompany.value === 'rh') return 'rh'
  if (currentCompany.value === 'ry') return 'ry'
  if (currentCompany.value && reportUrls[currentCompany.value]) return 'report'
  return 'stat'
})

watch(
  () => user.deptId,
  async (val) => {
    companyLoading.value = true
    try {
      if (!val) {
        company.value = ''
        return
      }
      company.value = await IotOpeationFillApi.getOrgName(val)
    } finally {
      companyLoading.value = false
    }
  },
  { immediate: true }
)

watch(
  currentCompany,
  async (val) => {
    const requestId = ++iframeRequestId
    iframeUrl.value = ''
    const reportUrl = val ? reportUrls[val] : ''
    if (!reportUrl) {
      iframeLoading.value = false
      return
    }

    iframeLoading.value = true
    try {
      const token = await IotStatApi.getSsoToken()
      if (requestId !== iframeRequestId) return
      iframeUrl.value = `${reportUrl}&ssoToken=${token}`
    } finally {
      if (requestId === iframeRequestId) {
        iframeLoading.value = false
      }
    }
  },
  { immediate: true }
)
</script>
<template>
  <div v-if="currentView === 'loading'" class="full-screen-container" v-loading="true"></div>
  <div v-else-if="currentView === 'report'" class="full-screen-container" v-loading="iframeLoading">
    <iframe
      v-if="iframeUrl"
      :src="iframeUrl"
      frameborder="0"
      class="full-screen-iframe"
      allowfullscreen></iframe>
  </div>
  <Rdkb v-else-if="currentView === 'rd'" />
  <Rhkb v-else-if="currentView === 'rh'" />
  <Rykb v-else-if="currentView === 'ry'" />
  <Stat v-else />
</template>

<style scoped>
.full-screen-container {
  position: absolute;
  inset: 0;
  z-index: 1;
  width: 100%;
  height: calc(100vh - 90px);
  overflow: hidden;
}

.full-screen-iframe {
  display: block;
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
  overflow: auto;
  border: none;
}
</style>
