<script setup lang="ts">
import LearningToday from '@/page/urge/learning/components/LearningToday.vue'
import LearningIm from '@/page/urge/learning/components/LearningIm.vue'
import LearningReport from '@/page/urge/learning/components/LearningReport.vue'
import urgeApi from '@/api/urge.ts'
import dayjs from 'dayjs'
import { useSocket } from '@/hooks'

import LearningDia from './components/LearningDia/index.vue'

const { inspectorEnd } = useSocket()

const isLoading = ref(false)
const plan = ref()

const activeClass = ref('today')
const classList = computed(() => {
  return [
    plan.value?.status === 2 ? { id: 'report', name: '督学报告' } : null,
    { id: 'today', name: '今日计划' },
    { id: 'im', name: '沟通记录' },
  ].filter(Boolean)
})

const loadPlan = async () => {
  isLoading.value = true
  try {
    const {
      data: { data: res },
    } = await urgeApi.getUserTodayInspectorPlanInfo()
    plan.value = res

    if (plan.value?.status === 2) {
      activeClass.value = 'report'
    }
  } finally {
    isLoading.value = false
  }
}

onActivated(loadPlan)

const teacher = computed(() => {
  if (!plan.value) {
    return null
  }
  const { inspectorTeacherInfo } = plan.value
  const { personalPhoto, name, qualifications: qualificationsJson } = inspectorTeacherInfo
  return {
    name,
    pic: personalPhoto,
    tags: JSON.parse(qualificationsJson).map(({ name }: { name: string }) => name),
  }
})

const students = computed(() => {
  if (!plan.value) {
    return []
  }
  return (
    plan.value.studentList?.map((item: anyObj) => ({
      id: item.id,
      avatar: item.avatarUrl,
      name: item.name,
    })) ?? []
  )
})

const now = ref(dayjs())
setInterval(() => {
  now.value = dayjs()
}, 1000)

const duration = computed(() => {
  if (!plan.value) {
    return {
      hours: 0,
      minutes: 0,
    }
  }
  const inspectorTimeStart = dayjs(plan.value.inspectorTimeStart)
  const hours = now.value.diff(inspectorTimeStart, 'hour')
  const minutes = now.value.diff(inspectorTimeStart, 'minute') % 60
  return {
    hours,
    minutes,
  }
})

const tasks: Ref<anyObj[]> = ref([])
const isTasksLoading = ref(false)
watchEffect(async () => {
  if (!plan.value) {
    return
  }
  isTasksLoading.value = true
  try {
    const {
      data: { data: res },
    } = await urgeApi.getInspectorPlanInfo(plan.value.id)
    tasks.value = res.taskList.map((task: anyObj) => {
      const {
        subjectName,
        inspectorTimeEnd,
        inspectorTimeStart,
        chapterName,
        courseTimeName,
        finishedNum = 0,
        num,
        progress,
        subjectId,
        courseTimeId,
      } = JSON.parse(task.taskInfoJson)
      return {
        id: task.id,
        subject: subjectName,
        subjectId: subjectId,
        time:
          dayjs(inspectorTimeStart).format('HH:mm') + '-' + dayjs(inspectorTimeEnd).format('HH:mm'),
        title:
          task.taskType === 0 || task.taskType === 1
            ? '观看【' + chapterName + '】章节的【' + courseTimeName + '】知识点视频'
            : task.taskType === 2
              ? 'AI精准学' + num + '次'
              : task.taskType === 3
                ? '语感练习' + num + '次'
                : '',
        mode: ['自由学', '自由学', '精准学', '语感'][task.taskType] ?? '',
        taskType: task.taskType, // 0-视频 1-章节 2-精准学 3-语感训练 4订正错
        completionRate: progress ?? 0,
        num,
        finishedNum,
        courseTimeId,
        completed: progress === 1 || (finishedNum > 1 && finishedNum === num),
      }
    })
  } finally {
    isTasksLoading.value = false
  }
})

const learningButtonText = computed(() => {
  if (tasks.value && tasks.value.length > 0) {
    const hasProgress = tasks.value.some(task => task.completionRate > 0 || task.finishedNum > 0)
    return hasProgress ? '继续学习' : '开始学习'
  }
  return '开始学习'
})

const learningDia = reactive<anyObj>({
  show: false,
})
const handleStartLearning = () => {
  // const nextUnfinishedTask = tasks.value.find(task => !task.completed);
  // if (nextUnfinishedTask) {
  //     const { subjectId, mode, courseTimeId } = nextUnfinishedTask;
  //     if (mode === '精准学') {
  //         router.push({ path: '/subject/doWork', query: { resourceType: 1, subjectId } });
  //     } else if (mode === '语感') {
  //         router.push('/subject/languageSense/sentenceSort');
  //     } else if (mode === '自由学') {
  //         router.push(
  //             `/subject/freeStudy/knowledgePoints/${subjectId}/${courseTimeId}?businessFlag=2`,
  //         );
  //     }
  // }
  // console.log('开始学习', nextUnfinishedTask);
  learningDia.show = true
  // learningDia.data = nextUnfinishedTask;
}

watch(inspectorEnd, _msg => {
  loadPlan()
})

onActivated(() => {
  activeClass.value = 'today'
})
</script>
<template>
  <div class="page">
    <div class="head">
      <div style="flex-grow: 1"></div>
      <Btn v-if="plan?.status === 1" width="272" height="80" tilt @click="handleStartLearning">{{
        learningButtonText
      }}</Btn>
      <Btn
        v-if="activeClass === 'report' && plan?.status === 2"
        width="272"
        height="80"
        tilt
        @click="$router.replace('/urge/timetable')"
        >结束督学</Btn
      >
    </div>
    <div class="content">
      <div class="content-sidebar">
        <Sidebar v-model="activeClass" :config="classList" class="left-vbar" />
      </div>
      <div class="content-main">
        <div v-if="isLoading" class="loadincontainer">
          <Icon name="global_loading" loading :size="80"></Icon>
        </div>
        <template v-else-if="plan">
          <LearningToday
            v-if="activeClass === 'today'"
            :duration="duration"
            :loading="isLoading"
            :tasks="tasks"
            :students="students"
            :teacher="teacher"
            :is-tasks-loading="isTasksLoading"
          />
          <LearningIm
            v-else-if="activeClass === 'im'"
            :readonly="plan?.status === 2"
            :plan="plan"
          />
          <LearningReport v-else-if="activeClass === 'report'" :loading="isLoading" :plan="plan" />
        </template>
      </div>
    </div>
  </div>
  <LearningDia v-model:show="learningDia.show" />
</template>
<style lang="scss" scoped>
.loadincontainer {
  position: fixed;
  left: 344px;
  right: 64px;
  top: 10.67vh;
  bottom: 0;
  display: grid;
  place-content: center;
}

.page {
  width: 100%;
  height: 100%;
  @include main_bg;
  padding-top: 10.67vh;
  position: relative;
  z-index: auto;

  .head {
    display: flex;
    padding-right: 88px;
    align-items: center;
    height: 10.67vh;
    position: absolute;
    width: 100%;
    top: 0;

    :deep(.x-button) {
      margin-left: auto;
    }
  }
}

.content {
  margin-left: 344px;
  margin-right: 64px;
}

.content-sidebar {
  width: 240px;
  flex-shrink: 0;
  position: absolute;
  left: 64px;
  top: 10.67vh;
  z-index: auto;
}

.content-main {
  flex-grow: 1;
}
</style>
