<template>
  <div class="page">
    <h-navbar title="Procurem" :handleBack="goBack" :handleGoHome="goBack" />
    <div class="page-body">
      <!-- 平台 -->
      <game-class
        v-if="searchData.type == 2"
        :current="gameClassId"
        @change="changeGameClass"
      />
      <div class="game-class" v-if="searchData.type == 2">
        <div
          class="class-item"
          :class="{ active: active === index }"
          v-for="(item, index) in providerIdData"
          :key="index"
          @click="changeProviderId(item.providerId, index)"
        >
          <img style="height: .8rem" :src="getImage(item.gameProviderImg)" />
          <!-- <div>{{ item.gameProviderName || "" }}</div> -->
        </div>
      </div>
      <!-- 厂商 -->
      <game-provider
        v-if="searchData.type == 3"
        :current="providerId"
        @change="changeProvider"
      />

      <div class="game-class" v-if="searchData.type == 3">
        <div
          class="class-typeItem class-item"
          :class="{ active: active === index }"
          v-for="(item, index) in gameTypeIdData"
          :key="index"
          @click="changeGameTypeId(item.gameTypeId, index)"
        >
          <!-- <img style="width: 2rem;" :src="getImage(item.gameProviderImg)" /> -->
          <div>{{ item.gameTypeName || "" }}</div>
        </div>
      </div>
      <div style="margin-top: 0.2rem">
        <van-search
          v-model="inputValue"
          shape="round"
          placeholder="Procurem jogos"
          background="#001018"
          :clearable="false"
        >
          <template #left-icon>
            <div @click="onSearch">
              <van-icon name="search" />
            </div>
          </template>
          <template #right-icon>
            <div @click="clear">Cancelar</div>
          </template>
        </van-search>
      </div>
      <div class="num">Jogo: Encontramos {{ totals }} resultados</div>
      <div
        v-if="list.length"
        class="game-box"
        ref="gameBoxRef"
      >
        <div class="data-all" v-for="(item, index) in list" :key="index">
          <div :data-id="item._id" @click="detail(item)">
            <img
              ref="iconRef"
              :src="getStaticImage('base/loading.png')"
              :data-src="getImage(item.gameImg2)"
              @error.once="moveErrorImg"
            />
            <div class="maintenance-box" v-show="item.state === 0">
              <img :src="getAssets('base/br.png')" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
// import game from "../home/game/index.vue";
import { ref, computed, watchEffect, nextTick } from "vue";
import { writeHistoricalData } from "@/utils/index";
import storage, { actions } from "@/utils/storage";
import { getAssets, getImage, getStaticImage } from "@/utils";
import { gameListStore } from "@/stores/modules/game-list";
import { useGameStore } from "@/stores/modules/game";
import GameClass from "../home/components/game-class.vue";
import router from "@/router";
import GameProvider from "./components/game-provider.vue";
import useInView from "@/hooks/useInView";
import emitter from "@/utils/eventBus";
import socketApi from "@/socket/socketApi";
import { toast } from "@/utils/toast";
import http from "@/https/index";

const { processImage } = useInView();
const iconRef = ref();
const gameBoxRef = ref();
const gameStore = gameListStore();
const gameDetalStore = useGameStore();
// 输入框搜索
const inputValue = ref<any>("");
// 平台id
const gameClassId = ref<any>();
// 当前厂商id
const providerId = ref<any>();

const active = ref(-1);

// 搜索列表
const list = ref<Array<any>>([]);
const _listData = ref<Array<any>>([]);
nextTick(() => {
  processImage(iconRef);
});
// 设置搜索数据
const searchData = computed(() => {
  return gameDetalStore.searchData;
});
// 总数
const totals = computed(() => {
  return list.value.length;
});
const providerIdData = computed(() => {
  let data: any;
  for (let i = 0; i < gameStore.gameList.length; i++) {
    if (gameStore.gameList[i].gameClassId == gameClassId.value) {
      data = gameStore.gameList[i].proIdData;
    }
  }
  return data;
});

const gameTypeIdData = ref<Array<any>>([]);

const changeProviderId = (id: any, index: number) => {
  active.value = index;
  let data = [..._listData.value];
  let newList: Array<any> = [];
  for (let i = 0; i < data.length; i++) {
    if (data[i].providerId === id) {
      newList.push(data[i]);
    }
  }
  list.value = newList;
  nextTick(() => {
    processImage(iconRef);
  });
};
const changeGameTypeId = (id: any, index: number) => {
  active.value = index;
  let data = [..._listData.value];
  let newList: Array<any> = [];
  for (let i = 0; i < data.length; i++) {
    if (data[i].gameTypeId === id) {
      newList.push(data[i]);
    }
  }
  list.value = newList;
  nextTick(() => {
    processImage(iconRef);
  });
};
async function detail(game: any) {
  if (game.state === 0) return;
  if (game.gameId !== "Esportes") {
    gameDetalStore.setGameInfo(game);
    emitter.emit("openGameDetail");
  } else {
    if (!storage.getStorage(actions.USER_TOEKN)) {
      router.replace("/login");
      return;
    }
    const res: ResultData = await http.getGameUrl({
      gameId: game.gameId,
    });
    if (res.code != 0) return toast(res.txt);
    gameDetalStore.setStartGameInfo(res.data);
    emitter.emit("openGame");
  }
}

const moveErrorImg = (event: any) => {
  event.currentTarget.src = getAssets("base/loading.png");
  return true;
};

const init = () => {
  switch (searchData.value.type) {
    case 2:
      gameClassId.value = Number(searchData.value.value);
      break;
    case 3:
      providerId.value = Number(searchData.value.value);
      break;
  }
};

watchEffect(() => {
  list.value = [];
  active.value = -1
  init();
  if (inputValue.value || providerId.value || gameClassId.value) {
    // 拷贝游戏列表
    let data = [...gameStore.originalList];
    // 最终处理完list
    let _list = [];
    // 厂商筛选
    if (providerId.value) {
      _list = gameStore.originalList.filter(
        (i: any) => i.providerId == providerId.value
      );
      data = _list;
      let typeData = [];
      for (let i = 0; i < data.length; i++) {
        if (data[i].gameTypeId) {
          let _type = gameStore.gameTypeData.filter(
            (item: any) => item.gameTypeId === data[i].gameTypeId
          );
          if (_type.length > 0) {
            typeData.push(_type[0]);
          }
        }
      }
      gameTypeIdData.value = Array.from(new Set(typeData));
    }
    // 平台筛选
    if (gameClassId.value) {
      _list = gameStore.originalList.filter((i) => {
        return i.gameClassId.find((s: any) => s == gameClassId.value);
      });
      _list.sort(
        (a: any, b: any) =>
          b.sortInClass[gameClassId.value] - a.sortInClass[gameClassId.value]
      );
      data = _list;
    }
    // 输入框筛选
    if (inputValue.value) {
      data = data.filter((i) => {
        if (
          i.gameAlias.toLowerCase().indexOf(inputValue.value.toLowerCase()) !=
          -1
        ) {
          return i;
        }
        active.value = -1;
      });
    }
    list.value = [...data];
    _listData.value = [...data];
  } else {
    list.value = [...gameStore.originalList];
    _listData.value = [...gameStore.originalList];
  }
  nextTick(() => {
    processImage(iconRef);
    if (gameBoxRef.value.scrollTo) {
      gameBoxRef.value.scrollTo({
        top: 0,
        left: 0,
        behavior: "smooth",
      });
    }
  });
});

// 厂家选择
const changeProvider = (id: number) => {
  providerId.value = id;
  active.value = -1;
  let obj = <any>{ ...searchData.value };
  obj.value = providerId.value;
  gameDetalStore.setSearchData(obj);
  // storage.setSessionStorage(actions.SEARCH_DATA, JSON.stringify(obj));
};

// 分类选择
const changeGameClass = (item: any) => {
  active.value = -1;
  gameClassId.value = item.gameClassId;
  let obj = <any>{ ...searchData.value };
  obj.value = gameClassId.value;
  gameDetalStore.setSearchData(obj);
  // storage.setSessionStorage(actions.SEARCH_DATA, JSON.stringify(obj));
};

// 开始搜索
function onSearch() {
  if (inputValue.value) {
    writeHistoricalData(inputValue.value);
  }
}

// 清除搜索框内容
function clear() {
  inputValue.value = "";
}
function goBack() {
  let obj = <any>{ ...searchData.value };
  obj.value = "";
  gameDetalStore.setSearchData(obj);
  inputValue.value = "";
  router.replace("/");
}
</script>
<style lang="scss" scoped>
.page {
  height: auto;
  overflow: inherit;
}
.page-body {
  .game-class {
    display: flex;
    overflow: auto;
    margin-top: 0.2rem;
    width: 100%;
    @extend .transition;
    @extend .not-select;

    &::-webkit-scrollbar {
      display: none;
    }
    .class-item {
      font-size: 0.3rem;
      padding: 1px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 0.1rem;
      min-width: 2rem;
      background: #33333d;
      border-radius: 0.1rem;
      color: #646c6b;
      border: 1px solid #33333d;
      div {
        white-space: nowrap;
        margin-left: 0.1rem;
        font-weight: 500;
      }
    }

    .class-typeItem {
      padding:.2rem;
    }
    
    .active {
      border: 1px solid #3359d8;
      color: #fff;
    }
  }
  .game-box {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 0.2rem;
    overflow-y: auto;
    &::-webkit-scrollbar {
      width: 0;
    }
    .data-all {
      > div {
        position: relative;
        display: flex;
      }
      img {
        width: 100%;
        height: 4.3rem;
        border-radius: 0.15rem;
      }
      .state-img {
        position: absolute;
        top: 0;
        right: 0;
        width: 1rem;
        z-index: 5;
      }
      .maintenance-box {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 6;
        background-color: rgba(0, 0, 0, 0.1);
      }
    }
  }
  .flex-sb {
    font-size: 0.3rem;
    margin: 0.3rem 0 0.2rem 0;
  }

  .num {
    font-size: 0.3rem;
    text-align: left;
    padding: 0.2rem 0;
  }
  .his {
    justify-content: left;
    font-size: 0.3rem;
    margin-top: 0.3rem;
    div {
      padding: 0.1rem 0.2rem;
      background-color: #21212a;
      margin-right: 0.2rem;
      border-radius: $border-radius;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .van-icon {
        margin-left: 0.3rem;
      }
    }
  }
  .recommend {
    padding-bottom: 2rem;
    &-list {
      font-size: 0.4rem;
      text-align: left;
      background-color: #21212a;
      margin: 0.2rem 0;
      padding: 0.1rem 0.2rem;
      border-radius: $border-radius;
    }
  }
}
:deep(.van-search) {
  padding: 0;
}
:deep(.van-search__content) {
  background-color: #06061a !important;
  border: 2px solid #2b3f3d;
  color: #fff;
  height: 40px;
  line-height: 40px;
  :deep(.van-cell) {
    padding: 0;
    background: transparent;
  }
}
:deep(.van-field__control) {
  color: #fff;
  font-size: 0.4rem;
  height: 40px;
}
:deep(.van-search__field) {
  height: 40px;
  padding: 0 0.2rem 0 0 !important;
  background: transparent !important;
  .van-icon-search {
    font-size: 0.6rem;
    font-weight: 800;
  }
}
</style>
