<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 { getCookies } from '@/utils/auth'
import keys from '@/keys.config'
import { mapGetters } from 'vuex'
export default {
  computed: {
    ...mapGetters(['userInfo', 'type', 'accessToken', 'authUserId']),
  },
  data() {
    return {
      isMounted: false,
    }
  },
  mounted() {
    this.init()
  },
  beforeDestroy() {
    window.removeEventListener('resize', () => {})
  },
  methods: {
    init() {
      this.responseWidth()
      this.initPageData()
    },
    // 初始化数据页面公共数据
    initPageData() {
      const id = this.$route.params.template
      // 保存页面入口
      this.$store.commit('user/SET_TYPE', `${id}/app`)
      // 保存用户AppId
      this.$store.commit('user/SET_AUTHUSERID', id)

      // 获取用户信息
      const userInfo = getCookies('userInfo')
      if (userInfo && userInfo.authUserId === id) {
        this.$store.commit('user/SET_USERINFO', JSON.parse(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)
      } catch (error) {
        console.log(error)
      } finally {
        this.isMounted = true
      }
    },

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

    // 回到首页
    backHome() {
      const url = '/' + this.type
      if (this.$route.path === url) return
      this.$router.replace(url)
    },

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

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