<script setup lang="ts">
import type { ExperimentInfo, ExperimentRecord, ExperimentRecordFile } from '../types'
import { ElMessage, ElMessageBox } from 'element-plus'
import ImageViewer from '@/components/ImageViewer.vue'
import { uploadExperimentPicture, getExperimentReport, getExperimentReportCache } from '../api'
const ResultScoreDialog = defineAsyncComponent(() => import('./ResultScoreDialog.vue'))

interface Props {
  data?: ExperimentInfo
}
const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update'): void
}>()

const detail = $ref(inject<ExperimentRecord>('detail'))

const dialogVisible = $ref(false)

const canRemove = $computed(() => {
  return !(detail?.status !== 0)
})
const hasScore = $computed(() => {
  if (props.data?.report_upload_way === 2) {
    // 在线报告
    return props.data.is_commit_report ? detail?.is_check_report && detail?.status === 2 : detail?.status === 2
  } else {
    return detail?.status === 2
  }
})

let imageViewerVisible = $ref<boolean>(false)
let imageViewerIndex = $ref<number>(0)
// 查看
function handlePreview(index: number) {
  imageViewerVisible = true
  imageViewerIndex = index
}
// 删除
async function handleRemove(index: number, file: ExperimentRecordFile) {
  if (!props.data) return
  let reportDetail: any = []
  await getExperimentReportCache({ experiment_id: props.data.id }).then(res => {
    const report = res.data.report
    if (report.detail) {
      try {
        reportDetail = JSON.parse(report.detail)
      } catch (error) {
        console.log(error)
      }
    }
  })
  await getExperimentReport({ experiment_id: props.data.id }).then(res => {
    const report = res.data.report
    if (report.detail) {
      try {
        reportDetail = JSON.parse(report.detail)
      } catch (error) {
        console.log(error)
      }
    }
  })
  const reportFiles: any[] = reportDetail.reduce((result: any[], item: any) => {
    if (item.type === 2) {
      result = result.concat(item.files)
    }
    return result
  }, [])
  const found = reportFiles.find(item => item.url === file.url)
  if (found) {
    ElMessage.error('不能删除实验报告中的截图，请先删除实验报告关联的截图！')
    return
  }
  ElMessageBox.confirm('删除之后无法恢复，确认删除该截图吗？', '提示').then(() => {
    if (!props.data) return
    const pictures = detail?.pictures.filter((item, i) => i !== index)
    uploadExperimentPicture({ experiment_id: props.data.id, pictures: JSON.stringify(pictures) }).then(() => {
      emit('update')
    })
  })
}
</script>

<template>
  <template v-if="detail && data">
    <div class="result-score">
      <h2>我的成绩</h2>
      <template v-if="hasScore">
        <p class="t1" @click="dialogVisible = !dialogVisible">{{ parseFloat(detail.score) }}</p>
        <p class="t2">批改讲师：{{ detail.checker_user.real_name }}</p>
      </template>
      <template v-else>
        <p class="t1">--</p>
      </template>
    </div>
    <h3>实验过程</h3>
    <ul class="picture-list">
      <li v-for="(item, index) in detail.pictures" :key="item.url">
        <img :src="item.url" />
        <p>截图时间：{{ item.upload_time }}</p>
        <div class="cover">
          <div class="cover-inner">
            <el-button type="primary" plain round @click="handlePreview(index)">查看</el-button>
            <el-button type="primary" plain round @click="handleRemove(index, item)" v-if="canRemove">删除</el-button>
          </div>
        </div>
      </li>
    </ul>
    <ImageViewer v-model="imageViewerVisible" :index="imageViewerIndex" :items="detail.pictures"></ImageViewer>
    <ResultScoreDialog
      v-model="dialogVisible"
      :experiment_id="data.id"
      v-if="dialogVisible && data"></ResultScoreDialog>
  </template>
  <el-empty description="暂无数据" v-else />
</template>

<style lang="scss" scoped>
.result-score {
  margin-bottom: 40px;
  text-align: center;
  h2 {
    font-size: 18px;
    font-weight: 400;
    line-height: 30px;
    color: #333333;
    text-align: center;
  }
  .t1 {
    margin: 20px auto 10px;
    padding-top: 64px;
    width: 80px;
    height: 110px;
    font-size: 24px;
    font-weight: bold;
    line-height: 1;
    color: #ffffff;
    background: url(@/assets/images/score_bg.png) no-repeat;
    background-size: contain;
    box-sizing: border-box;
    cursor: pointer;
  }
  .t2 {
    font-size: 14px;
    line-height: 24px;
    color: #666666;
  }
}
h3 {
  font-size: 16px;
  font-weight: 400;
  line-height: 27px;
  color: #333333;
}
.picture-list {
  li {
    position: relative;
    height: 200px;
    margin: 20px 0;
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    p {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      padding: 0 10px;
      font-size: 14px;
      color: #fff;
      line-height: 30px;
      text-align: right;
      background-color: rgba(0, 0, 0, 0.5);
    }
    &:hover {
      .cover {
        display: block;
      }
    }
  }
  .cover {
    display: none;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .cover-inner {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .el-button {
      width: 100px;
      margin: 10px 0;
    }
  }
}
</style>
