<script setup lang="ts">
import { watchEffect } from 'vue'
import Card from '@/page/urge/components/Card.vue'
import dayjs from 'dayjs'
import StatCard from '@/page/urge/components/StatCard.vue'
import urgeApi from '@/api/urge.ts'

const props = defineProps<{
  reports: anyObj[]
  stats: anyObj
}>()

const emit = defineEmits(['selectReport'])

const closedDays = computed(() => props.reports.map(report => report.day))
const dayToInspectorCourseIdMap = computed(() => {
  const map = new Map()
  props.reports.forEach(report => {
    map.set(report.day, report)
  })
  return map
})

const historyStatTime = computed(() => {
  const minutes = props.stats?.inspectorTimeMinute
  if (!minutes) {
    return null
  }
  return {
    hours: Math.floor(minutes / 60),
    minutes: minutes % 60,
  }
})

const lastClosedDay = computed(() => closedDays.value[closedDays.value.length - 1])
const firstClosedDay = computed(() => closedDays.value[0])

const selectedDay = ref()
watchEffect(() => {
  selectedDay.value = lastClosedDay.value
  emit('selectReport', dayToInspectorCourseIdMap.value.get(lastClosedDay.value))
})

function handleSelectDay(day: string) {
  if (closedDays.value.includes(day)) {
    selectedDay.value = day
    emit('selectReport', dayToInspectorCourseIdMap.value.get(day))
  }
}

const isTeacherLoading = ref(false)
const teacher = ref()
watch(
  selectedDay,
  async day => {
    isTeacherLoading.value = true
    try {
      const report = dayToInspectorCourseIdMap.value.get(day)
      const {
        data: { data: res },
      } = await urgeApi.getInspectorTeacherStudentInfoByInspectorCourseId(report.inspectorCourseId)
      const {
        personalInformation,
        qualifications: qualificationsJson,
        name,
        gradSchool,
        personalPhoto,
        propagandaSlogan,
        degree,
      } = res.inspectorTeacher
      let qualifications = []
      try {
        qualifications = JSON.parse(qualificationsJson)
      } catch (e) {
        console.error(e)
      }
      teacher.value = {
        name,
        education: gradSchool + ' / ' + degree,
        pic: personalPhoto,
        intro: propagandaSlogan,
        tags: qualifications.map(({ name }: { name: string }) => name),
        content: [personalInformation],
      }
    } finally {
      isTeacherLoading.value = false
    }
  },
  {
    immediate: true,
  },
)

const activeMonth = ref(new Date())
watchEffect(() => {
  activeMonth.value = dayjs(lastClosedDay.value).toDate()
})

const calendarHeight = computed(() => {
  const firstDay = dayjs(activeMonth.value).startOf('month')
  const totalDays = firstDay.daysInMonth()
  let startDayOfWeek = firstDay.day() - 1
  if (startDayOfWeek === -1) startDayOfWeek = 6
  const totalRows = Math.ceil((totalDays + startDayOfWeek) / 7)
  const pxValue = totalRows >= 6 ? 67.714285 : 79
  return (pxValue / 1200) * window.innerHeight + 'px'
})

const prevMonthVisible = computed(() => {
  return dayjs(firstClosedDay.value)
    .startOf('month')
    .isBefore(dayjs(activeMonth.value).startOf('month'))
})

const nextMonthVisible = computed(() => {
  return dayjs(lastClosedDay.value)
    .startOf('month')
    .isAfter(dayjs(activeMonth.value).startOf('month'))
})

function changeMonth(offset: number) {
  activeMonth.value = new Date(
    activeMonth.value.getFullYear(),
    activeMonth.value.getMonth() + offset,
  )
}
</script>

<template>
  <Card>
    <div class="stats">
      <StatCard title="已学视频">
        <span class="stat-value">{{ stats?.studyVideoCount ?? '--' }}</span> 个
      </StatCard>
      <StatCard title="练习题数">
        <span class="stat-value">{{ stats?.exercisesCount ?? '--' }}</span> 道
      </StatCard>
      <StatCard title="督学次数">
        <span class="stat-value">{{ stats?.inspectorCount ?? '--' }}</span> 次
      </StatCard>
      <StatCard title="督学总时长">
        <template v-if="historyStatTime?.hours && historyStatTime.hours > 0"
          ><span class="stat-value">{{ historyStatTime?.hours ?? '--' }}</span> 时
        </template>
        <span class="stat-value">{{ historyStatTime?.minutes ?? '--' }}</span> 分
      </StatCard>
    </div>
  </Card>
  <div class="calendar-and-teacher">
    <div class="calendar">
      <div class="calendar-header">
        <div class="month-navigation">
          <button
            v-if="prevMonthVisible"
            class="prev-month"
            @click="() => changeMonth(-1)"
          ></button>
          <span class="month-title">{{ activeMonth.getMonth() + 1 }}月</span>
          <button v-if="nextMonthVisible" class="next-month" @click="() => changeMonth(1)"></button>
        </div>
      </div>
      <div class="calendar-body">
        <el-calendar v-model="activeMonth" class="calendar-table">
          <template #header>
            <div></div>
          </template>
          <template #date-cell="{ data }">
            <div
              :class="[
                'calendar-day',
                {
                  closed: closedDays.includes(data.day),
                  selected: selectedDay === data.day,
                },
              ]"
              @click="handleSelectDay(data.day)"
            >
              {{ data.date.getDate() }}
            </div>
          </template>
        </el-calendar>
        <div class="calendar-legend">
          <span class="legend-item pending">选中</span>
          <span class="legend-item closed">已上课</span>
        </div>
      </div>
    </div>
    <Card class="teacher">
      <div v-if="isTeacherLoading" class="loadincontainer">
        <Icon name="global_loading" loading :size="80"></Icon>
      </div>
      <template v-if="teacher">
        <div class="card-pic">
          <img :src="teacher.pic" :alt="teacher.name" />
        </div>
        <div class="card-body">
          <div class="card-body-base">
            <div class="card-title">
              <h2>{{ teacher.name }}</h2>
              <div class="card-tags">
                <span v-for="(tag, index) in teacher.tags" :key="index" class="card-tag">{{
                  tag
                }}</span>
              </div>
              <span class="card-education">{{ teacher.education }}</span>
            </div>
            <div class="card-intro">{{ teacher.intro }}</div>
          </div>
          <div class="card-detail">
            <p v-for="(content, index) in teacher.content" :key="index">
              {{ content }}
            </p>
          </div>
        </div>
      </template>
    </Card>
  </div>
</template>

<style scoped lang="scss">
.loadincontainer {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: grid;
  place-content: center;
}

.stats {
  border-radius: 1.67vh;
  display: flex;
  padding: 1.33vh;
  justify-content: space-between;
}

.calendar-and-teacher {
  margin-top: 6.67vh;
  display: flex;
  justify-content: space-between;
}

.calendar {
  width: 728px;
  height: 542px + 80px;
  border-radius: 1.33vh;
  overflow: hidden;
  background: #fff;
  filter: drop-shadow(0px 4px 4px rgba(0, 0, 0, 0.25));
}

/* ================== calendar ================== */
.calendar-day {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  &.closed {
    background: #fff78c;
  }

  &.selected {
    background: #c4b5ff;
  }

  &.start-day {
    &:after {
      font-family: OPPOSans, sans-serif;
      content: '开课时间';
      color: #fff;
      text-align: center;
      font-size: 1.33vh;
      line-height: 2vh;
      position: absolute;
      top: 0;
    }
  }
}

.calendar {
  :deep(.el-calendar__header) {
    display: none;
  }

  :deep(.el-calendar__body) {
    padding: 0;

    table {
      table-layout: auto;
    }

    th {
      background: #ece5ff;
    }

    th,
    td {
      border: none;
    }

    th,
    .el-calendar-day {
      position: relative;
      padding: 0;
      height: v-bind(calendarHeight);
    }

    .prev,
    .next {
      .calendar-day {
        color: #ccc;
        background: #fafafa;
      }
    }

    .el-calendar-day,
    .el-calendar-day:hover {
      background: transparent;
    }

    .is-selected,
    .is-selected:hover {
      background: transparent;
    }

    th {
      color: $font-color;
      font-family: $font-special, sans-serif;
      font-size: 2vh;
      line-height: 3vh;
    }

    .el-calendar-day {
      color: $font-color;
      font-family: $font-special, sans-serif;
      font-size: 2.33vh;
      line-height: 3.5vh;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    tr {
      position: relative;
    }

    tr::after {
      content: '';
      position: absolute;
      height: 0.17vh;
      top: 0;
      width: 100%;
      left: 0;
      background: repeating-linear-gradient(
        to right,
        #cfc8e3,
        #cfc8e3 8px,
        transparent 8px,
        transparent 16px
      );
    }

    th,
    td {
      position: relative;

      &:not(:last-child):after {
        z-index: 1;
        content: '';
        position: absolute;
        height: 100%;
        bottom: 0;
        right: 0;
        width: 2px;
        background: repeating-linear-gradient(
          to bottom,
          #cfc8e3,
          #cfc8e3 8px,
          transparent 8px,
          transparent 16px
        );
      }
    }
  }
}

.calendar-table {
  height: 39.5vh;
  overflow: auto;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 0 0 1.33vh 1.33vh;
}

.calendar-header {
  height: 6.67vh;
  color: $font-color;
  text-align: center;
  font-family: $font-special, sans-serif;
  font-size: 3.33vh;
  font-style: normal;
  font-weight: 400;
  line-height: 5vh;

  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 0 24px 0 24px;

  background:
    url('../assets/bg-mesh.svg') left bottom,
    linear-gradient(269deg, #adadff 2.25%, #cab5ff 51.93%, #8f9df7 99.65%);

  text-shadow:
    -2px -2px 0 #fff,
    2px -2px 0 #fff,
    -2px 2px 0 #fff,
    2px 2px 0 #fff,
    0px 4px 2px rgba(0, 0, 0, 0.25);
}

.calendar-legend {
  display: flex;
  justify-content: center;
  height: 5.67vh;
  align-items: center;

  color: $font-color;
  font-family: $font-special, sans-serif;
  font-size: 2vh;
  font-style: normal;
  font-weight: 400;
  line-height: 3vh;

  .legend-item {
    border-radius: 2.75vh;
    display: flex;
    align-items: center;

    + .legend-item {
      margin-left: 72px;
    }

    &:before {
      content: ' ';
      display: inline-block;
      width: 56px;
      height: 2vh;
      border-radius: 2.67vh;
      margin-right: 16px;
      box-shadow: 0 0.17vh 0.17vh 0 rgba(0, 0, 0, 0.25);
    }

    &.pending:before {
      background: #c4b5ff;
    }

    &.closed:before {
      background: #fff78c;
    }

    &.today:before {
      background: #92fc90;
    }
  }
}

.month-navigation {
  display: flex;
  align-items: center;
  column-gap: 16px;

  button {
    background: url('../assets/nav-prev.svg') no-repeat center;
    background-size: 100%;
    width: 48px;
    height: 4vh;

    &.next-month {
      background-image: url('../assets/nav-next.svg');
    }
  }
}

/* ============== teacher ============== */
.teacher {
  width: 754px;
}

.card-body-base {
  height: 23.17vh;
  overflow: auto;
  padding-left: 294px;
}

.card-title {
  display: flex;
  flex-wrap: wrap;
  align-items: center;

  &:after {
    display: block;
    content: ' ';
    height: 0.17vh;
    width: 100%;
    background: repeating-linear-gradient(
      to right,
      #ccc,
      #ccc 10px,
      transparent 10px,
      transparent 20px
    );
    margin: 1.33vh 0;
  }

  .card-tags {
    margin-top: 0.33vh;
    margin-left: 8px;
  }

  .card-tag {
    border-radius: 0.83vh;
    background: #92fc90;
    padding: 0.33vh 24px;

    color: $font-color;
    font-size: 2.17vh;
    line-height: 3.33vh;

    + .card-tag {
      margin-left: 8px;
    }
  }

  h2 {
    font-size: 3.33vh;
    color: $font-color;
    font-family: $font-special, serif;
    font-weight: 400;
    line-height: 5vh;
    display: flex;
    align-items: center;

    & + .card-education {
      margin-left: $space-2;
    }
  }

  .card-education {
    color: #666;
    font-family: OPPOSans, Arial, sans-serif;
    font-size: 2vh;
    font-weight: 400;
    line-height: 3vh;
    margin-top: 0.67vh;
  }
}

.card-pic {
  position: absolute;
  left: 24px;
  top: 2vh;
  background: linear-gradient(4deg, #b3ffd8 8.53%, #e3ffd3 84.26%);
  border: 0.33vh solid $font-color;
  border-radius: 50%;
  overflow: hidden;
  width: 246px;
  height: 20.5vh;
  z-index: 1;

  img {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.card-body {
  border-radius: 1.33vh;
  background: linear-gradient(180deg, #fafafa 0%, #f4f0fa 100%);

  padding: 2vh 32px 2.67vh 0;
  position: relative;
  overflow: auto;

  &::after {
    content: ' ';
    display: block;
    width: 410px;
    height: 30.08vh;
    background: url('../assets/hole-purple.svg') no-repeat right bottom;
    background-size: 50%;
    position: fixed;
    right: 0;
    bottom: 0;
    pointer-events: none;
  }

  p {
    color: #666;
    font-size: 2vh;
    font-style: normal;
    font-weight: 400;
    line-height: 3.5vh;
    display: flex;
    margin-top: $space-2_h;

    &::before {
      display: block;
      content: ' ';
      width: 40px;
      flex-shrink: 0;
      height: 3.33vh;
      background: url('../assets/leaf.svg') center no-repeat;
      background-size: 100%;
      margin-right: $space-2;
    }
  }
}

.card-intro {
  color: $font-color;
  font-size: 2.67vh;
  line-height: 4vh;
}

.card-detail {
  padding-left: 24px;
  height: 22.67vh;
  overflow: auto;
}

h2,
h3 {
  font-weight: 400;

  .title-outline {
    line-height: normal;
  }
}
</style>
