<template>
  <div class="layout" v-if="isMounted">
    <div class="header"></div>
    <div class="content">
      <nuxt />
    </div>
    <div class="footer"></div>
    <ldm-login></ldm-login>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  computed: {
    ...mapGetters([
      'userInfo',
      'accessToken',
      'authUserId',
      'appId',
      'accountType',
      'routePrefix',
    ]),
  },
  head() {
    return {
      title: '德国WELLCOMET LDM® 官方查询系统',
      link: [{ rel: 'icon', type: 'image/x-icon', href: '/ldm.ico' }],
    }
  },
  data() {
    return {
      isMounted: false,
    }
  },
  mounted() {
    this.init()
  },
  beforeDestroy() {
    window.removeEventListener('resize', () => {})
  },
  methods: {
    init() {
      this.responseWidth()
      this.initPageData()
    },
    // 初始化数据页面公共数据
    initPageData() {
      // 获取供应商id
      const authUserId = parseInt(this.$route.params.template)
      const routePrefix = `/${authUserId}/ldm`
      // 保存页面路由前缀
      this.$store.commit('app/SET_ROUTE_PREFIX', routePrefix)
      // 保存用户AppId
      this.$store.commit('user/SET_AUTH_USER_ID', authUserId)

      // 获取用户信息
      let userInfo = this.$getStorage(routePrefix, 'userInfo')
      if (userInfo && userInfo.authUserId === authUserId) {
        this.$store.commit('user/SET_USER_INFO', userInfo)
      }
      // 初始化供应商信息
      this.fetchSupplierInfo()
    },

    // 获取供应商信息
    async fetchSupplierInfo() {
      try {
        const res = await this.$http.api.fetchSupplierInfo({
          authUserId: this.authUserId,
        })
        this.$store.commit('supplier/SET_SUPPLIER_INFO', res.data)
        this.$store.commit('user/SET_APPID', res.data.appId)
        // 如果appId存在
        if (res.data.appId) {
          this.checkAccountType(res.data.appId)
        }
      } catch (error) {
        console.log(error)
      } finally {
        this.isMounted = true
        // 清除缓存
        this.refreshCacheData()
      }
    },

    // 校验公众号类型
    async checkAccountType(appId) {
      try {
        // 1订阅号，2服务号
        const res = await this.$http.api.checkAccountType({ appId })
        this.$store.commit('user/SET_ACCOUNT_TYPE', res.data)
      } catch (error) {
        console.log(error)
      }
    },

    // 退出登录
    logout() {
      this.$store.dispatch('user/logout')
      this.$removeStorage(this.routePrefix, 'userInfo')
      this.backHome()
    },

    // 回到首页
    backHome() {
      if (this.$route.path === this.routePrefix) return
      this.$router.replace(this.routePrefix)
    },

    // 响应页面宽度变化
    responseWidth() {
      this.$store.commit('app/SET_SCREEN', window.innerWidth)
      window.addEventListener('resize', (e) => {
        this.$store.commit('app/SET_SCREEN', e.target.innerWidth)
      })
    },

    // 数据初始化刷新浏览器
    refreshCacheData() {
      this.$removeStorage(this.routePrefix, 'club_list_data')
    },
  },
}
</script>

<style scoped lang="scss"></style>
