<template>
  <div class="sunshineRun">
    <div class="sunshineRun-top">
      <div class="sunshineRun-top-center">
        <div class="logo">
          <img v-if="userInfo?.logo_url" :src="userInfo.logo_url" />
          <img v-else src="@/assets/images/common/logo.png" />
        </div>
        <div class="sunshineRun-title"><img src="@/assets/images/sunshineRun/title.png" /></div>
        <div class="toolList">
          <div class="li">{{ date }}</div>
          <div class="li btn screen" :class="{ 'on': screen, 'off': !screen }" @click="getFullScreen" title="屏幕"></div>
          <div class="li btn rankingSwitch" :class="{ 'on': rankingSwitch2, 'off': !rankingSwitch2 }" @click="getRankingBtn" title="排行榜"></div>
          <div class="li btn closeBtn" @click="confirmExit"></div>
        </div>
      </div>
    </div>
    <div class="sunshineRun-main">
      <div class="sunshineRun-left">
        <div class="list-box">
          <div class="sunshineRun-columns-title">
            <div class="title">实时数据</div>
          </div>
          <div class="testList">
            <ul>
              <TransitionGroup>
                <li v-for="(item, index) in testList" :key="item.student_id">
                  <!-- <img v-if="item.student_id && item.student_icon_url" :src="item.student_icon_url" />
                  <img class="noPic"
                    v-else src="@/assets/images/common/noImg.png" /> -->
                  <div class="nameBox">{{ item.name }}</div>
                  <div class="pic" v-if="item.student_id && item.student_icon_url"
                    :style="{ backgroundImage: 'url(' + item.student_icon_url + ')' }"></div>
                  <div class="con">
                    <!-- <div class="name">{{ item.name }}</div> -->
                    <div class="score">
                      <div class="quanshu">{{ item.ring_count || 0 }}<i>圈</i></div>
                      <div>
                        {{ item.distance }}<span>{{ unit }}</span>
                      </div>
                    </div>
                  </div>
                </li>
              </TransitionGroup>
            </ul>
          </div>
        </div>
      </div>
      <div class="sunshineRun-right">
        <div class="list-box">
          <div class="sunshineRun-columns-title">
            <div class="title">排行榜</div>
          </div>
          <div class="reportList">
            <ul>
              <li v-for="(item, index) in reportList" :key="index">
                <div class="left">
                  <div class="pai"
                    :class="{ 'pai1': item.rankid == 1, 'pai2': item.rankid == 2, 'pai3': item.rankid == 3 }">
                    <div>{{ item.rankid }}</div>
                  </div>
                  <!-- <div class="pic"><img :src="item.icon" /></div> -->
                  <div class="txt">
                    <div>
                      <div class="name">{{ item.student_name }}</div>
                      <div class="className">{{ item.class_name }}</div>
                    </div>
                  </div>
                </div>
                <div class="right">
                  <div class="score">{{ item.run_distance }}</div>
                  <div class="unit">{{ unit }}</div>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
    <RankingWindow ref="rankingWindowRef" @getClose="openRanking"></RankingWindow>
  </div>
</template>

<script setup name="SunshineRun" lang="ts">
import { clearInterval, clearTimeout, setInterval, setTimeout } from 'worker-timers';
import { useSunshineRunSocket } from '@/utils/sunshineRunWs';
const { proxy } = getCurrentInstance() as any;
const router = useRouter();
const myInfo: any = localStorage.getItem('userInfo');
const { sunshineRunWs, startConnect } = useSunshineRunSocket();
const rankingWindowRef = ref();
const data = reactive<any>({
  timerManager: {}, //计时器管理
  userInfo: {}, //用户信息
  testList: [], //测试列表
  reportList: [], //排行榜
  date: '', //当前时间
  unit: '', //单位
  screen: true, //全屏控制
  studentPage: {
    current: 1,
    size: 8,
    pages: 1
  }, //学生分页
  timer: null, //排行榜定时弹窗状态
  rankingSwitch2: true, //排行榜开关
});

const { timerManager, userInfo, testList, reportList, date, unit, screen, studentPage, timer, rankingSwitch2 } = toRefs(data);

/**
 * 更新时间
 */
const setDate = () => {
  timerManager.value.currentTime = setInterval(() => {
    date.value = proxy?.$utils.getDate();
  }, 1000);
};

/**
 * 屏幕模式
 */
const getFullScreen = () => {
  screen.value = !screen.value;
  localStorage.setItem('screen', screen.value);
  proxy?.$utils.fullScreen();
};

/**
 * 确定退出
 */
const confirmExit = async () => {
  if (import.meta.env.DEV) {
    getClearTimer();
    proxy?.$modal.msgSuccess('测试环境免密退出');
    await proxy?.$http.common.logout({}).then((res: any) => { });
    proxy?.$modal?.closeLoading();
    //清空缓存
    // localStorage.clear();
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    //跳转
    router.push({ path: '/login/sunshineRun' });
  } else {
    let myInfo: any = localStorage.getItem('userInfo');
    let userInfo = JSON.parse(myInfo);
    proxy?.$modal
      .prompt(`【${userInfo.login_name}】，请输入密码`, 'password')
      .then((e: any) => {
        // console.log("e", e)
        if (e.action == 'confirm' && e.value) {
          getClearTimer();
          let params = {
            password: e.value
          };
          proxy?.$http.common.checkPassword(params).then(async (res: any) => {
            if (res.status === 200 || res.status === 1) {
              await proxy?.$http.common.logout({}).then((res: any) => { });
              proxy?.$modal?.closeLoading();
              //清空缓存
              // localStorage.clear();
              localStorage.removeItem('token');
              localStorage.removeItem('userInfo');
              //跳转
              router.push({ path: '/login/sunshineRun' });
            } else {
              proxy?.$modal.msgError(res.message);
            }
          });
        }
      })
      .finally(() => { });
  }
};

/**
 * 清空定时任务
 */
const getClearTimer = (data?: any) => {
  if (data) {
    //清除指定
    clearInterval(timerManager.value[data]);
    timerManager.value[data] = null;
  } else {
    //清除全部
    for (let key in timerManager.value) {
      if (timerManager.value.hasOwnProperty(key)) {
        clearInterval(timerManager.value[key]);
        timerManager.value[key] = null;
      }
    }
  }
};

/**
 * 获取排名
 */
const getStudentList = () => {
  let params: any = {
    page: studentPage.value.current,
    per_page: studentPage.value.size
  };
  proxy?.$http.ranking.sunshineRunRanking(params).then((res: any) => {
    if (res.status == 200) {
      let list: any = res.sunlight_rank_data;
      reportList.value = list;
      getPages(res.total);
    }
  });
};

/**
 * 计算页码
 */
const getPages = (data: any) => {
  studentPage.value.pages = Math.ceil(data / studentPage.value.size);
};

/**
 * 自动切换排行榜
 */
const getAutoplay = () => {
  getStudentList();
  timerManager.value.autoplayTime = setInterval(() => {
    // 切换页码
    if (studentPage.value.current >= studentPage.value.pages || studentPage.value.current >= 5) {
      studentPage.value.current = 1;
    } else {
      studentPage.value.current++;
    }
    getStudentList();
  }, 10000);
};

/**
 * 获取模拟数据
 */
const getSunshineRunPushData = async () => {
  let params = {
    password: 'fb083a6fe1e14600910b06977c1d037e',
    school_id: '3'
  };
  await proxy?.$http.common.sunshineRunPushData(params).then((res: any) => { });
};

/**
 * 加载WS
 */
const initSunshineRun = () => {
  sunshineRunWs((e: any) => {
    //console.log('eeeee', e);
    //定时打开排行榜
    openRanking();
    if (e?.wksid) {
      startConnect();
    }
    //接收第一次成绩列表
    if (e?.cmd == 'sunlight_init_result' && e?.data.length) {
      let ids = e.data.map((item: any) => {
        return item.student_id;
      });
      let list = testList.value.filter((item: any) => {
        return !ids.includes(item.student_id);
      });
      testList.value = [...e.data, ...list];
      //定时打开排行榜
      openRanking();
      //模拟数据
      // setInterval(() => {
      //   getSunshineRunPushData();
      // }, 1000)
    }
    //接收推送数据
    if (e?.cmd == 'sunlight_one_result' && e?.data) {
      let myIndex = testList.value.findIndex((item: any) => {
        return item.student_id == e.data.student_id;
      });
      if (myIndex != -1) {
        //如果已经存在就删除
        testList.value.splice(myIndex, 1); //删除数据
      }
      testList.value.unshift(e.data); //插入数据
      //定时打开排行榜
      openRanking();
    }
  });
};

/**
 * 定时打开排行榜
 */
const openRanking = () => {
  clearTimeout(timer.value);
  if (rankingWindowRef.value.rankingState) {
    rankingWindowRef.value.close();
  }
  //console.log("timer.value", timer.value)
  let state = localStorage.getItem('rankingSwitch2');
  if (state != "1") {
    return false;
  }
  // 设置新的定时器
  timer.value = setTimeout(() => {
    if (!rankingWindowRef.value.rankingState) {
      rankingWindowRef.value.open();
    }
  }, 1000 * 60 * 5);
};

/**
 * 排行榜开关
*/
const getRankingBtn = () => {
  let state = localStorage.getItem('rankingSwitch2');
  if (state == "1") {
    localStorage.setItem('rankingSwitch2', "0");
    rankingSwitch2.value = false;
    proxy?.$modal.msgWarning('排行榜定时任务已停用');
  } else {
    localStorage.setItem('rankingSwitch2', "1");
    rankingSwitch2.value = true;
    proxy?.$modal.msgSuccess('排行榜定时任务已启用');
  }
  openRanking();
};

onBeforeMount(() => {
  localStorage.setItem('loginType', "3");
  let state2 = localStorage.getItem('rankingSwitch2');
  if (state2 == undefined) {
    localStorage.setItem('rankingSwitch2', "1");
  }
  //获取当前时间
  setDate();
  //用户信息
  userInfo.value = JSON.parse(myInfo);
  //屏幕
  let screenData = localStorage.getItem('screen');
  if (screenData != undefined && screenData == 'false') {
    screen.value = false;
  } else {
    screen.value = true;
  }
  //单位
  unit.value = 'M';
  //排行榜
  getAutoplay();
});

/**
 * 监听数据
 */
// watch(
//   () => testList.value.length,
//   (v) => {
//     if (v == 0) {
//       openRanking();
//     } else {
//       closeRanking();
//     }
//   },
//   { immediate: true }
// );

onMounted(() => {
  //初始化WS
  initSunshineRun();
});

onBeforeUnmount(() => {
  getClearTimer();
});
</script>

<style lang="scss" scoped>
.sunshineRun {
  width: 100%;
  height: 100%;
  padding: 0 0 1vw 0;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background: #3bddce url('@/assets/images/sunshineRun/bg.png') top center no-repeat;
  background-size: cover;

  .sunshineRun-top {
    padding: 0px 1vw;

    .sunshineRun-top-center {
      height: 10vh;
      position: relative;
      display: flex;
      justify-content: center;

      .logo {
        position: absolute;
        left: 0;
        top: 2vh;

        img {
          height: 5vh;
        }
      }

      .sunshineRun-title {
        display: inline-block;

        img {
          height: 15vh;
        }
      }

      .toolList {
        position: absolute;
        right: 0;
        top: 2vh;
        color: #efefef;
        font-size: 2.5vh;
        display: flex;
        align-items: center;
        text-shadow: 1px 1px 1px #a3a3a3;

        .li {
          margin-left: 2vw;
        }

        .btn {
          width: 3vh;
          height: 3vh;
          display: block;
          background-position: center;
          background-repeat: no-repeat;
          background-size: 100% auto;
          cursor: pointer;
        }

        .closeBtn {
          background-image: url('@/assets/images/sunshineRun/close.png');
        }

        .screen.on {
          background-image: url('@/assets/images/sunshineRun/screen1.png');
        }

        .screen.off {
          background-image: url('@/assets/images/sunshineRun/screen2.png');
        }

        .rankingSwitch.on {
          background-image: url('@/assets/images/sunshineRun/rankingSwitch1.png');
        }

        .rankingSwitch.off {
          background-image: url('@/assets/images/sunshineRun/rankingSwitch2.png');
        }
      }
    }
  }

  .sunshineRun-main {
    display: flex;
    justify-content: space-evenly;
    height: 100%;

    .sunshineRun-columns-title {
      display: flex;

      .title {
        height: 5vh;
        line-height: 5vh;
        font-size: 3vh;
        color: #1a293a;
        padding: 0px 2vw;
        letter-spacing: 3px;
        border-top-left-radius: 2vh;
        border-top-right-radius: 2vh;
        background: radial-gradient(374% 336% at 36% 50%, #ffffff 0%, #07ffe7 100%);
        box-shadow: inset 0px 1px 0px 2px rgba(255, 255, 255, 0.5577);
      }
    }

    .sunshineRun-left {
      width: 76%;
      display: flex;
      flex-direction: column;
      position: relative;

      .list-box {
        display: flex;
        flex-direction: column;
        height: 100%;

        .testList {
          width: 100%;
          height: calc(100vh - 1vw - 10vh - 5vh);
          border-radius: 2vh;
          overflow-x: hidden;
          overflow-y: scroll;
          background: linear-gradient(170deg, #276066 -13%, #09111b 87%);
          box-sizing: border-box;
          border: 1px solid #ffffff;
          box-shadow: 0px 0px 6px 2px rgba(255, 255, 255, 0.5);
          border-top-left-radius: 0px;

          &::-webkit-scrollbar {
            width: 0px;
          }

          &::-webkit-scrollbar-thumb {
            border-width: 2px;
            border-radius: 4px;
            border-style: dashed;
            border-color: transparent;
            background-color: rgba(26, 62, 78, 0.9);
            background-clip: padding-box;
          }

          &::-webkit-scrollbar-button:hover {
            border-radius: 6px;
            background: rgba(26, 62, 78, 1);
          }

          ul {
            display: flex;
            flex-wrap: wrap;
            padding: 1.6vh 0.8vh 0px 0.8vh;

            li {
              position: relative;
              width: calc((100% / 6) - 1.6vh);
              height: calc(((100vh - 1vw - 10vh - 5vh - 1.6vh) / 3) - 1.6vh);
              margin: 0px 0.8vh 1.6vh 0.8vh;
              box-sizing: border-box;
              border: 1px solid #ffffff;
              border-radius: 1.6vh;
              overflow: hidden;
              display: flex;
              align-items: center;
              justify-content: center;

              img {
                width: 100%;
                height: 100%;
              }

              .nameBox {
                position: absolute;
                left: 0;
                top: 0;
                font-size: 1.5vw;
                color: #ffffff;
                line-height: 1;
                width: auto;
                text-align: left;
                margin-bottom: 0.7vh;
                font-weight: bold;
                display: inline-block;
                padding: 0.8vh 8% 0.8vh 5%;
                box-sizing: border-box;
                // background: linear-gradient(180deg, rgba(0, 0, 0, 0.87) 45%, rgba(18, 133, 124, 0.7367) 135%);
                background: linear-gradient(to right, rgba(15, 25, 38, 1) 0%, rgba(49, 95, 126, 0.6) 100%);
                border-radius: 0px 0px 1vh 0px;
              }

              .pic {
                width: 100%;
                height: 100%;
                background-size: cover;
                background-position: center;
              }

              .noPic {
                width: auto;
                height: auto;
                max-width: 60% !important;
                max-height: 60% !important;
                opacity: 0.2;
              }

              .con {
                position: absolute;
                bottom: 0;
                width: 100%;
                // padding: 0.7vh 4%;
                padding: 0.8vh 4%;
                display: flex;
                align-items: center;
                // justify-content: space-between;
                flex-direction: column;
                box-sizing: border-box;
                background: linear-gradient(180deg, rgba(0, 0, 0, 0.87) 45%, rgba(18, 133, 124, 0.7367) 135%);

                .name {
                  font-size: 1.5vw;
                  color: #ffffff;
                  line-height: 1;
                  width: 100%;
                  text-align: left;
                  margin-bottom: 0.7vh;
                  font-weight: bold;
                }

                .score {
                  width: 100%;
                  font-size: 1.8vw;
                  color: #00ffe8;
                  font-family: 'Saira-ExtraBold';
                  font-style: italic;
                  line-height: 1;
                  text-align: right;
                  display: flex;
                  justify-content: space-between;

                  .quanshu {
                    font-style: normal;
                  }

                  span {
                    font-size: 1.8vw;
                  }

                  i {
                    font-size: 1.1vw;
                    margin-left: 2px;
                  }
                }
              }
            }
          }
        }
      }
    }

    .sunshineRun-right {
      width: 21%;
      display: flex;
      flex-direction: column;
      position: relative;

      .list-box {
        display: flex;
        flex-direction: column;
        height: 100%;

        .reportList {
          width: 100%;
          border-radius: 2vh;
          overflow: hidden;
          background: radial-gradient(90% 90% at 50% 100%, #38869e 0%, #38869e 50%, #17323d 100%);
          box-sizing: border-box;
          border: 1px solid #ffffff;
          display: flex;
          flex-direction: column;
          height: 100%;
          border-top-left-radius: 0px;

          ul {
            height: 100%;
            // overflow-y: scroll;

            li {
              height: calc(100% / 8);
              border-bottom: 1px solid #48677e;
              padding: 0px 5%;
              display: flex;
              justify-content: space-between;
              align-items: center;
              transition: all 0.2s;
              box-sizing: border-box;

              // &:hover {
              //   background: rgba(255, 255, 255, 0.4);
              // }

              .left {
                display: flex;
                align-items: center;
                padding-right: 5%;
                width: 100%;

                .pai {
                  width: 2.5vw;
                  height: 2vw;
                  line-height: 1;
                  text-align: center;
                  color: #f9f9f9;
                  font-size: 1.5vw;
                  font-family: 'Saira-ExtraBold';
                  margin-right: 10%;
                  flex-shrink: 0;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  font-style: italic;
                }

                .pai1,
                .pai2,
                .pai3 {
                  align-items: end;
                }

                .pai1 {
                  background: url('@/assets/images/ranking/pai1.png') left center no-repeat;
                  background-size: 100% 100%;
                }

                .pai2 {
                  background: url('@/assets/images/ranking/pai2.png') left center no-repeat;
                  background-size: 100% 100%;
                }

                .pai3 {
                  background: url('@/assets/images/ranking/pai3.png') left center no-repeat;
                  background-size: 100% 100%;
                }

                .pic {
                  width: 7vh;
                  height: 7vh;
                  border-radius: 50%;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                  overflow: hidden;
                  box-sizing: border-box;
                  border: 1px solid rgba(255, 255, 255, 0.5);
                  margin-right: 5%;
                  flex-shrink: 0;

                  img {
                    width: 100%;
                  }
                }

                .txt {
                  display: flex;
                  align-items: center;

                  .name {
                    color: #f9f9f9;
                    // font-size: 1vw;
                    font-size: 1.6vw;
                  }

                  .className {
                    color: #13ed84;
                    // font-size: 0.8vw;
                    font-size: 1vw;
                  }
                }
              }

              .right {
                flex-shrink: 0;
                font-family: 'Saira-ExtraBold';
                // font-size: 1.4vw;
                font-size: 1.8vw;
                font-style: italic;

                .score {
                  color: #ffffff;

                  display: inline-block;
                }

                .unit {
                  color: #ffffff;
                  margin-left: 2px;
                  display: inline-block;
                }
              }
            }

            &::-webkit-scrollbar {
              width: 0px;
            }

            &::-webkit-scrollbar-thumb {
              border-width: 2px;
              border-radius: 4px;
              border-style: dashed;
              border-color: transparent;
              background-color: rgba(216, 216, 216, 0.8);
              background-clip: padding-box;
            }

            &::-webkit-scrollbar-button:hover {
              border-radius: 6px;
              background: rgba(216, 216, 216, 0.8);
            }
          }
        }
      }
    }
  }
}
</style>
