<script setup lang="ts">
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
import { userStore } from '@/stores'
import { XMessage, debounce } from '@/hooks'
import homeWorkApi from '@/api/system/homeWork'
import LoadIcon from '@/page/system/mailbox/components/LoadIcon.vue'
import sass from '@/utils/sass'

const router = useRouter()
const { token } = userStore()
const OSS_URL = import.meta.env.VITE_OSS_URL
const itemBg = `url(${OSS_URL}/icon/homeWork_temporary_item_bg.svg)`

const subjectList: any = ref([])

const page = reactive({
  pageSize: 11,
  pageNum: 1,
  total: 0,
})
const jobList: any = ref([])
const uploadLoading = ref(false)
const listLoading = ref(false) // 列表加载
const moreLoading = ref(false) // 加载更多
const uploadMsg = ref({
  submitUrl: '',
  subjectId: '',
  clientType: 0,
})
function toLook(item: any) {
  router.push(`/system/homeWork/temporaryHomeWork/${item.id}`)
}
function handleSelectClass() {
  initList()
}

function handleBeforeUpload(rawFile: any) {
  const fileType = ['image/jpeg', 'image/png']
  if (!fileType.includes(rawFile.type)) {
    XMessage.error('上传格式不正确，只支持JPG/PNG')
    return false
  }
  if (rawFile.size / 1024 / 1024 > 10) {
    XMessage.error('图片过大')
    return false
  }
  uploadLoading.value = true
  return true
}
async function handleUploadSuccess(res: any, _file: any) {
  uploadMsg.value.submitUrl = res.data.filePath
  uploadLoading.value = false
  try {
    const { data } = await homeWorkApi.uploadTemporaryJob(uploadMsg.value)
    if (data.code === 200) {
      initList()
    }
  } catch (err) {
    console.log(err)
  }
}
function handleUploadError() {
  XMessage.error('上传失败，请重新上传～')
  uploadLoading.value = false
}
const debounceScroll = debounce(handleScroll, 200, false)
const scrollBoxRef = ref()
async function handleScroll(event: any) {
  if (jobList.value.length >= page.total) return
  if (moreLoading.value) return
  if (event.target.scrollTop + event.target.offsetHeight >= scrollBoxRef.value?.offsetHeight - 50) {
    page.pageNum++
    try {
      moreLoading.value = true
      await initTemporaryJobList()
    } catch {
      page.pageNum--
    }
    moreLoading.value = false
  }
}
async function initList() {
  if (listLoading.value) return
  listLoading.value = true
  jobList.value = []
  page.pageNum = 1
  try {
    await initTemporaryJobList()
  } catch {
    console.log('网络出问题了啦～')
  }
  listLoading.value = false
}
// 获取学科对应临时作业
async function initTemporaryJobList() {
  try {
    const { data } = await homeWorkApi.temporaryJobList({
      clientType: 0,
      subjectId: uploadMsg.value.subjectId,
      ...page,
    })
    page.total = data.total
    for (let i in data.rows) {
      jobList.value.push(data.rows[i])
    }
  } catch (err) {
    console.log(err)
  }
}
// 获取学科
async function getSubjectList() {
  try {
    const { data } = await homeWorkApi.getTemporarySubjectList()
    subjectList.value = data.rows
  } catch (err) {
    console.log(err)
  }
}
onMounted(async () => {
  await getSubjectList()
  uploadMsg.value.subjectId = subjectList.value[0].id
  initList()
})
</script>
<template>
  <div class="temporary">
    <div class="top">
      <BackBar leftText="临时作业" />
    </div>
    <div class="main">
      <div class="main_sidebar">
        <Sidebar
          v-model="uploadMsg.subjectId"
          :config="subjectList"
          @handle-change="handleSelectClass"
        ></Sidebar>
      </div>
      <div class="main_answer">
        <Empty v-if="listLoading" class="empty" type="loading"></Empty>
        <div v-else class="main_answer_list hidden_scroll" @scroll="debounceScroll">
          <div ref="scrollBoxRef" class="content">
            <div>
              <el-upload
                class="pointer"
                action="/api/main/sysFileInfo/tenUploadAll"
                :data="{ type: 1 }"
                :headers="{
                  Authorization: token,
                  'X-Tenant-Id': sass.platform.tenantId,
                }"
                accept="image/*"
                :before-upload="handleBeforeUpload"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :show-file-list="false"
                :disabled="uploadLoading"
              >
                <Icon name="add_book" size="80" />
                <span class="text">{{ uploadLoading ? '上传中' : '上传图片' }}</span>
              </el-upload>
            </div>
            <div v-for="(i, index) in jobList" :key="index" class="item pointer" @click="toLook(i)">
              <img :src="i.submitUrl" alt="" class="sub_answer" />
              <span class="sub_date">{{ dayjs(i.submitTime).format('YYYY/MM/DD HH:mm') }}</span>
              <div v-if="i.status === 1" class="result">已批改</div>
            </div>
          </div>
          <LoadIcon v-if="moreLoading" class="load-icon"></LoadIcon>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped lang="scss">
.temporary {
  @include main_bg;
  padding: 2.67vh 64px;
  height: 100vh;
  overflow: hidden;
  box-sizing: border-box;

  .top {
    position: absolute;
  }
  .main {
    display: flex;
    padding-top: 8.67vh;
    width: 100%;
    height: 100%;

    &_sidebar {
      padding-top: 2vh;
      width: 214px;
      margin-right: 98px;
    }
    &_answer {
      width: 100%;
      height: 100%;
      padding: 2.5vh;
      border-radius: 3.33vh;
      border: 0.67vh solid #fff;
      background: linear-gradient(179.32deg, #fdfdf9 0.69%, #dfebf7 99.53%);
      box-sizing: border-box;

      &_list {
        height: 100%;
        .content {
          display: flex;
          flex-wrap: wrap;
          :deep(.el-upload) {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            margin-right: 24px;
            width: 328px;
            height: 33.5vh;
            border-radius: 1.67vh;
            background: #f2f3ff;
            box-shadow: 0 0.33vh 0.33vh 0 #00000026;
            .text {
              font-family: $font-special;
              margin-top: 2vh;
              display: block;
              font-size: 2.33vh;
              line-height: 3.5vh;
              color: #80b5fe;
            }
          }

          .item {
            position: relative;
            padding: 2vh 24px 2.67vh 24px;
            width: 332px;
            height: 33.83vh;
            margin: 0 24px 2vh 0;
            border-radius: 1.67vh;
            background-image: v-bind(itemBg);
            background-size: 100%;
            background-repeat: no-repeat;
            background-position: right bottom;

            .sub_answer {
              width: 284px;
              height: 23.67vh;
              border-radius: 0.83vh;
            }
            .sub_date {
              display: inline-block;
              margin-top: 2vh;
              font-size: 2.33vh;
              line-height: 3.5vh;
              color: #666;
            }
            &:nth-child(4n) {
              margin-right: 0;
            }
            .result {
              position: absolute;
              top: 0;
              right: 0;
              padding: 0.67vh 14px;
              color: #2f8a5b;
              font-family: $font-special;
              font-size: 2.33vh;
              line-height: 3.5vh;
              text-align: center;
              background-color: #a2fb6e;
              border-radius: 0 1.67vh 0 1.67vh;
            }
          }
        }
      }
    }
  }
}
</style>
