<template>
  <div class="gesture">
    <Header :showTool="true" @confirmExit="getLogout" type="gesture"></Header>
    <div class="menu" v-if="projectList.length" :key="projectList.length">
      <swiper :slides-per-view="5" :space-between="0" :loop="true" :observe-parents="true" :observer="true"
        :centered-slides="true" :modules="[Navigation]" @swiper="onSwiper">
        <swiper-slide v-for="(item, index) in projectList" :key="index" @click="getOption(item)">
          <div class="li">
            <div>
              <div class="pic"><img :src="'static/images/train/' + item.key + '.png'" /></div>
              <div class="name">
                {{ item.name }}
              </div>
            </div>
          </div>
        </swiper-slide>
      </swiper>
    </div>
    <!-- <div class="erweima">
      <img :src="erweima" />
      <span>扫码遥控</span>
    </div> -->
    <OptionWindow ref="optionWindowRef" :projectList="projectList" />
  </div>
</template>

<script setup name="Gesture" lang="ts">
import { useWebSocket } from '@/utils/handWs';
import { Swiper, SwiperSlide } from 'swiper/vue';
import { Navigation } from 'swiper/modules';
import { clearInterval, clearTimeout, setInterval, setTimeout } from 'worker-timers';
import QRCode from 'qrcode';
import 'swiper/css';
import 'swiper/scss/navigation';
const { handWs, startDevice, startHand, stateHand } = useWebSocket();
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance() as any;
const optionWindowRef = ref();
const data = reactive<any>({
  mySwiper: {},
  projectList: [],
  timerManager: {},
  deviceInfo: {},
  erweima: '',
  sid: '',
});
const { mySwiper, projectList, timerManager, deviceInfo, erweima, sid } = toRefs(data);

/**
 * 清空定时任务
 */
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 getInitExam = () => {
  getExam();
  //定时刷新
  timerManager.value.exam = setInterval(() => {
    getExam();
  }, 5000);
};

/**
 * 获取项目
 */
const getExam = async () => {
  let myList = deviceInfo.value?.project_list || [];
  let examList = myList.map((item: any) => {
    return item.exam_name;
  });
  await proxy?.$http.train.projectList().then((res: any) => {
    projectList.value = proxy?.$utils.getProject(res.exams).filter((item: any) => {
      //只显示能开的
      return item.area.length > 0 && examList.includes(item.key);
      //return item.area.length > 0;
    });
    // console.log("projectList.value", projectList.value)
  });
};

/**
 * 获取实例
 */
const onSwiper = ($ev: any) => {
  // console.log('1111111', $ev);
  mySwiper.value = $ev;
  slidePrev();
};

/**
 * 切换上一页
 */
const slidePrev = () => {
  mySwiper.value.slidePrev();
};

/**
 * 切换下一页
 */
const slideNext = () => {
  mySwiper.value.slideNext();
};

/**
 * 启动切换
 */
const slideChange = () => {
  // if (projectList.value.length <= 3) {
  //   slidePrev()
  // } else {
  //   slideNext();
  // }
  slidePrev();
};

/**
 * 进入项目
 */
const getOption = (data: any) => {
  confirm(data);
};

/**
 * 确定并进入
 */
const confirm = (myProject?: any) => {
  let project = myProject || projectList.value[mySwiper.value.realIndex];
  console.log('projectList.value', projectList.value);
  console.log('mySwiper.value', mySwiper.value);
  console.log('mySwiper.value.realIndex', mySwiper.value.realIndex);
  console.log('project', project);
  if (project == undefined) {
    proxy?.$modal.msgError('获取不到项目信息');
    return false;
  }
  let obj = deviceInfo.value.project_list.find((item: any) => {
    return item.exam_name == project.key;
  });
  if (obj == undefined) {
    proxy?.$modal.msgError('该项目没有配置参数');
    return false;
  }
  let dataObj = {
    gesture: obj.gesture ? true : false,
    demo: obj?.demo || 0,
    area: obj?.area_test_id || '',
    ctrl: obj?.area_ctrl_id || '',
    time: obj?.test_time || '',
    music: obj?.music_info?.id || '',
    handcontroller: deviceInfo.value.handcontroller_id
  };
  optionWindowRef.value.getGesture(project, dataObj);
};

/**
 * 退出
 */
const getLogout = async () => {
  if (import.meta.env.DEV) {
    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/qrcode' });
  } 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) {
          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/qrcode' });
            } else {
              proxy?.$modal.msgError(res.message);
            }
          });
        }
      })
      .finally(() => { });
  }
};

/**
 * 提示语
 */
const getTips = () => {
  let myTime = 7000;
  let num = 0;
  timerManager.value.tips = setInterval(() => {
    if (projectList.value.length) {
      if (num % 2 == 0) {
        proxy?.$modal.msgWarning({
          message: `手向左滑切换项目`,
          duration: 5000
        });
      } else {
        proxy?.$modal.msgWarning({
          message: `举左手进入测试`,
          duration: 5000
        });
      }
      num++;
    }
  }, myTime);
};


/**
 * 获取设备项目
 */
const getDevice = async () => {
  let deviceid = localStorage.getItem('deviceid') || '';
  if (deviceid) {
    startDevice({ deviceid: deviceid });
  } else {
    proxy?.$modal.msgError(`缺少设备信息请重新登录！`);
    await proxy?.$http.common.logout({}).then((res: any) => { });
    proxy?.$modal?.closeLoading();
    //清空缓存
    // localStorage.clear();
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    //跳转
    router.push({ path: '/login/qrcode' });
  }
};

/**
 * 获取二维码
 */
const getErweima = () => {
  let deviceid = localStorage.getItem('deviceid') || '';
  QRCode.toDataURL(`${location.origin}/#/login/mobile?sid=${sid}&deviceid=${deviceid}`).then((res: any) => {
    erweima.value = res;
  });
};

onBeforeMount(() => {
  localStorage.setItem('loginType', "2");
  //加载设备WS
  handWs((e: any) => {
    if (router.currentRoute.value.path != '/gesture') {
      return false;
    }
    // console.log("eeeee", e)
    if (e?.wksid) {
      //获取设备项目
      getDevice();
    }
    //接收设备信息
    if (e?.device_info) {
      getInitExam();
      deviceInfo.value = e.device_info;
      let handcontroller_id = deviceInfo.value.handcontroller_id;
      //启用才执行命令
      if (deviceInfo.value.status) {
        stateHand(handcontroller_id);
      }
    }
    //获取手势状态
    if (e?.cmd == 'get_handcontroller_state' && e?.state == 0) {
      //提示语
      getTips();
      let handcontroller_id = deviceInfo.value.handcontroller_id;
      startHand(handcontroller_id);
    }
    //左滑动
    if (e?.data?.result == 'next_item') {
      proxy?.$modal.msgSuccess('手势指令：左滑动');
      if (projectList.value.length == 0) {
        return false;
      }
      slideChange();
    }
    //举左手
    if (e?.data?.result == 'left_hand') {
      proxy?.$modal.msgSuccess('手势指令：举左手');
      confirm();
    }
    //退出
    if (e?.data?.result == 'exit') {
      // proxy?.$modal.msgSuccess('手势指令：交叉手');
    }
    //刷新
    if (e?.data?.result == 'refresh') {
      window.location.reload();
    }
  });
});
onMounted(() => {
  //登录码
  getErweima();
});
onBeforeUnmount(() => {
  getClearTimer();
  ElMessage.closeAll();
});
</script>

<style lang="scss" scoped>
$topPadding: 5.19rem;
$waiPadding: 6.51rem;

.menu {
  width: calc(100% - ($waiPadding * 2));
  height: 100vh;
  margin: 0 auto;
  display: flex;
  align-items: center;

  .li {
    // width: calc((100% / 6) - 1rem + (1rem/6));
    // margin-right: 1rem;
    // margin-bottom: 1rem;
    width: 100%;
    height: 100%;
    padding: 3vh 0;
    border-radius: 1.6rem;
    box-sizing: border-box;
    box-shadow: inset 0px 1px 0px 2px rgba(255, 255, 255, 0.9046), inset 0px 3px 6px 0px rgba(0, 0, 0, 0.0851);
    display: flex;
    justify-content: center;
    align-items: center;
    background: radial-gradient(96% 96% at 2% 32%, #ffffff 0%, #fcfdfd 54%, #e1e4e7 100%);
    cursor: pointer;

    .name {
      width: 100%;
      font-size: 2.48rem;
      color: #1a293a;
      padding: 0.5rem 0;
      text-align: center;
    }

    .pic {
      width: 11.36vw;
      height: 11.36vw;
      border-radius: 50%;
      background: radial-gradient(78% 78% at 53% 50%, #07121a 0%, #2a4256 49%, #5180a9 100%);
      box-shadow: 0px 0px 2px 2px #ffffff;
      margin-bottom: 2vh;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;

      img {
        max-width: 88%;
        max-height: 88%;
        transition: all 1s;
      }
    }

    &:hover {
      img {
        transform: translateY(-0.5vw);
      }
    }
  }

  .swiper {
    width: 100%;
  }

  .swiper-slide {
    transform: scale(0.8);
    transition: all 0.3s ease-in-out;
    border-radius: 1.6rem;
    opacity: 0.6;
    overflow: hidden;
  }

  .swiper-slide-active {
    opacity: 1;
    transform: scale(1);

    .li {
      background: radial-gradient(167% 126% at 97% 6%, #35ffc6 0%, #00ffe8 100%);
    }
  }
}

.erweima {
  position: absolute;
  right: 3rem;
  bottom: 3rem;
  text-align: center;

  img {
    width: 6.625rem;
  }

  span {
    display: block;
    color: #ffffff;
    font-size: 1rem;
    padding-top: 3px;
  }
}
</style>
