<script setup lang="ts">
import dayjs from 'dayjs'
import { rateType } from '@/hooks'
import homeWorkApi from '@/api/system/homeWork'
import { useRouter } from 'vue-router'
import { userStore } from '@/stores'
import { storeToRefs } from 'pinia'

const router = useRouter()

const OSS_URL = import.meta.env.VITE_OSS_URL

const { userInfo } = storeToRefs(userStore())

const colorConfig = {
  // 字体颜色 progerss_border progress_bg progress_active
  primary: ['#2D39BC', '#2D39BC', '#6B73E5', '#90FCF7'],
  success: ['#2F8A5B', '#27A363', '#25BF6E', '#1FFF8A'],
  error: ['#BC2D37', '#B22731', '#CB3741', '#FF3542'],
  warning: ['#a13c00', '#C08129', '#CC8A33', '#FFFE36'],
}

const rateConfig = computed(() => {
  return (rate: number) => {
    const r = Number(rate) * 100
    return {
      color: colorConfig[rateType.value(r) || 'primary'][0],
      border: colorConfig[rateType.value(r) || 'primary'][1],
      bg: colorConfig[rateType.value(r) || 'primary'][2],
      activeBg: colorConfig[rateType.value(r) || 'primary'][3],
    }
  }
})

// 筛选状态
const activeStatus = ref('')
function handleChangeStatus() {
  refreshJobList()
}

// 作业科目列表
const classList = ref<any[]>([])
async function getClassList() {
  const { data: res } = await homeWorkApi.getSubjectList({ statusList: [1, 2, 3], historyFlag: 1 })
  if (res.code === 200) {
    classList.value = res.data
  }
}

// 当前选中的科目
const activeClass = ref<number>(0)
function handleSelectClass(_item: any) {
  refreshJobList()
}

// 作业列表
const jobList = ref<any[]>([])
const page = reactive({
  pageSize: 4,
  pageNum: 1,
  total: -1,
})
const listLoading = ref(false)
async function getJobList() {
  const { data: res } = await homeWorkApi.getJobList({
    statusList: activeStatus.value ? (activeStatus.value === '3' ? [3] : [1, 2]) : [1, 2, 3],
    ...page,
    subjectId: activeClass.value,
    historyFlag: 1,
  })
  if (res.code === 200) {
    jobList.value = res.rows
    page.total = res.total
  }
}

const pageError = ref(false)
async function changePage(type: 0 | 1) {
  pageError.value = false
  const { total, pageNum, pageSize } = page
  if (type) {
    if (pageNum * pageSize >= total) return
    page.pageNum++
  } else {
    if (pageNum <= 1) return
    page.pageNum--
  }
  try {
    listLoading.value = true
    jobList.value = []
    await getJobList()
  } catch {
    pageError.value = true
  }
  listLoading.value = false
}

async function refreshJobList() {
  pageError.value = false
  listLoading.value = true
  jobList.value = []
  page.pageNum = 1
  try {
    await getJobList()
  } catch {
    pageError.value = true
  }
  listLoading.value = false
}

const pageLoading = ref(false)
onActivated(async () => {
  pageLoading.value = true
  listLoading.value = true
  jobList.value = []
  page.pageNum = 1
  try {
    await getClassList()
    if (classList.value.length) {
      if (classList.value.every(i => i.id !== activeClass.value)) {
        activeClass.value = classList.value[0]?.id
      }
      await getJobList()
    }
  } catch {}
  listLoading.value = false
  pageLoading.value = false
})

function toReports(item: any) {
  router.push(`/system/homeWork/reports/${item.id}`)
}

// 是否到截止时间
const isDeadline = computed(() => (time: string) => dayjs().isAfter(time))
</script>
<template>
  <div class="uncomplete">
    <div class="top">
      <BackBar leftText="作业记录" />
      <Select
        v-model="activeStatus"
        :selectList="[
          { label: '全部', value: '' },
          { label: '已批改', value: '3' },
          { label: '未批改', value: '2' },
        ]"
        @selectChange="handleChangeStatus"
      ></Select>
    </div>
    <div v-if="classList.length" class="main">
      <div class="main-sidebar">
        <Sidebar
          v-model="activeClass"
          :config="classList"
          :prop="{ name: 'subject' }"
          @handle-change="handleSelectClass"
        ></Sidebar>
      </div>
      <div class="list-box">
        <template v-if="jobList.length">
          <div class="list hidden_scroll">
            <div ref="scrollRef">
              <div v-for="i in jobList" :key="i.id" class="list-item pointer" @click="toReports(i)">
                <div class="list-item-info">
                  <div class="list-item-title">{{ i.name }}</div>
                  <div class="list-item-name">{{ i.paperName }}</div>
                  <div class="list-item-time">
                    {{
                      i.createTime && `发布时间：${dayjs(i.createTime).format('YYYY/MM/DD HH:mm')}`
                    }}
                    &nbsp;&nbsp;
                    {{
                      i.submitEndTime &&
                      `截止时间：${dayjs(i.submitEndTime).format('YYYY/MM/DD HH:mm')}`
                    }}
                    &nbsp;&nbsp;
                    {{ i.markTime && `批改时间：${dayjs(i.markTime).format('YYYY/MM/DD HH:mm')}` }}
                  </div>
                  <div
                    v-if="i.status === 3 && isDeadline(i.submitEndTime)"
                    class="list-item-rate"
                    :style="{ color: rateConfig(i.scoreRate).color }"
                  >
                    得分率：{{ i.scoreRate }}%
                    <ProgressBar
                      :rate="i.scoreRate / 100"
                      width="196"
                      v-bind="rateConfig(i.scoreRate)"
                    ></ProgressBar>
                    <div class="reward-list">
                      <div v-if="i.addDiamond" class="reward-list-item">
                        <ItemPopover
                          :data="{
                            iconName: 'reward_diamond',
                            rewardName: '钻石',
                            personalCount: userInfo.diamond,
                          }"
                        >
                          <Icon name="diamond_nobg" width="48" @click.stop="false"></Icon>
                        </ItemPopover>
                        <span class="text">+{{ i.addDiamond }}</span>
                      </div>
                      <div v-if="i.addExp" class="reward-list-item">
                        <ItemPopover
                          :data="{
                            iconName: 'reward_exp',
                            rewardName: '经验值',
                            personalCount: userInfo.experience,
                          }"
                        >
                          <Icon name="exp_nobg" width="48" @click.stop="false"></Icon>
                        </ItemPopover>
                        <span class="text">+{{ i.addExp }}</span>
                      </div>
                    </div>
                  </div>
                </div>
                <div
                  :class="{ 'list-item-status': true, active: i.status === 3 }"
                  :style="{
                    'background-image':
                      i.status === 3
                        ? `url(${OSS_URL}/urm/homeWork/corrected.svg)`
                        : `url(${OSS_URL}/urm/homeWork/uncorrected.svg)`,
                  }"
                >
                  {{ i.status === 3 ? '已批改' : '未批改' }}
                </div>
              </div>
            </div>
          </div>
          <div class="page">
            <Btn v-if="page.pageNum > 1" width="162" height="80" tilt @click="changePage(0)">
              上一页
            </Btn>
            <div>{{ page.pageNum }}/{{ Math.ceil(page.total / page.pageSize) }}</div>
            <Btn
              v-if="page.pageNum * page.pageSize < page.total"
              type="success"
              width="162"
              height="80"
              tilt
              @click="changePage(1)"
            >
              下一页
            </Btn>
          </div>
        </template>
        <Empty
          v-else
          class="empty"
          :type="listLoading ? 'loading' : pageError ? 'network' : 'learn'"
          :content="pageError ? '网络出问题了啦' : '暂无作业记录，快去做作业吧！'"
        ></Empty>
      </div>
    </div>
    <Empty
      v-else
      class="empty"
      :type="pageLoading ? 'loading' : 'learn'"
      content="暂无作业记录，快去做作业吧！"
    ></Empty>
  </div>
</template>
<style scoped lang="scss">
.uncomplete {
  @include main_bg;
  height: 100vh;
  overflow: hidden;
  box-sizing: border-box;

  .top {
    padding: 3vh 64px 0;
    // margin-bottom: 24px;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    // &-menu {
    //     display: flex;
    //     justify-content: space-between;
    //     align-items: center;
    //     // flex: 1;
    //     padding-left: 80px;
    // }
  }

  .main {
    // display: flex;
    height: calc(100% - 130px);
    padding-left: 64px;
    padding-right: 64px;
    padding-top: 2.67vh;
    position: relative;
    &-sidebar {
      position: absolute;
      left: 64px;
      top: 2.67vh;
      height: calc(100% - 66px);
      width: 272px;
    }
    .list-box {
      height: 100%;
      margin-left: 310px;
      overflow: hidden;
      .page {
        margin-top: 0.83vh;
        display: flex;
        align-items: center;
        color: #666;
        font-family: $font-special;
        font-size: 2.67vh;
        font-style: normal;
        font-weight: 400;
        line-height: 4vh;
        justify-content: flex-end;
        :deep(.x-button) {
          box-shadow: none;
          margin: 0 40px;
          &.primary {
            margin-right: 80px;
          }
        }
      }
    }

    .list {
      height: calc(100% - 90px);
      overflow-y: auto;
      &-item {
        display: flex;
        align-items: center;
        border-radius: 1.67vh;
        background: #fff;
        overflow: hidden;

        margin-bottom: 1.33vh;
        &:last-child {
          margin-bottom: 0;
        }
        &-info {
          width: calc(100% - 230px);
          position: relative;
        }
        &-title {
          // display: inline-block;
          padding: 0 8px;
          height: 6.67vh;
          line-height: 6.67vh;
          background: #7effff;
          margin-bottom: 2vh;
          width: 500px;
          box-sizing: border-box;
          text-align: center;
          // max-width: 100%;
          color: $font-color;
          font-family: $font-special;
          font-size: 2.5vh;
          font-style: normal;
          font-weight: 400;
          border-top-left-radius: 20px;
          @include single_ellipsis;
        }
        &-name {
          color: #666;
          font-family: 'OPPO Sans';
          font-size: 2.33vh;
          font-style: normal;
          font-weight: 400;
          line-height: 3.5vh; /* 150% */
          padding-left: 32px;
          width: 100%;
          margin-bottom: 1.33vh;
          @include single_ellipsis;
        }
        &-time {
          color: #999;
          font-family: 'OPPO Sans';
          font-size: 2vh;
          font-style: normal;
          font-weight: 400;
          line-height: 3vh; /* 150% */
          padding-left: 32px;
          padding-bottom: 2vh;
        }
        &-status {
          width: 216px;
          height: 8vh;
          // background: url('~@/static/unity/schoolJob/uncorrected.svg') no-repeat;
          background-repeat: no-repeat;
          background-size: 100%;
          color: $font-color;
          font-family: $font-special;
          font-size: 2.67vh;
          font-style: normal;
          font-weight: 400;
          line-height: 8vh; /* 150% */
          text-align: center;
          // &.active {
          // background: url('~@/static/unity/schoolJob/corrected.svg') no-repeat;
          // }
        }
        &-rate {
          display: flex;
          align-items: center;
          position: absolute;
          left: 516px;
          top: 1.83vh;
          font-family: $font-special;
          font-size: 2.33vh;
          line-height: 3vh;
          .progress-bar {
            margin-left: 12px;
          }
        }
        .reward-list {
          display: flex;
          align-items: center;
          justify-content: center;
          margin-left: 12px;
          &-item {
            display: flex;
            align-items: center;
            margin: 0 8px;
            // color: $font-color;
            font-family: $font-special;
            font-size: 2.33vh;
            .x-icon {
              margin-right: 8px;
            }
          }
        }
      }
    }
  }
  .empty {
    height: calc(100% - 156px);
    position: relative;
    .box {
      position: absolute;
      top: 22.08vh;
      left: 50%;
      transform: translateX(-50%);
      text-align: center;
    }
    img {
      width: 320px;
      height: 26.67vh;
    }
    .text {
      color: #afbfcf;
      text-align: center;
      font-family: $font-special;
      font-size: 2.33vh;
      font-style: normal;
      font-weight: 400;
      line-height: 3.5vh; /* 150% */
    }
  }
}
.info-time {
  color: #999;
  font-family: 'PingFang SC';
  font-size: 1.67vh;
  font-style: normal;
  font-weight: 400;
  line-height: 2.5vh; /* 150% */
  margin-top: 0.5vh;
  span {
    margin-right: 24px;
  }
}
</style>
