<template>
  <router-view v-if="ready" />
</template>

<script>
import { mapMutations, mapActions } from 'vuex'

export default {
  data () {
    return {
      ready: false,
    }
  },
  methods: {
    ...mapMutations('user', {
      updateUser: 'UPDATE_USER',
    }),
    ...mapActions('user', {
      refreshUser: 'refresh',
    }),
    async checkUser () {
      // 作为子站点打开
      if (this.isMinion) return this.pushMessage('sign')
      // 独立打开
      const token = window.localStorage.getItem('token')
      const ttl = window.localStorage.getItem('token_ttl')
      if (token && ttl && new Date() < new Date(Number(ttl))) {
        try {
          await this.refreshUser()
        } catch {
          this.goSign()
        }
      } else this.goSign()
    },
    goSign () {
      this.$router.replace({ name: 'sign' })
    },
    pushMessage (type, payload = {}) {
      const { SYSTEM_NAME, MAIN_URL } = process.env
      window.parent.postMessage({
        system: SYSTEM_NAME,
        type,
        payload,
      }, MAIN_URL)
    },
    receiveMessage ({ data: { type, payload }, origin }) {
      if (origin === window.origin) return
      const messageTypes = {
        sign: () => {
          this.updateUser(payload)
          this.ready = true
          this.pushMessage('ready')
        },
        view: () => {
          this.$router.push({ path: `/${payload.view}/` })
        },
      }
      if (messageTypes[type]) messageTypes[type]()
    },
  },
  mounted () {
    window.UPLOAD_URL = process.env.API_URL.upload ||
      `${process.env.API_URL.default}config/upload`
    const handleError = (content, cb) => {
      this.$Message.error({ content })
      if (cb) cb()
    }
    this.isMinion = this.$store.state.isMinion
    this.ready = !this.isMinion

    this.$hub.$on('GLOBAL_AUTH_ERROR', ({ message }) => {
      handleError(message, () => {
        if (this.isMinion) return this.pushMessage('sign', { resign: true })
        this.$router.replace({ name: 'sign' })
      })
    })
    this.$hub.$on('GLOBAL_ERROR', ({ message }) => {
      handleError(message)
    })
    window.addEventListener('message', this.receiveMessage, false)
    this.checkUser()
  },
}
</script>
