<template>
  <view class="course-table">
    <wd-skeleton animation="gradient" theme="paragraph" v-if="isLoading" />
    <template v-else>
      <time-cycle :list="timeCycleList" @change="timeCycleChange" />

      <supervisor-teacher :teacher="teacher"/>

      <classmates :classmates="classmateList" v-if="classmateList.length"/>

      <custom-calender ref="customCalenderRef" @selected-day="selectedDay">
        <template #header="{date}">
          <view class="header">
            <wd-icon name="arrow-left" size="22px" @click="prevTime"></wd-icon>
            <view>{{date.monthDate}}</view>
            <wd-icon name="arrow-right" size="22px" v-if="show(date)" @click="nextTime"></wd-icon>
          </view>
        </template>
        <template #cell="{date}">
          <course-table-cell :list="list" :date="{value: date?.date, disable: date?.disable}"/>
        </template>
      </custom-calender>
    </template>
  </view>
</template>

<script setup lang=ts>
import TimeCycle from "./TimeCycle.vue";
import SupervisorTeacher from "@/components/SupervisorTeacher/SupervisorTeacher.vue";
import Classmates from "./Classmates.vue";
import CustomCalender from "@/components/customCalender/index.vue"
import {ref} from "vue";
import dayjs from "dayjs";
import {onLoad, onUnload} from "@dcloudio/uni-app";
import {getInspectorCourseList, getInspectorTeacherStudentInfo} from "@/api";
import CourseTableCell from "./CourseTableCell.vue";

const OSS_URL = import.meta.env.VITE_OSS_HOST;
const currentTime = ref(null);

const customCalenderRef = ref(null)

const teacher = ref<{
  name: string;
  school: string;
  edu: string;
  avatar: string;
  labelList: {
    name: string;
    color: string;
    bgColor: string;
  }[];
  titleLabel: string[];
  desc: string;
}|null>(null)
const classmateList = ref([])

const colorList = [
  {color: '#FF8624', bgColor: "#fff7f0"},
  {color: '#0CC25C', bgColor: "#F1FFF7"},
  {color: '#FF3C58', bgColor: "#FFF3F5"}
]

const loadTeacherAndClassmate = (id: string) => {
  getInspectorTeacherStudentInfo({orderId: id}).then(({data}) => {
    const teacherData = data.inspectorTeacher
    teacher.value = teacherData ? {
      name: teacherData.nickName,
      school: teacherData.gradSchool,
      edu: teacherData.degree,
      avatar: teacherData.personalPhoto,
      labelList: teacherData.label.split(",").map((item, index) => {
        let color = colorList[index % 3]
        return {
          name: item,
          color: color.color,
          bgColor: color.bgColor
        }
      }),
      titleLabel: teacherData.propagandaSlogan?.split(","),
      desc: teacherData.personalInformation
    } : null
    classmateList.value = (data.studentList || []).map(item => {
      return {
        name: item.name,
        avatar: item.avatarUrl
      }
    })
  })
}

const timeCycleChange = (time: {start: string, end: string}) => {
  currentTime.value = time;
  if (time && timeCycleMap.value[`${time.start}-${time.end}`]) {
    loadTeacherAndClassmate(timeCycleMap.value[`${time.start}-${time.end}`].orderId)
  }
}

const list = ref([])

const show = (date: {
  date: string,
  monthDate: string
}) => {
  return true
  // return dayjs(date.date).month() < dayjs().month()
}

const prevTime = () => {
  customCalenderRef.value.prevMonth()
}
const nextTime = () => {
  customCalenderRef.value.nextMonth()
}

const planMap = ref([])
const selectedDay = (date: {date: string}) => {
  let dayData = planMap.value.find(item => item.date === date.date)
  if (dayData && dayData.id) {
    uni.navigateTo({
      url: `/pages/parents/mySupervisionService/studyPlan?d=${date.date}&i=${dayData.id}`,
    })
  }
}

const timeCycleList = ref([])

const timeCycleMap = ref({})

const isLoading = ref(true)

onLoad((options) => {

  getInspectorCourseList({userId: options.id}).then(({data}) => {
    let planList = []
    data.forEach(item => {
      timeCycleList.value.push({
        start: item.inspectorTimeStart,
        end: item.inspectorTimeEnd,
      })
      timeCycleMap.value[`${item.inspectorTimeStart}-${item.inspectorTimeEnd}`] = item
      planList.push(item.inspectorCourseList.map(i => {
        let date = dayjs(i.courseDate).format("YYYY-MM-DD")
        if (i.inspectorPlanId) {
          planMap.value.push({
            date: date,
            id: i.inspectorPlanId
          })
        }
        return {
          date: date,
          info: {
            taskCount: i.taskCount,
            state: i.planStatus,
            mode: i.mode,
          }
        }
      }))
    })
    list.value = planList.flat(1)
    uni.setStorageSync('plan', planMap.value)
  }).catch(() => {
    uni.removeStorageSync('plan')
  }).finally(() => {
    isLoading.value = false
  })
})

onUnload(() => {
  uni.removeStorageSync('plan')
})
</script>

<style scoped lang="scss">
.course-table {
  padding-bottom: 122rpx;
  .header {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10rpx 0 30rpx 0;
  }
  .cell-date {

  }
}
</style>
