<template>
  <div id="app">
    <div class="c-main">
      <div class="c-wrap" v-if="toApp">
        <panel></panel>
        <router-view></router-view>
      </div>
      <div v-else class="c-login">
        <login-box></login-box>
      </div>
    </div>
    <div class="c-copyright">
      <span>copyright © 2019 MeeChat.</span>
    </div>
  </div>
</template>

<script>
import ScatterJS from 'scatter-js/dist/scatter.esm'
import { showError } from '@/util/util.js'
import { mapActions, mapState } from 'vuex'

import loginBox from '@/components/login/loginBox'
import panel from '@/components/panel/panel'

export default {
  name: 'App',
  components: {
    loginBox,
    panel
  },
  computed: {
    ...mapState({
      isLogin: state => state.chat.isLogin,
      toApp: state => state.chat.toApp,
      curSession: state => state.curSession
    })
  },
  methods: {
    ...mapActions([
      'setScatter',
      'setAccount',
      'doScatterLogin',
      'doContractLogin',
      'initSocket'
    ])
  },
  async created () {
    // 连接scatter
    ScatterJS.scatter.connect('MEE_CHAT').then(async connected => {
      if (connected) {
        // 设置scatter
        this.setScatter(ScatterJS.scatter)

        // 清空全局scatter引用
        window.ScatterJS = null

        try {
          // 调起scatter授权登录
          await this.doScatterLogin()
          // 签名登录
          await this.doContractLogin()

          await this.initSocket()

          this.$store.commit('chatAppLogin', true)
          this.$store.commit('toApp', true)
        } catch (error) {
          this.$store.commit('chatAppLogin', false)
        }
      } else {
        // 用户scatter未解锁
        showError(this.$t('installScatter'), 'Scatter')

        this.setAccount('')
      }
    })
  },
  mounted () {
    // 监听浏览器切换事件
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState !== 'hidden') {
        // 切换回当前页面
        document.title = 'MeeChat'
      }
    })
    window.$router = this.$router
  }
}
</script>

<style lang="scss">
@import "@/style/global.scss";
</style>

<style lang="scss" scoped>
.c-main {
  height: 80%;
  min-height: 600px;
  padding-top: 100px;
  -webkit-transition: padding 0.3s linear;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}
@media (max-height: 800px), (max-width: 1000px) {
  .c-main {
    padding-top: 0;
    height: 100%;
  }
  .c-copyright {
    display: none;
  }
}
.c-wrap {
  display: flex;
  max-width: 1066px;
  min-width: 800px;
  height: 100%;
  margin: 0 auto;
  border-radius: 3px;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  overflow: hidden;
}
.c-copyright {
  position: absolute;
  bottom: 30px;
  width: 100%;
  text-align: center;
  font-size: 12px;
  color: #e3e3e3;
}
</style>
