<template>
  <view class="page">
    <BackBar title="我的督学任务" :leftIcon="false">
      <wd-badge :is-dot="unreadCount > 0" :right="4" :top="2" :hidden="false">
        <image
          class="info"
          src="/src/static/tabBar/info.png"
          @click="jumpPage('/pages/inspector/chat/index')"
        ></image>
      </wd-badge>
    </BackBar>
    <view class="content">
      <view class="card flex-bt">
        <view class="card-left"
          ><wd-icon
            v-if="currentDateIndex > 0"
            name="arrow-left"
            size="30rpx"
            @click="changeDay('prev')"
          ></wd-icon
          >{{ currentDate
          }}<wd-icon
            v-if="currentDateIndex < calendarData.length - 1"
            name="arrow-right"
            size="30rpx"
            @click="changeDay('next')"
          ></wd-icon
        ></view>
        <view class="card-right" @click="showList = !showList">
          <view v-if="showList">
            <text>列表</text>
            <wd-icon name="bulletpoint" size="30rpx"></wd-icon>
          </view>
          <view v-else class="calendar-view">
            <text>日历</text>
            <svg-calendar-icon />
          </view>
        </view>
      </view>
      <CusCalender v-if="showList" :selectedDay="currentDate" :showHeader="false">
        <template #cell="{ date }">
          <view v-for="d of calendarData" :key="d.courseDate" @click="selectedDay(d)">
            <view v-if="d.courseDate === date.date" class="state-group">
              <view class="mode">{{ d.mode === 1 ? '1v1' : '1vN' }}服务</view>
              <view class="mode">{{ d.userCount }}人</view>
              <view :class="['plan', stateCorlo[d.state]]">{{ stateName[d.state] }}</view>
            </view>
          </view>
        </template>
      </CusCalender>
      <view v-if="!showList" class="card">
        <view v-if="noPlan" class="tips-box">
          <wd-icon name="error-circle-filled" size="30rpx"></wd-icon>
          <text>请前往学员详情提前发布学习计划</text>
        </view>
        <view class="cell">
          <text class="cell-label">督学模式:</text>
          <text class="cell-value">{{ courseData.mode === 1 ? '1v1' : '1vN' }}服务</text>
        </view>
        <view class="cell">
          <text class="cell-label">督学时间:</text>
          <text class="cell-value"
            >{{ dayjs(courseData.courseDate).format('M月DD日') }}&nbsp;{{
              dayjs(courseData.courseStartDate).format('HH:mm')
            }}-{{ dayjs(courseData.courseEndDate).format('HH:mm') }}</text
          >
          <text v-if="courseData.planState > 0" :class="['tag', tagColor[courseData.planState]]">{{
            courseData.planState === 1 ? '进行中' : '已结束'
          }}</text>
        </view>
        <view class="cell">
          <text class="cell-label">督学人数:</text>
          <text class="cell-value">{{ studentList.length }}人</text>
        </view>
      </view>
      <view v-if="!showList" class="card">
        <view
          v-for="item of studentList"
          :key="item.id"
          class="list-item flex-bt"
          @click="studentDetail(item)"
        >
          <view class="list-left">
            <wd-img width="80rpx" height="80rpx" round :src="getAvatarUrl(item.avatarUrl)" />
            <text class="stu-name">{{ item.name }}</text>
            <text :class="['tag', item.isOnline ? 'onlin-tag' : 'offline-tag']">{{
              item.isOnline ? '在线' : '离线'
            }}</text>
          </view>
          <view class="list-right">
            <text :class="item.planNum ? 'plan' : 'no-plan'">{{ item.planNum }}个学习计划</text>
          </view>
        </view>
      </view>
    </view>
    <view v-if="!showList" class="footer">
      <button v-if="courseData.planState === 0" class="footer-btn" @click="startSubmit">
        开始督学
      </button>
      <button
        v-if="courseData.planState === 1"
        class="primary-btn"
        @click="jumpPage('/pages/inspector/schedule/condition')"
      >
        督学时况
      </button>
      <button
        v-if="courseData.planState === 1"
        :class="{ 'col-btn': true, disabled: !endDX }"
        :disabled="!endDX"
        @click="endSubmit"
      >
        <text class="btn-text">{{ endDX ? '结束督学' : '督学中' }}</text>
        <text v-if="courseData.planState === 1" class="timer"> {{ time }}</text>
      </button>
    </view>
    <isp-menu current-menu="schedule" />
    <!-- 提示 -->
    <DuxueTipsModal
      :show="showTipsModal"
      :titleText="titleText"
      :content="modalContent"
      :cancel="() => (showTipsModal = false)"
      :canContinue="!noPlan"
      @confirm="confirmModal"
    />
  </view>
</template>
<script setup lang="ts">
import dayjs from 'dayjs';
import { onShow } from '@dcloudio/uni-app';
import { computed, onMounted, ref, watch, onUnmounted } from 'vue';
import DuxueTipsModal from './components/duxueTipsModal.vue';
import CusCalender from '@/components/customCalender/index.vue';

import { useSocket } from '@/hooks/useSocket';
import {
  endInpector,
  getCourseDate,
  getScheduleList,
  getUnreadCount,
  startInpector,
} from '@/api/modules/inspector';
import { getAvatarUrl, setCache } from '@/utils';

const { init: socketInit, sendMsg, inspectorMessage } = useSocket();
const OSS_URL = import.meta.env.VITE_OSS_HOST;

const showTipsModal = ref(false);
const calendarData = ref<any[]>([]);
const titleText = ref('');
const unreadCount = ref(0);
const modalContent = ref('');
const courseData = ref<any>({}); // 课表学生列表
const currentDate = ref(dayjs().format('YYYY-MM-DD'));
const today = ref(dayjs().format('YYYY-MM-DD'));
const currentDateIndex = ref(0); // 当前时间在日历表中的下标
const inspectorTimeStart = ref<string>(); // 督学开始时间
const time = ref<string>('');
const studentList = ref<any[]>([]);
const tagColor = {
  1: 'green',
  2: 'grey',
};
const stateCorlo = {
  0: 'plan',
  1: 'green',
  2: 'grey',
  3: 'grey',
};
const stateName = {
  '-1': '待发计划',
  0: '待开课',
  1: '督学中',
  2: '已督学',
  3: '已过期',
};
const currentType = ref('');
const showList = ref(false);
// 日期判断是否可以开始督学
const canStart = () => {
  return (
    today.value === currentDate.value &&
    new Date().getTime() >= new Date(courseData.value.courseStartDate).getTime() - 30 * 1000 * 60
  );
};
// 是否可以结束督学
const endDX = ref(false);
let timer: any;
const endCount = () => {
  let duration = new Date().getTime() - new Date(inspectorTimeStart.value).getTime();
  const hours = Math.floor(duration / 3600000);
  const minutes = Math.floor((duration % 3600000) / 60000);
  const seconds = Math.floor((duration % 60000) / 1000);
  time.value = `${hours.toString().padStart(2, '0')}:${minutes
    .toString()
    .padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
};
const canEnd = () => {
  endCount();
  clearInterval(timer);
  if (inspectorTimeStart.value) {
    timer = setInterval(() => {
      endCount();
      endDX.value =
        today.value === currentDate.value &&
        new Date().getTime() > new Date(courseData.value.courseEndDate).getTime();
    }, 1000);
  }
};
// 学员有无计划判断是否可以督学
const noPlan = computed(() => {
  let flag = false;
  studentList.value.forEach(e => {
    if (!e.planNum) {
      flag = true;
    }
  });
  return flag;
});
// 开始督学
function startSubmit() {
  if (noPlan.value) {
    titleText.value = '无法开始督学';
    modalContent.value = '存在学员没有学习计划，请发布学习计划后再开始督学！';
    currentType.value = 'none';
  } else {
    titleText.value = '温馨提示';
    modalContent.value = '确定开始督学？';
    currentType.value = 'start';
  }
  showTipsModal.value = true;
}
// 结束督学
function endSubmit() {
  titleText.value = '温馨提示';
  modalContent.value = '确认结束督学';
  currentType.value = 'end';
  showTipsModal.value = true;
}
// 结束确认
const confirmEnd = async () => {
  try {
    uni.showLoading({ title: '请稍后...' });
    const { code } = await endInpector({ courseDate: currentDate.value });
    uni.hideLoading();
    if (code === 200) {
      uni.showToast({
        title: '结束督学成功',
      });
      sendMsg({
        type: 'inspectorEnd',
        msg: {
          receiverIds: studentList.value.map(item => item.id),
        },
      });
      showTipsModal.value = false;
      getDate(currentDate.value);
    }
  } catch (error) {
    uni.hideLoading();
  }
};
// 督学确认开始
const confirmStart = async () => {
  showTipsModal.value = false;
  if (!canStart()) {
    uni.showToast({
      title: '最多提前30分钟开始督学',
      icon: 'none',
    });
    return;
  }
  try {
    uni.showLoading({ title: '请稍后...' });
    const { code } = await startInpector({ courseDate: currentDate.value });
    uni.hideLoading();
    if (code === 200) {
      sendMsg({
        type: 'inspectorStart',
        msg: {
          receiverIds: studentList.value.map(item => item.id),
          courseDate: currentDate.value,
        },
      });
      uni.showToast({
        title: '开始督学成功',
      });
      getDate(currentDate.value);
    }
  } catch (error) {
    uni.hideLoading();
  }
};
const confirmModal = () => {
  if (currentType.value === 'start') {
    confirmStart();
  } else if (currentType.value === 'end') {
    confirmEnd();
  }
};
// 选择的日期
function selectedDay(date: any) {
  currentDate.value = date.courseDate;
  getDate(currentDate.value);
  showList.value = false;
}
// 学生详情
const studentDetail = (_student: any) => {
  setCache('student_detail', {
    orderId: _student.orderId,
    courseDate: currentDate.value,
    backType: 1,
  });
  uni.navigateTo({
    url: `/pages/inspector/student-detail/index?orderId=${_student.orderId}&courseDate=${currentDate.value}`,
  });
};
// 跳转
function jumpPage(path: string) {
  uni.setStorageSync('courseDate', currentDate.value);
  uni.navigateTo({
    url: path,
  });
}
// 点击命中下一个日期
function changeDay(type: string) {
  switch (type) {
    case 'prev':
      if (currentDateIndex.value > 0) {
        currentDate.value = calendarData.value[currentDateIndex.value - 1].courseDate;
      }
      break;
    case 'next':
      if (currentDateIndex.value < calendarData.value.length - 1)
        currentDate.value = calendarData.value[currentDateIndex.value + 1].courseDate;

      break;
  }
  currentDateIndex.value = calendarData.value.findIndex(e => e.courseDate === currentDate.value);
  getDate(currentDate.value);
}
// 获取课表时间
async function getDate(date?: string) {
  uni.showLoading({ title: '加载中...' });
  try {
    const { code, data, message } = await getCourseDate({ date });
    if (code === 200) {
      currentDate.value =
        dayjs(data.courseDate).format('YYYY-MM-DD') || dayjs().format('YYYY-MM-DD');
      courseData.value = data || {};
      currentDateIndex.value = calendarData.value.findIndex(
        e => e.courseDate === currentDate.value,
      );
      inspectorTimeStart.value = data.inspectorTimeStart ? data.inspectorTimeStart : '';
      studentList.value = data.studentDetails || [];
      if (data.planState === 1) {
        canEnd();
      }
    }
  } catch (e) {
  } finally {
    uni.hideLoading();
  }
}
// 获取课表信息
async function getList() {
  try {
    uni.showLoading({ title: '加载中...' });
    const { code, data, message } = await getScheduleList();
    if (code === 200) {
      calendarData.value = data || [];
    } else {
      uni.showToast({ title: message, icon: 'none' });
    }
    uni.hideLoading();
  } catch (error) {
    uni.hideLoading();
  }
}
// 获取我的未读消息
async function getMyUnreadCount() {
  const { code, data } = await getUnreadCount();
  if (code === 200) {
    unreadCount.value = data;
  }
}
watch(inspectorMessage, msg => {
  if (!msg) return;
  unreadCount.value++;
});
onMounted(async () => {
  socketInit();

  await getList();
  getDate();
});
onUnmounted(() => {
  clearInterval(timer);
});
onShow(() => {
  getMyUnreadCount();
});
</script>
<style lang="scss" scoped>
.page {
  padding: 0 30rpx;
  box-sizing: border-box;
  height: 100vh;

  .content {
    height: calc(100vh - 310rpx);
    overflow: hidden;
    overflow-y: auto;
  }
  .info {
    width: 48rpx;
    height: 48rpx;
  }
  .flex-bt {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .card {
    margin: 30rpx 0;
    padding: 30rpx;
    box-sizing: border-box;
    border-radius: 20rpx;
    background: #fff;
    .card-left {
      .wd-icon {
        color: #a9aab5;
      }
    }
    .card-right {
      display: flex;
      align-items: center;
      font-size: 30rpx;
      color: #666;
      .wd-icon {
        margin-left: 10rpx;
      }
      .calendar-view {
        > svg {
          width: 30rpx;
          height: 30rpx;
          margin-left: 10rpx;
          vertical-align: -12%;
        }
      }
    }
    .tips-box {
      display: flex;
      padding: 8rpx;
      align-items: center;
      justify-content: center;
      font-size: 24rpx;
      color: #ff2828;
      line-height: 36rpx;
      gap: 10rpx;
      align-self: stretch;
      border-radius: 10px;
      background: linear-gradient(90deg, #ffeded 0%, #fff6f6 100%);
      margin-bottom: 20rpx;
    }
    .cell {
      font-size: 30rpx;
      line-height: 45rpx;
      .cell-label {
        color: #a9aab5;
        display: inline-block;
        width: 150rpx;
      }
      .cell-vlaue {
        color: #0a1f13;
      }
      .tag {
        font-size: 22rpx;
        line-height: 30rpx;
        padding: 0 10rpx;
        box-sizing: border-box;
        border-radius: 6rpx;
        border: 1rpx solid;
        margin-left: 10rpx;
      }
      .green {
        color: #21d17a;
        border-color: #21d17a;
      }
      .grey {
        color: #ccc;
        border-color: #ccc;
      }
    }
    .list-item {
      font-size: 30rpx;
      .list-left {
        display: flex;
        align-items: center;
        .stu-name {
          color: #000;
          font-size: 30rpx;
          margin: 0 20rpx;
        }
        .tag {
          font-size: 22rpx;
          padding: 0 10rpx;
          line-height: 30rpx;
          box-sizing: border-box;
          border-radius: 6rpx;
        }
        .onlin-tag {
          color: #21d17a;
          border: 1rpx solid #21d17a;
        }
        .offline-tag {
          color: #ccc;
          border: 1rpx solid #ccc;
        }
      }
      .list-right {
        .plan {
          color: #21d17a;
        }
        .no-plan {
          color: #ff2828;
        }
      }
    }
    .list-item:not(:last-child) {
      border-bottom: 1rpx solid #f6f6f6;
      padding-bottom: 20rpx;
      margin-bottom: 20rpx;
    }
  }
  .footer {
    width: 100vw;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: fixed;
    padding: 0 30rpx;
    box-sizing: border-box;
    bottom: 102rpx;
    // bottom: 120rpx;

    .primary-btn {
      width: 335rpx;
      height: 90rpx;
      margin-right: 20rpx;
      line-height: 90rpx;
      background: #615dff;
      color: #fff;
      font-weight: 500;
      font-size: 30rpx;
    }
    .col-btn {
      width: 335rpx;
      height: 90rpx;
      background: #615dff;
      color: #fff;
      display: flex;
      flex-direction: column;
      justify-content: center;
      .btn-text {
        line-height: 40rpx;
        font-size: 30rpx;
      }
      .timer {
        font-size: 22rpx;
        color: #fff;
        line-height: 30rpx;
      }
    }
    .disabled {
      background: #e2e2e7;
      color: #b6b7c1;
      .timer {
        color: #b6b7c1;
      }
    }
  }
  .footer-btn {
    width: 690rpx;
    height: 90rpx;
    border-radius: 20rpx;
    background: #615dff;
    color: #fff;
    font-size: 30rpx;
    font-weight: 500;
    line-height: 90rpx;
    margin: 0 auto;
  }
}
.state-group {
  width: 100%;
  font-size: 20rpx;
  .mode {
    color: #666;
    line-height: 32rpx;
  }
  .plan {
    color: #ff8d5f;
    line-height: 32rpx;
  }
  .green {
    color: #21d17a;
  }
  .grey {
    color: #ccc;
  }
}
</style>
