<template>
  <div
    class="home"
  >
    <div
      v-if="!store.state.loginStatus"
      class="for-visitor"
    >
      <button
        class="login"
        @click="onClickLogin"
      >
        <img
          class=""
          src="@/assets/images/btn-login-bg.png"
          alt=""
          draggable="false"
        >
        <span>登录</span>
      </button>
      <button
        class="sign-up"
        @click="onClickSignUp"
      >
        <img
          class=""
          src="@/assets/images/btn-sign-up-bg.png"
          alt=""
          draggable="false"
        >
        <span>注册</span>
      </button>
    </div>
    <div
      v-else
      class="after-login"
    >
      <img
        class="avatar"
        src="@/assets/images/avatar.png"
        alt=""
        draggable="false"
      >
      <div class="info-wrap">
        <div class="user-id">
          <span class="title">用户ID：</span>
          <span
            class="value"
            :title="store.state.userInfo.userName"
          >{{ store.state.userInfo.userName }}</span>
        </div>
        <div class="point-bonus">
          <span
            v-show="store.state.score !== null"
            class="title"
          >当前积分：</span>
          <span class="value">{{ store.state.score }}</span>
        </div>
      </div>
      <button
        class="change-password"
        @click="router.push({
          name: 'ChangePassword',
        })"
      >
        <img
          class=""
          src="@/assets/images/icon-password.png"
          alt=""
          draggable="false"
        >
      </button>
      <button
        class="logout"
        @click="onClickLogout"
      >
        <img
          class=""
          src="@/assets/images/icon-exit.png"
          alt=""
          draggable="false"
        >
      </button>
    </div>
    <div class="entry-list">
      <!-- 乡村林场 -->
      <button
        class="game-entry plant-tree-entry"
        @click="onClickGameEntry(0)"
      >
        <img
          class=""
          src="@/assets/images/plant-tree-entry.png"
          alt=""
          draggable="false"
        >
      </button>
      <!-- 助农课堂 -->
      <button
        class="game-entry exam-paper-entry"
        @click="onClickGameEntry(1)"
      >
        <img
          class=""
          src="@/assets/images/exam-paper-entry.png"
          alt=""
          draggable="false"
        >
      </button>
      <!-- 企业翻翻看 -->
      <button
        class="game-entry pair-up-entry"
        @click="onClickGameEntry(2)"
      >
        <img
          class=""
          src="@/assets/images/pair-up-entry.png"
          alt=""
          draggable="false"
        >
      </button>
      <!-- 抗体大作战 -->
      <button
        class="game-entry antibody-battle-entry"
        @click="onClickGameEntry(3)"
      >
        <img
          class=""
          src="@/assets/images/antibody-battle-entry.png"
          alt=""
          draggable="false"
        >
      </button>
      <!-- 应急救灾 -->
      <button
        class="game-entry disaster-relief-entry"
        @click="onClickGameEntry(4)"
      >
        <img
          class=""
          src="@/assets/images/disaster-relief-entry.png"
          alt=""
          draggable="false"
        >
      </button>
      <!-- 生态保护 -->
      <button
        class="game-entry enviroment-protection"
        @click="onClickGameEntry(5)"
      >
        <img
          class=""
          src="@/assets/images/enviroment-protection.png"
          alt=""
          draggable="false"
        >
      </button>
      <!-- 找回走失儿童 -->
      <button
        class="game-entry lost-children-entry"
        @click="onClickGameEntry(6)"
      >
        <img
          class=""
          src="@/assets/images/lost-children-entry.png"
          alt=""
          draggable="false"
        >
      </button>
    </div>

    <!-- 悬浮按钮 -->
    <div class="floating-btn-group">
      <button
        v-if="store.state.loginStatus"
        class="redeem"
        @click="router.push({
          name: 'ShopView'
        })"
      >
        <img
          class=""
          src="@/assets/images/icon-present.png"
          alt=""
          draggable="false"
        >
      </button>
      <button
        class="share"
        :data-clipboard-text="shareText"
      >
        <img
          class=""
          src="@/assets/images/icon-share.png"
          alt=""
          draggable="false"
        >
      </button>
      <button
        class="quit"
        @click="onClickQuit"
      >
        <img
          class=""
          src="@/assets/images/icon_home_2.png"
          alt=""
          draggable="false"
        >
      </button>
    </div>

    <!-- 让用户选择是否登录、注册 -->
    <LoginChoice
      v-show="isShowLoginChoice"
      class="login-choice"
      @login="onClickLogin"
      @signUp="onClickSignUp"
      @visitor="onLoginChoiceVisitor"
      @close="onLoginChoiceClose"
    />

    <van-loading
      v-show="isShowLoading"
      class="loading"
      type="spinner"
    />
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted, watchEffect } from "vue"
import { useRoute, useRouter } from "vue-router"
import { useStore } from "vuex"
import ClipboardJS from 'clipboard'
import { showDialog } from 'vant'
import { logout, getScore, notifyQuit } from '@/api.js'
import LoginChoice from '@/components/LoginChoice.vue'

const route = useRoute()
const router = useRouter()
const store = useStore()

const {
  windowSizeInCssForRef,
  windowSizeWhenDesignForRef,
} = useSizeAdapt(390, 752)

const loginStatus = computed(() => {
  return store.state.loginStatus
})
const gameRuleList = computed(() => {
  return store.state.gameRuleList
})
const score = computed(() => {
  return store.state.score
})
const ifScoreLimitReached = computed(() => {
  return store.state.ifScoreLimitReached
})
const scoreLimit = computed(() => {
  return store.state.scoreLimit
})

if (loginStatus.value) {
  getScore().then((res) => {
    store.commit('setScore', res.total)
    store.commit('setIfScoreLimitReached', res.hasOver)
  })
}

const isShowLoading = ref(true)
let hideLoadingCallback = null
watchEffect(() => {
  if (
    (loginStatus.value === false && gameRuleList.value.length > 0) ||
    (loginStatus.value === true && gameRuleList.value.length > 0 && score.value !== undefined && ifScoreLimitReached.value !== undefined && !scoreLimit.value !== undefined)
  ) {
    isShowLoading.value = false
    if (hideLoadingCallback) {
      hideLoadingCallback()
    }
  }
})


function onClickLogin() {
  router.push({
    name: 'LoginView',
  })
}

function onClickSignUp() {
  router.push({
    name: 'SignUp',
  })
}

function onClickLogout() {
  logout()
}

const shareText = location.href
const clipboard = new ClipboardJS('button.share')
clipboard.on('success', function(e) {
  showDialog({
    message: '链接已复制',
    theme: 'round-button',
  })
})
// clipboard.on('error', function(e) {
//   showDialog({
//       message: '请使用浏览器原生功能进行分享',
//       theme: 'round-button',
//     })
// });
onUnmounted(() => {
  clipboard.destroy()
})

const entryFunctionList = [
  function () {
    router.push({
      name: 'PlantTree',
    })
  },
  function () {
    router.push({
      name: 'ExamPaper1',
    })
  },
  function () {
    router.push({
      name: 'PairUp',
    })
  },
  function () {
    router.push({
      name: 'GameByUnity',
      query: {
        gameName: 'AntibodyBattle'
      },
    })
  },
  function () {
    router.push({
      name: 'GameByUnity',
      query: {
        gameName: 'DisasterRelief'
      },
    })
  },
  function () {
    router.push({
      name: 'GameByUnity',
      query: {
        gameName: 'EnviromentProtection'
      },
    })
  },
  function () {
    router.push({
      name: 'GameByUnity',
      query: {
        gameName: 'LostChildren'
      },
    })
  },
]
const isShowLoginChoice = ref(false)

function onClickGameEntry(idx) {
  if (store.state.loginStatus) {
    entryFunctionList[idx]()
  } else {
    store.commit('setGameToPlayIdx', idx)
    isShowLoginChoice.value = true
  }
}

function onLoginChoiceVisitor() {
  const gameIdx = store.state.gameToPlayIdx
  store.commit('setGameToPlayIdx', null)
  isShowLoginChoice.value = false
  entryFunctionList[gameIdx]()
}
function onLoginChoiceClose() {
  store.commit('setGameToPlayIdx', null)
  isShowLoginChoice.value = false
}

// 如果是点击游戏入口触发了登录、注册，且登录、注册完毕后回到首页，需要自动进入游戏页。
// 如果是点击游戏入口触发了登录，但登录、注册未成功即回到首页，则不应自动进入游戏页。
if (store.state.gameToPlayIdx !== null) {
  const gameIdx = store.state.gameToPlayIdx
  store.state.gameToPlayIdx = null
  if (store.state.loginStatus) {
    entryFunctionList[gameIdx]()
  }
}

// 如果通过url要求自动进入游戏页
if (route.query.gameIdx) {
  const gameIdx = Number(route.query.gameIdx)
  router.replace({
    name: route.name
  })
  store.commit('setIsDirectPlayGame', true)
  if (isShowLoading.value) {
    hideLoadingCallback = () => {
      onClickGameEntry(gameIdx)
    }
  } else {
    onClickGameEntry(gameIdx)
  }
}

function onClickQuit() {
  notifyQuit()
}
</script>

<style lang="less" scoped>
.home {
  width: 100%;
  height: 100%;
  overflow: auto;
  >.for-visitor{
    margin-top: calc(15 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    margin-bottom: calc(18 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-left: calc(16 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    padding-right: calc(16 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    >button{
      width: calc(165 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      position: relative;
      >img{
        width: 100%;
        height: 100%;
      }
      >span{
        position: absolute;
        left: calc(95 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        top: calc(32 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        font-size: calc(24 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        font-family: Source Han Sans SC, Source Han Sans SC;
        font-weight: bold;
        color: #A97C46;
        line-height: calc(28 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      }
    }
  }
  >.after-login{
    margin-top: calc(25 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    margin-bottom: calc(15 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    display: flex;
    align-items: center;
    padding-left: calc(12 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    padding-right: calc(12 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    padding-top: calc(13 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    padding-bottom: calc(13 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    background: rgba(226, 201, 163, 0.5);
    box-shadow: inset -1px -2px 1px 0px #E2C9A3;
    border-radius: calc(4 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    margin-left: calc(16 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    margin-right: calc(16 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    >img.avatar{
      flex: 0 0 auto;
      width: calc(54 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      height: calc(54 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      border-radius: calc(27 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      object-fit: cover;
    }
    >.info-wrap{
      flex: 0 0 auto;
      margin-left: calc(16 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      font-size: calc(16 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      font-family: Source Han Sans SC, Source Han Sans SC;
      font-weight: 400;
      color: #A97C46;
      line-height: 1.5;
      white-space: pre;
      >.user-id{
        >.title{
          vertical-align: middle;
          display: inline-block;
          width: calc(69 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
          letter-spacing: calc(4 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
          margin-right: calc(10 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        }
        >.value{
          vertical-align: middle;
          display: inline-block;
          overflow: hidden;
          white-space: pre;
          text-overflow: ellipsis;
          width: calc(80 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        }
      }
      >.point-bonus{
        >.title{
          vertical-align: middle;
          display: inline-block;
          width: calc(69 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
          margin-right: calc(10 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        }
        >.value{
          vertical-align: middle;
          display: inline-block;
          overflow: hidden;
          white-space: pre;
          text-overflow: ellipsis;
          width: calc(80 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));

        }
      }
    }
    >button.change-password{
      flex: 0 0 auto;
      width: calc(32 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      margin-left: calc(12 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      >img{
        width: 100%;
      }
    }
    >button.logout{
      flex: 0 0 auto;
      width: calc(32 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      margin-left: calc(12 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      >img{
        width: 100%;
      }
    }
  }
  >.entry-list{
    margin-left: calc(10 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    margin-right: calc(10 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    >button.game-entry{
      width: 100%;
      >img{
        width: 100%;
      }
    }
  }
  >.floating-btn-group{
    position: fixed;
    right: calc(11 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    bottom: calc(58 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    >button{
      width: calc(60 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      height: calc(60 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      display: block;
      >img{
        width: 100%;
        height: 100%;
      }
    }
  }
  >.loading{
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>