<template>
  <div class="gesture">
    <Header :showTool="false" @confirmExit="getLogout"></Header>
    <div class="menu">
      <swiper v-if="projectList.length" :slides-per-view="5" :space-between="0" :initialSlide="2" :loop="true"
        :centeredSlides="true" :modules="[Navigation]" @swiper="onSwiper">
        <swiper-slide v-for="(item, index) in projectList" :key="index">
          <div class="li">
            <div class="pic"><img :src="'static/images/train/' + item.key + '.png'"></div>
            <div class="name">
              {{ item.name }}
            </div>
          </div>
        </swiper-slide>
      </swiper>
    </div>
    <OptionWindow ref="optionWindowRef" :projectList="projectList" />

    <div style=" width: 100%; color: #ffffff; font-size:1.5rem; text-align: center; position:fixed; bottom: 10px; ">
      <div style="margin-bottom: 10px;">模拟发送手势：</div>
      <div @click="getCmdtest(1)" style="margin-bottom: 10px;">1、左滑动</div>
      <div @click="getCmdtest(2)" style="margin-bottom: 10px;">2、举左手</div>
      <div @click="getCmdtest(3)">3、双手胸前交叉</div>
    </div>
  </div>
</template>

<script setup name="Gesture" lang="ts">
import { handWs, startHand, closeHand } from '@/utils/handWs'
import { deviceWs, startDevice } from '@/utils/deviceWs'
import { Swiper, SwiperSlide } from 'swiper/vue';
import { Navigation } from 'swiper/modules';
import 'swiper/css';
import 'swiper/scss/navigation';
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance() as any;
const optionWindowRef = ref();
const mySwiper = ref();
const data = reactive<any>({
  projectList: [],
  timerManager: {},
  device_info: {}
});
const { projectList, timerManager, device_info } = toRefs(data);

/**
 * 清空定时任务
*/
const getClearTimer = () => {
  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 getOption = (data: any) => {
  optionWindowRef.value.open(data);
};

/**
 * 获取项目
*/
const getExam = async () => {
  let examList = device_info.value?.project_list.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);
    });
    console.log("projectList.value", projectList.value)
  });
};

/**
 * 获取实例
*/
const onSwiper = ($ev) => {
  mySwiper.value = $ev;
};

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

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

/**
 * 确定并进入
*/
const confirm = () => {
  let project = projectList.value[mySwiper.value.realIndex];
  console.log("project", project)
  let obj = device_info.value.project_list.find((item: any) => {
    return item.exam_name == project.key;
  })
  if (obj == undefined) {
    proxy?.$modal.msgError("该项目没有配置参数");
    return false;
  }
  let data = {
    gesture: obj.gesture ? true : false,
    demo: obj.demo,
    area: obj.area_test_id,
    ctrl: obj.area_ctrl_id,
    time: obj.test_time,
    music: obj.music_info.url,
    handcontroller: device_info.value.handcontroller_id,
  }
  console.log("111", project)
  optionWindowRef.value.getGesture(JSON.parse(JSON.stringify(project)), data);
};

/**
 * 手势
*/
const getHandWs = () => {
  //加载手势WS
  handWs((e: any) => {
    //发送设备
    if (e?.wksid) {
      console.log("e.wksid", e.wksid)
      let handcontroller_id = device_info.value.handcontroller_id;
      if (handcontroller_id) {
        startHand(handcontroller_id)
      } else {
        proxy?.$modal.msgError("请配置手势ID");
      }
    }
    //左滑动
    if (e?.data?.result == "next_item") {
      slideNext();
    }
    //举左手
    if (e?.data?.result == "left_hand") {
      confirm();
    }
    //退出
    if (e?.data?.result == "exit") {

    }
  });
};

/**
 * 模拟发送手势
*/
const getCmdtest = (data: any) => {
  let params = {
    hctrl_name: `handcontroller_${device_info.value.handcontroller_id}`,
    cmd: data
  };
  proxy?.$http.common.cmdtest(params).then((res: any) => {
  });
};

/**
 * 退出
*/
const getLogout = () => {
  proxy?.$modal.prompt('请输入密码', '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((res: any) => {
        if (res.status === 200 || res.status === 1) {
          proxy?.$http.common.logout({}).then((res: any) => {
          });
          proxy?.$modal?.closeLoading()
          //清空缓存
          localStorage.clear();
          //跳转
          router.push({ path: '/login/qrcode' });
        } else {
          proxy?.$modal.msgError(res.message);
        }
      });
    }
  }).finally(() => {
  });
};

onBeforeMount(() => {
  //加载设备WS
  deviceWs((e: any) => {
    //发送设备
    if (e?.wksid) {
      console.log("e.wksid", e.wksid)
      let deviceid = localStorage.getItem("deviceid");
      startDevice({ deviceid: deviceid })
    }
    //接收百度语音token
    if (e?.bdapi_token) {
      console.log("e.bdapi_token", e.bdapi_token)
      let tok = e.bdapi_token;
      localStorage.setItem('tok', tok);
    }
    //接收参数
    if (e?.device_info) {
      console.log("e.device_info", e.device_info)
      device_info.value = e.device_info
      getInitExam();
      getHandWs();
    }
  });
})
onMounted(() => {

})
onBeforeUnmount(() => {
  getClearTimer();
})
</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;
    flex-wrap: wrap;
    justify-content: center;
    text-align: center;
    background: radial-gradient(96% 96% at 2% 32%, #FFFFFF 0%, #FCFDFD 54%, #E1E4E7 100%);
    flex-shrink: 0;
    cursor: pointer;

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


    .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%);
    }
  }
}
</style>
