<script setup lang="ts">
import type { ExperimentRecord, Contest } from '../types'
import { HomeFilled } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import DragPanel from '@/components/DragPanel.vue'
import { upload } from '@/utils/upload'
import { getContest, getExperimentRecord, uploadExperimentPicture } from '../api'
import dayjs from 'dayjs'
import { useCookies } from '@vueuse/integrations/useCookies'
import { useAppConfig } from '@/composables/useAppConfig'
const appConfig = useAppConfig()

const Book = defineAsyncComponent(() => import('../components/Book.vue'))
const Video = defineAsyncComponent(() => import('../components/Video.vue'))
const Discuss = defineAsyncComponent(() => import('../components/Discuss.vue'))
const Result = defineAsyncComponent(() => import('../components/Result.vue'))
const Exam = defineAsyncComponent(() => import('../components/Exam.vue'))
const ReportDialog = defineAsyncComponent(() => import('../components/ReportDialog.vue'))

const route = useRoute()

interface Props {
  id: string
}
const props = defineProps<Props>()

// 获取赛项信息
let competition = $ref<Contest>()
function fetchCompetition() {
  getContest({ id: props.id }).then(res => {
    competition = res.data.detail
  })
}
onMounted(() => {
  fetchCompetition()
})

// 左侧
let detail = $ref<ExperimentRecord>()
provide('detail', $$(detail))

function fetchInfo() {
  getExperimentRecord({ competition_id: props.id }).then(res => {
    const data = res.data.detail || {}
    let pictures = []
    try {
      pictures = JSON.parse(data.pictures)
    } catch (error) {
      console.log(error)
    }
    detail = Object.assign(data, { pictures })
  })
}
watchEffect(() => {
  fetchInfo()
})

// 右侧
const cookies = useCookies(['TGC'])
let iframeKey = $ref(Date.now())
// 返回首页
function handleBackHome() {
  ElMessageBox.confirm('此操作将会强制返回到实验室首页，您当前的操作内容有可能丢失，确定返回首页吗？', '提示').then(() => {
    iframeKey = Date.now()
  })
}

const iframeRef = $ref<HTMLIFrameElement>()

let screenshotLoading = $ref(false)
let screenshotTimestamp = $ref(0)
// 截图
function handleCapture() {
  const pictures = detail?.pictures || []
  if (pictures.length >= 20) {
    ElMessage.error('已达到单个实验最大截图数量，无法截图，请在过程与结果功能中删除多余截图之后再进行操作。')
    return
  }
  const iframeWindow = iframeRef?.contentWindow
  if (!iframeWindow) return
  screenshotTimestamp = Date.now()
  screenshotLoading = true
  // 发送截图消息
  iframeWindow?.postMessage({ action: 'screenshot', timestamp: screenshotTimestamp }, '*')
}
// 截图之后
function handleCaptureCallback(event: MessageEvent) {
  const { data } = event
  if (data.action === 'screenshot' && data.timestamp === screenshotTimestamp) {
    upload(data.blob).then(url => {
      uploadPicture(url)
    })
  }
}
onMounted(() => {
  window.addEventListener('message', handleCaptureCallback, false)
})
onUnmounted(() => {
  window.removeEventListener('message', handleCaptureCallback, false)
})

// 上传截图
function uploadPicture(url: string) {
  const pictures = detail?.pictures || []
  pictures.unshift({ url, name: Date.now() + '.png', upload_time: dayjs().format('YYYY-MM-DD HH:mm:ss'), size: 1024 })
  uploadExperimentPicture({ competition_id: props.id, pictures: JSON.stringify(pictures) }).then(() => {
    fetchInfo()
    screenshotLoading = false
  })
}
// let resizeKey = $ref(0)
function handleResize() {
  resizeKey = Date.now()
}

const competitionUrl = computed(() => {
  const item = competition?.train_platform_configs.find((item: any) => item.platform_key === route.query.type)
  const url = item?.url || ''
  return url.includes('?') ? `${url}&token=${cookies.get('TGC')}` : `${url}?token=${cookies.get('TGC')}`
})

let isHeadShow = $ref(!appConfig.hideContestToolbar)
const handleShowHead = function () {
  isHeadShow = !isHeadShow
}

const getExperimentId = computed(() => {
  const item = competition?.train_platform_configs.find((item: any) => item.platform_key === route.query.type)
  let value = '0'
  if (item?.url) {
    value = item?.url.indexOf('experiment_id') !== -1 ? item?.url.substring(item?.url.indexOf('experiment_id=') + 14, item?.url.length + 1) : '0'
  }
  return value
})

const reportDialogVisible = $ref(false)
</script>

<template>
  <DragPanel @resize="handleResize">
    <template #left>
      <div class="lab-left">
        <h1>{{ competition?.name }}</h1>
        <el-tabs type="border-card">
          <el-tab-pane label="实训指导" lazy>
            <!-- <Book :competition_id="id" :key="resizeKey"></Book> -->
            <Book :competition_id="id" :experiment_id="getExperimentId"></Book>
          </el-tab-pane>
          <el-tab-pane label="操作视频" lazy>
            <Video :competition_id="id"></Video>
          </el-tab-pane>
          <el-tab-pane label="讨论交流" lazy>
            <Discuss :competition_id="id"></Discuss>
          </el-tab-pane>
          <el-tab-pane label="过程与结果" lazy>
            <Result :competition_id="id" @update="fetchInfo"></Result>
          </el-tab-pane>
          <el-tab-pane label="实操试卷" lazy v-if="appConfig.hidePracticalTestPaper !== true">
            <Exam :competition_id="id"></Exam>
          </el-tab-pane>
        </el-tabs>
      </div>
    </template>
    <template #right>
      <AppCard v-if="isHeadShow" style="margin-bottom: 20px">
        <el-row justify="space-between">
          <el-button type="primary" :icon="HomeFilled" @click="handleBackHome">返回首页</el-button>
          <div>
            <el-button type="primary" :loading="screenshotLoading" @click="handleCapture">截图</el-button>
            <el-button type="primary" @click="reportDialogVisible = true">上传实验报告</el-button>
          </div>
        </el-row>
      </AppCard>
      <div class="lab-box">
        <div class="close-btn" @click="handleShowHead">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 86" aria-hidden="true" width="16" height="66">
            <g fill="none" fill-rule="evenodd">
              <path class="path-wapper" d="M0 0l14.12 8.825A4 4 0 0116 12.217v61.566a4 4 0 01-1.88 3.392L0 86V0z" fill="#f8f9fa"></path>
              <path
                class="path-arrow"
                style="transform: rotate(180deg); transform-origin: center"
                d="M10.758 48.766a.778.778 0 000-1.127L6.996 43l3.762-4.639a.778.778 0 000-1.127.85.85 0 00-1.172 0l-4.344 5.202a.78.78 0 000 1.128l4.344 5.202a.85.85 0 001.172 0z"
                fill="#8D9EA7"
                fill-rule="nonzero"></path>
            </g>
          </svg>
        </div>
        <iframe allowfullscreen allow="camera; microphone" :src="competitionUrl" :key="iframeKey" frameborder="0" class="iframe" ref="iframeRef"></iframe>
      </div>
    </template>
  </DragPanel>
  <ReportDialog v-model="reportDialogVisible" :data="competition" v-if="reportDialogVisible && competition"></ReportDialog>
</template>
<!-- 上传报告 -->

<style lang="scss" scoped>
.close-btn {
  cursor: pointer;
  position: absolute;
  top: -40px;
  right: 45px;
  transform: rotate(270deg);
  transform-origin: center;
}
.lab-left {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;
  h1 {
    margin-bottom: 20px;
  }
  .el-tabs {
    flex: 1;
    border: 0;
    overflow: hidden;
  }
  :deep(.el-tabs__header) {
    background-color: #e1e4eb;
  }
  :deep(.el-tabs__item) {
    padding: 0 14px !important;
    border: 0;
    border-radius: 6px 6px 0px 0px;
  }
  :deep(.el-tabs__content) {
    height: calc(100% - 40px);
    box-sizing: border-box;
  }
  :deep(.el-tab-pane) {
    height: 100%;
    overflow-y: auto;
  }
}
.lab-box {
  position: relative;
  flex: 1;
  width: 100%;
  background: #f8f9fa;
}
.iframe {
  width: 100%;
  height: 100%;
}
</style>
