<template>
  <view class="page">
    <BackBar title="督学时况">
      <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 v-for="item of list" :key="item.id" class="card">
        <view class="card-top">
          <view class="communication-tag" @click="chat(item)">发起沟通</view>
          <view class="scren-img">
            <wd-img
              width="292rpx"
              height="182rpx"
              :src="item.deskUrl ? item.deskUrl : 'https://www.123.com/a.jpg'"
            >
              <template #error>
                <view class="error-wrap">
                  <wd-icon name="error-circle-filled" size="32rpx"></wd-icon>
                  账号离线
                </view>
              </template>
              <template #loading>
                <view class="loading-wrap">
                  <wd-loading />
                </view>
              </template>
            </wd-img>
          </view>
          <view class="card-top-right">
            <view class="name">{{ item.username }}</view>
            <view class="cell"
              >已学:<text class="text-grren">{{ item.studyVideoCount }}</text
              >个视频</view
            >
            <view class="cell"
              >已练:<text class="text-grren">{{ item.exercisesCount }}</text
              >道题</view
            >
            <view class="cell">
              正确率:<text class="text-grren">
                {{ +((item.correctness || 0) / 100).toFixed(2) }} %
              </text>
            </view>
          </view>
        </view>
        <view class="card-content">
          <view v-for="(sub, index) of item.tasks" :key="index">
            <view v-if="item.fold ? index === 0 : true" class="card-item">
              <wd-img
                v-if="
                  ([0].includes(sub.taskType) && Number(sub.progress) > 0.8) ||
                  (sub.finishedNum === sub.num && [1, 2, 3, 4].includes(sub.taskType))
                "
                width="46rpx"
                height="46rpx"
                :src="selectionIcon"
              ></wd-img>
              <view v-else class="index">{{ padZero(index + 1) }}</view>
              <view class="item-content">
                <view class="subject-top">
                  <view class="left">
                    <text class="subject-name">{{ sub.subjectName }}</text>
                    <text :class="['tag', tagClass[sub.taskType]]">{{
                      tagName[sub.taskType]
                    }}</text>
                  </view>
                  <view class="right">
                    <text
                      v-if="[0].includes(sub.taskType)"
                      :class="['rate', sub.progress > 0.8 ? 'finished' : 'unfinished']"
                      >{{ sub.progress > 0.8 ? '1/1' : '0/1' }}</text
                    >
                    <text
                      v-else
                      :class="['rate', sub.finishedNum >= sub.num ? 'finished' : 'unfinished']"
                      >{{ sub.finishedNum }}/ {{ sub.num }}</text
                    >
                    <text class="date"
                      >{{ timeFormat(sub.inspectorTimeStart) }} -
                      {{ timeFormat(sub.inspectorTimeEnd) }}</text
                    >
                  </view>
                </view>
                <view v-if="sub.taskType === 0" class="subject-detail"
                  >观看学习视频：《{{ sub.chapterName }}》<text v-if="sub.courseTimeName"
                    >《{{ sub.courseTimeName }}》的视频</text
                  >
                </view>
                <view v-if="sub.taskType === 1" class="subject-detail"
                  >完成章节练习{{ sub.num }}次
                </view>
                <view v-if="sub.taskType === 2" class="subject-detail"
                  >AI精准学{{ sub.num }}次
                </view>
                <view v-if="sub.taskType === 3" class="subject-detail"
                  >语感训练{{ sub.num }}次
                </view>
              </view>
            </view>
          </view>
        </view>
        <view v-if="item.tasks?.length > 1" class="card-footer">
          <text v-if="item.fold" class="label" @click="item.fold = !item.fold"
            >展开<wd-icon name="arrow-down" size="28rpx"></wd-icon
          ></text>
          <text v-else class="label" @click="item.fold = !item.fold"
            >收起<wd-icon name="arrow-up" size="28rpx"></wd-icon
          ></text>
        </view>
      </view>
    </view>
  </view>
</template>
<script setup lang="ts">
import dayjs from 'dayjs';
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app';
import { onMounted, ref, watch } from 'vue';
import selectIcon from '/src/static/svg/select.svg';
import { condition, getUnreadCount } from '@/api/modules/inspector';
import { useSocket } from '@/hooks/useSocket';
const { init: socketInit, inspectorMessage, sendMsg, inspectorDesktopMessage } = useSocket();
const selectionIcon = selectIcon;
const list = ref<any[]>([{ id: 0, fold: true, list: [{ id: 0 }, { id: 1 }] }]);
const tagName = {
  0: '自由学',
  1: '自由学',
  2: '精准学',
  3: '语感训练',
};
const tagClass = {
  0: 'yellow',
  1: 'yellow',
  2: 'blue',
  3: 'red',
};
const unreadCount = ref(0);
function padZero(value) {
  return value < 10 ? `0${value}` : `${value}`;
}
function timeFormat(time: string) {
  return dayjs(time).format('HH:mm');
}
function jumpPage(path: string) {
  uni.navigateTo({
    url: path,
  });
}
const deskUserId = ref('');
const deskShotArr = ref([]);
async function getData() {
  try {
    uni.showLoading({ title: '加载中...' });
    const courseDate = uni.getStorageSync('courseDate');
    const { code, data } = await condition({ courseDate });
    uni.hideLoading();
    if (code === 200) {
      deskUserId.value = data.map(item => item.userId).join();
      sendMsg({ type: 'inspectorDesktopPreview', msg: deskUserId.value });
      list.value = (data || []).map(item => {
        return {
          ...item,
          fold: true,
        };
      });
    }
  } catch (error) {
    uni.hideLoading();
  }
}
function chat(row: any) {
  uni.setStorageSync('stu', {
    sender: 1,
    receiverId: row.userId,
    avatarUrl: row.avatarUrl,
    nickName: row.username,
  });
  uni.setStorageSync('user', { userName: row.userName, userId: row.userId });
  uni.navigateTo({
    url: '/pages/inspector/chat/chatDetails',
  });
}
// 获取我的未读消息
async function getMyUnreadCount() {
  const { code, data } = await getUnreadCount();
  if (code === 200) {
    unreadCount.value = data;
  }
}
watch(inspectorMessage, msg => {
  if (!msg) return;
  unreadCount.value++;
});
watch(inspectorDesktopMessage, (info: any) => {
  if (!info.type) return;
  if (!info.msg) {
    deskShotArr.value.push({ ...info.data });
  } else {
    deskShotArr.value.push({ ...info.msg });
  }
  list.value = list.value.map((i: any) => {
    let v: any = deskShotArr.value.filter((i2: any) => i2.userId === i.userId);
    if (v.length > 0) {
      return {
        ...i,
        deskUrl: v[0].imageUrl ? v[0].imageUrl : '',
      };
    }
    return i;
  });
});
onPullDownRefresh(() => {
  sendMsg({ type: 'inspectorDesktopPreview', msg: deskUserId.value });
  uni.stopPullDownRefresh();
});
onMounted(() => {
  socketInit();
  getData();
});
onShow(() => {
  deskShotArr.value = [];
  getMyUnreadCount();
});
</script>
<style lang="scss" scoped>
.page {
  padding: 0 30rpx;
  .info {
    width: 48rpx;
    height: 48rpx;
  }
  .content {
    padding: 30rpx 0;
    box-sizing: border-box;
  }
  .card {
    padding: 30rpx;
    width: 690rpx;
    box-sizing: border-box;
    border-radius: 20rpx;
    background: #fff;
    margin-bottom: 30rpx;
    .card-top {
      display: flex;
      align-items: center;
      position: relative;
      border-bottom: 1rpx solid #f6f6f6;
      padding-bottom: 20rpx;
      box-sizing: border-box;
      .communication-tag {
        position: absolute;
        top: 0;
        right: 0;
        width: 128rpx;
        height: 46rpx;
        border-radius: 10rpx;
        background: #efefff;
        color: #615dff;
        font-weight: 500;
        font-size: 24rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .card-top-right {
        margin-left: 20rpx;
        .name {
          font-size: 30rpx;
          line-height: 46rpx;
          color: #0a1f13;
          font-weight: 500;
          margin-bottom: 10rpx;
        }
        .cell {
          font-size: 28rpx;
          line-height: 42rpx;
          color: #0a1f13;
          .text-grren {
            color: #21d17a;
            margin-left: 8rpx;
          }
        }
      }
    }
    .scren-img {
      background: #f6f6fa;
      width: 292rpx;
    }
    .wd-img {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .error-wrap {
      font-size: 24rpx;
      color: #666;
      margin: 0 auto;
      .wd-icon {
        color: #ff2828;
      }
    }
    .card-content {
      padding-top: 20rpx;
      box-sizing: border-box;
      .card-item {
        display: flex;
        justify-content: space-between;
        padding-bottom: 20rpx;
        box-sizing: border-box;

        .index {
          font-size: 30rpx;
          font-weight: 500;
          color: #0a1f13;
        }
        .item-content {
          width: 564rpx;
          padding-bottom: 20rpx;
          border-bottom: 1rpx solid #f6f6f6;
          box-sizing: border-box;
          .subject-top {
            display: flex;
            align-items: center;
            justify-content: space-between;
            .left {
              .subject-name {
                font-size: 30rpx;
                font-weight: 500;
                color: #0a1f13;
                margin-right: 8rpx;
              }
              .tag {
                padding: 0 10rpx;
                font-size: 22rpx;
                line-height: 30rpx;
                border-radius: 6rpx;
                color: #fff;
              }
              .yellow {
                background: #ffa65d;
              }
              .blue {
                background: #4fd6ee;
              }
              .red {
                background: #ff91a1;
              }
            }
            .right {
              font-size: 24rpx;
              line-height: 36rpx;
              .finished {
                color: #21d17a;
              }
              .unfinished {
                color: #ff2828;
              }
              .rate::after {
                content: '';
                display: inline-block;
                height: 24rpx;
                width: 1rpx;
                background: #e0e1f0;
                margin: 0 8rpx;
              }
              .date {
                color: #a9aab5;
              }
            }
          }
          .subject-detail {
            margin-top: 10rpx;
            font-size: 28rpx;
            line-height: 42rpx;
            color: #333;
          }
        }
      }
    }
    .card-footer {
      text-align: center;
      font-size: 24rpx;
      color: #a9aab5;
    }
  }
}
</style>
