<script setup lang="ts">
import AppList from '@/components/base/AppList.vue'
import { getCompetitionItems, getCompetitionStatistics, getCompetitionCompetitors } from '../api'
import { useNow } from '@vueuse/core'
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
dayjs.extend(duration)

const appList = ref<InstanceType<typeof AppList> | null>(null)

const competitionList = ref<Array<any>>([])
const currentCompetition = ref()
const countdown = computed(() => {
  const timestamp = currentCompetition.value?.end_at * 1000 - useNow().value.getTime()
  if (timestamp > 0) {
    return dayjs.duration(timestamp).format('HH:mm:ss')
  }
  return '00:00:00'
})

async function fetchCompetition() {
  const res = await getCompetitionItems()
  competitionList.value = res.data.items
  if (res.data.items.length) {
    currentCompetition.value = res.data.items[0]
  }
}
onMounted(() => {
  fetchCompetition()
})

const platformKey = ref('data_marketing')
const platformKeys = ref([
  { platform_key: 'career_data_analysis', name: '商业数据分析实验' },
  { platform_key: 'data_marketing', name: '数据营销实操' }
])
// async function fetchPlatformKeys(competition_id: string) {
//   const res = await getPlatformKeys({ competition_id })
//   platformKeys.value = res.data.items
// }
// watchEffect(() => {
//   if (currentCompetition.value?.id) fetchPlatformKeys(currentCompetition.value.id)
// })

function fetchInfo() {
  if (currentCompetition.value?.id && platformKey.value) {
    fetchStatistics(currentCompetition.value.id, platformKey.value)
    fetchCompetitors(currentCompetition.value.id, platformKey.value)
  }
}
let timer: null | number = null
onMounted(() => {
  timer = setInterval(() => {
    fetchInfo()
  }, 3000)
})

onUnmounted(() => {
  timer && clearInterval(timer)
})

const statistics = reactive({
  competitor_count: 0,
  complete_answer_competitor_count: 0,
  starting_answer_competitor_count: 0
})
async function fetchStatistics(competition_id: string, platform_key = 'career_data_analysis') {
  const res = await getCompetitionStatistics({ competition_id, platform_key })
  Object.assign(statistics, res.data.detail)
}

const competitorsList = ref([])
const competitorsTableData = computed(() => {
  return competitorsList.value.map((row: any) => {
    const commit_time = dayjs.unix(row.commit_time).format('YYYY-MM-DD HH:mm:ss')
    const timestamp = (row.commit_time * 1000 || Date.now()) - row.start_answer_time * 1000
    const dur = dayjs.duration(timestamp)
    const answer_time = dur.hours() === 0 ? dur.format("m[']s") : dur.format("H[h]m[']s")
    return { ...row, commit_time, answer_time }
  })
})
async function fetchCompetitors(competition_id: string, platform_key = 'career_data_analysis') {
  const res = await getCompetitionCompetitors({ competition_id, platform_key })
  competitorsList.value = res.data.items
}

watchEffect(() => {
  fetchInfo()
})
//  已提交选手
const submittedListOptions = {
  columns: [
    { label: '序号', type: 'index', width: 60 },
    { label: '选手姓名', prop: 'student.name' },
    { label: '参赛ID', prop: 'login_id' },
    { label: '所在学校', prop: 'student.organ_name' },
    { label: '所在专业', prop: 'student.specialty_name' },
    { label: '所在班级', prop: 'student.class_name' },
    { label: '提交时间', prop: 'commit_time' },
    { label: '作答用时', prop: 'answer_time' }
  ]
}
const submittedLis = computed(() => {
  return competitorsTableData.value.filter((item: any) => item.commit_status == 3)
})
// 正在作答选手
const answeringListOptions = {
  columns: [
    { label: '序号', type: 'index', width: 60 },
    { label: '选手姓名', prop: 'student.name' },
    { label: '参赛ID', prop: 'login_id' },
    { label: '所在学校', prop: 'student.organ_name' },
    { label: '所在专业', prop: 'student.specialty_name' },
    { label: '所在班级', prop: 'student.class_name' },
    {
      label: '作答用时',
      prop: 'answer_time'
    }
  ]
}
const answeringList = computed(() => {
  return competitorsTableData.value.filter((item: any) => item.commit_status == 2 || item.commit_status == 4)
})

// 选手答题情况
const listOptions = {
  columns: [
    { label: '序号', type: 'index', width: 60 },
    { label: '选手姓名', prop: 'student.name' },
    { label: '参赛ID', prop: 'login_id' },
    { label: '性别', prop: 'student.gender' },
    { label: '所在学校', prop: 'student.organ_name' },
    { label: '所在专业', prop: 'student.specialty_name' },
    { label: '所在班级', prop: 'student.class_name' },
    {
      label: '模块一',
      prop: 'module_1',
      computed({ row }: { row: any }) {
        return getModuleStatus(row, 0)
      }
    },
    {
      label: '模块二',
      prop: 'module_2',
      computed({ row }: { row: any }) {
        return getModuleStatus(row, 1)
      }
    },
    {
      label: '模块三',
      prop: 'module_3',
      computed({ row }: { row: any }) {
        return getModuleStatus(row, 2)
      }
    },
    {
      label: '模块四',
      prop: 'module_4',
      computed({ row }: { row: any }) {
        return getModuleStatus(row, 3)
      }
    },
    {
      label: '模块五',
      prop: 'module_5',
      computed({ row }: { row: any }) {
        return getModuleStatus(row, 4)
      }
    },
    {
      label: '模块六',
      prop: 'module_6',
      computed({ row }: { row: any }) {
        return getModuleStatus(row, 5)
      }
    }
  ]
}
function getModuleStatus(row: any, index: number) {
  try {
    const list = JSON.parse(row.module_status_data) || []
    const status: number = list[index].status
    if (status == 0) return '<span class="not-started">未开始</span>'
    if (status == 1) return '<span class="is-inProgress">进行中</span>'
    if (status == 2) return '<span class="is-completed3">未完成</span>'
    if (status == 3) return '<span class="is-completed2">部分完成</span>'
    if (status == 4) return '<span class="is-completed">全部完成</span>'
  } catch (error) {
    console.log(error)
  }
  return '<span class="not-started">未开始</span>'
}
</script>

<template>
  <AppCard>
    <h2 class="end-countdown">
      结束倒计时：<span>{{ countdown }}</span>
    </h2>
    <el-row justify="center">
      <el-select v-model="currentCompetition" value-key="id" size="large" style="margin-right: 20px">
        <el-option v-for="item in competitionList" :key="item.id" :value="item" :label="item.name"></el-option>
      </el-select>
      <el-select v-model="platformKey" size="large" v-if="false">
        <el-option
          v-for="item in platformKeys"
          :key="item.platform_key"
          :value="item.platform_key"
          :label="item.name"
        ></el-option>
      </el-select>
    </el-row>
    <ul class="statistics">
      <li>
        <h6>
          <span>{{ statistics.competitor_count }}</span>
          <em>人</em>
        </h6>
        <p>参赛人数</p>
      </li>
      <li>
        <h6>
          <span>{{ statistics.starting_answer_competitor_count }}</span>
          <em>人</em>
        </h6>
        <p>正在答题人数</p>
      </li>
      <li>
        <h6>
          <span>{{ statistics.complete_answer_competitor_count }}</span>
          <em>人</em>
        </h6>
        <p>已完成人数</p>
      </li>
    </ul>
    <el-row :gutter="20">
      <el-col :span="12">
        <h2 class="h2-title">已提交选手</h2>
        <AppList border v-bind="submittedListOptions" :data="submittedLis" ref="appList"></AppList
      ></el-col>
      <el-col :span="12">
        <h2 class="h2-title">正在作答选手</h2>
        <AppList border v-bind="answeringListOptions" :data="answeringList" ref="appList"></AppList
      ></el-col>
    </el-row>
    <h2 class="h2-title">选手答题情况</h2>
    <AppList border v-bind="listOptions" :data="competitorsTableData" ref="appList"></AppList>
  </AppCard>
</template>

<style lang="scss">
.statistics {
  display: flex;
  align-items: center;
  justify-content: center;
  column-gap: 140px;
  margin: 90px 0;
  li {
    width: 212px;
    height: 212px;
    background-color: rgba(247, 247, 247, 1);
    border-radius: 50%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    h6 {
      color: rgba(178, 15, 60, 1);
      span {
        font-size: 40px;
      }
      em {
        font-size: 18px;
      }
    }
    p {
      margin-top: 20px;
      font-size: 18px;
      color: rgba(96, 96, 96, 1);
    }
  }
}

.is-inProgress {
  display: inline-block;
  width: 60px;
  height: 24px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 24px;
  text-align: center;
  background-color: rgba(211, 242, 216, 1);
  color: rgba(32, 176, 48, 1);
}
.is-completed {
  display: inline-block;
  width: 60px;
  height: 24px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 24px;
  text-align: center;
  background-color: rgba(251, 219, 225, 1);
  color: rgba(171, 42, 65, 1);
}
.is-completed2 {
  display: inline-block;
  width: 60px;
  height: 24px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 24px;
  text-align: center;
  background-color: #fbf0dc;
  color: #e3983e;
}
.is-completed3 {
  display: inline-block;
  width: 60px;
  height: 24px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 24px;
  text-align: center;
  background-color: rgb(225, 239, 255);
  color: rgb(59, 146, 254);
}
.not-started {
  display: inline-block;
  width: 60px;
  height: 24px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 24px;
  text-align: center;
  color: rgba(144, 144, 144, 1);
  background-color: rgba(228, 228, 230, 1);
}
.h2-title {
  padding-left: 5px;
  font-size: 18px;
  font-weight: 500;
  line-height: 1;
  margin: 20px 0;
  border-left: 3px solid #aa1941;
}
.end-countdown {
  float: right;
  color: rgba(109, 110, 111, 1);
  font-size: 14px;
  span {
    color: rgba(65, 80, 88, 1);
    font-size: 30px;
  }
}
</style>
