<script>
import Person from './Person.vue'
// import Login from './Login.vue'
import BScroll from '@better-scroll/core'
import MouseWheel from '@better-scroll/mouse-wheel'
BScroll.use(MouseWheel)
import { getAccountCenterAsync } from '@/api/common'
import { getToken, logout, removeToken, navToLogin } from '@/utils/login-helper.ts'
import '@/store/store'
import bus from 'vue3-eventbus'
import { PLATFORMS_KEY, USERNAME_KEY } from '@/constants'
import { useWindowSize } from '@vueuse/core'

const marginRight = 64
let bs

export default {
  props: {
    headerTitle: {
      type: String,
      default: 'AI平台'
    },
    clickAppkey: {
      type: String, //选中的平台appkey
      default: ''
    },
    platformType: { // license-web,license-client需要单独处理
      type: String,
      default: ''
    },
  },
  components: {
    Person,
  },
  data() {
    return {
      visibleLogin: false,
      token: getToken(),
      platforms: JSON.parse(sessionStorage.getItem(PLATFORMS_KEY)) || [],
      username: localStorage.getItem(USERNAME_KEY) || '未知用户',
      refPlatform: null,
      refPlatformList: null,
      wrapWidth: null,
      listWidth: null,
    }
  },
  created() {
    // 初次获取token
    const token = getToken()
    // 如果有token
    if (token) {
      this.handleLoginSuccess()
    } else {
      this.visibleLogin = true
      // debugger
      navToLogin()
    }

    // 监听relogin，axios/index.js里面触发
    bus.on('relogin', this.handleRelogin)
    window.addEventListener('resize', this.handleWindowResize, false)

    bus.on('gotoLogin', (path) => {
      this.$router.push({ path })
    })
  },
  watch: {
    // 监听平台列表platforms的变化，重新计算宽度
    platforms: {
      async handler(val) {
        await nextTick()
        this.handleWindowResize()
        // 初始化BScroll
        if (!bs && this.$refs.refPlatform) {
          bs = new BScroll(this.$refs.refPlatform, {
            scrollX: true,
            scrollY: false,
            mouseWheel: {
              speed: 20,
              invert: false,
              easeTime: 200
            }
          })
        }
        // 等待列表渲染完成，不然可能无法滚动到对应元素
        await nextTick()
        this.setActiveIndex(bs)
      },
      immediate: true
    },
  },
  mounted() {
    bus.emit('getAppKey', this.clickAppkey)
  },
  methods: {
    handleLogoClick() {
      // TODO
      window.location.href = '/'
    },
    // 平台列表
    clickPlatform(item, isMiddle = false) {
      const tokenParam = getToken() ? `?token=${getToken()}` : ''
      // 支持鼠标中键
      if (isMiddle) {
        window.open(item.url + tokenParam)
      } else {
        window.location = item.url + tokenParam
      }
    },
    // 获取平台列表
    getPlatformList() {
      return getAccountCenterAsync().then(res => {
        if (res.status === 200) {
          const user = res.data
          this.username = user.account
          // 排序
          this.platforms = (user.platforms || []).sort((a, b) => a.order - b.order > 0 ? 1 : -1)
          // 如果当前用户没有此平台的权限
          const findPlatform = this.platforms.find(v => v.appKey === this.clickAppkey)
          if (!findPlatform) {
            // 生产环境跳转：您当前没有该平台的权限！
            if (import.meta.env.PROD) {
              debugger
              clickPlatform(this.platforms[0])
            }
            bus.emit('getAppName', this.platforms[0]?.name)
          } else {
            bus.emit('getAppName', findPlatform?.name)
          }
          // 缓存
          sessionStorage.setItem(PLATFORMS_KEY, JSON.stringify(this.platforms))
          localStorage.setItem(USERNAME_KEY, this.username)
          this.$emit('getUser', user)
        }
      })
    },
    // 登录成功回调
    handleLoginSuccess() {
      const token = getToken()
      let timer = null
      if (token) {
        // 如果100ms内接口没有报错，不用等待接口返回，则直接判定登录成功
        timer = setTimeout(() => {
          this.$emit('loginSuccess')
          timer && window.clearTimeout(timer)
          timer = null
        }, 150)
        this.getPlatformList().then(() => {
          // 如果接口在100ms内返回，则直接执行回调
          if (timer) {
            this.$emit('loginSuccess')
            timer && window.clearTimeout(timer)
            timer = null
          }
        }).catch(error => {
          // 如果接口报错则清除timer，防止执行loginSuccess回调
          timer && clearTimeout(timer)
          this.visibleLogin = true
        })
        this.visibleLogin = false
      } else {
        this.visibleLogin = true
      }
    },
    // 处理重新登录
    handleRelogin() {
      removeToken()
      this.visibleLogin = true
      // debugger
    },
    handleWindowResize() {
      const { width } = useWindowSize()
      this.wrapWidth = width.value - 300 + 'px'
      // 计算所有子节点的宽度
      if (this.$refs.refPlatformList) {
        const itemList = [...this.$refs.refPlatformList.querySelectorAll('.platform-item')]
        const arr = []
        itemList.forEach(v => {
          const width = v.getBoundingClientRect().width
          arr.push(width)
        })
        try {
          const innerWidth = arr.reduce((a, b) => a + b) + (itemList.length - 1) * marginRight
          this.listWidth = innerWidth + 'px'
        } catch (error) {
          console.log(error)
        }
      }
      // 重置
      bs && this.setActiveIndex(bs)
    },
    setActiveIndex(bs) {
      if (!bs || !this.$refs.refPlatformList) return
      const activeIndex = this.platforms.findIndex(v => v.appKey === this.clickAppkey)
      const itemList = this.$refs.refPlatformList.querySelectorAll('.platform-item')
      try {
        bs.refresh().scrollToElement(itemList[activeIndex])
      } catch (error) {
        itemList[0] && bs.scrollToElement(itemList[0])
      }
    },
    handleLogout() {
      logout()
      bus.emit('logout')
    },
  },
}

</script>

<template>
  <header id="header" class="flex-space select-none">
    <div class="header-logo" @click="handleLogoClick">
      <h2 class="mx-20px header-title pointer nowrap hover-primary">{{ headerTitle }}</h2>
    </div>
    <div ref="refPlatform" class="platform-list-wrap" :style="{ width: wrapWidth }">
      <div ref="refPlatformList" class="platform-list nowrap" :style="{ width: listWidth }">
        <div
          class="platform-item"
          @click.left="clickPlatform(item)"
          @click.middle="clickPlatform(item, true)"
          v-for="item in platforms"
          :key="item.appKey"
          :class="{ 'active': clickAppkey === item.appKey }"
        >
          <h3>{{ item.name }}</h3>
          <div class="line" v-if="clickAppkey === item.appKey"></div>
        </div>
      </div>
    </div>
    <div class="flex-alignC">
      <Person @logout="handleLogout" :username="username" />
    </div>
    <!-- <Login v-if="visibleLogin" @loginSuccess="handleLoginSuccess"></Login> -->
  </header>
</template>

<style>
@import url('@/styles/index.scss');
</style>
<style lang="scss" scoped>
#header {
  width: 100%;
  min-width: 1100px;
  height: 50px;
  line-height: 50px;
  // background: url(../../../assets/img/headerBG.png);
  background-color: #fff;
  background-size: 100% 100%;
  border-bottom: 1px solid #dbdeea;
  .header-logo {
    .header-title {
      font-size: 18px;
      font-weight: 600;
    }
  }
  .platform-list-wrap {
    overflow: hidden;
    margin: 0 32px;
    display: flex;
    flex: 1;
    justify-content: center;
  }
  .platform-list {
    display: flex;
    .platform-item {
      height: 50px;
      margin-right: 64px;
      box-sizing: border-box;
      border-bottom: 3px solid transparent;
      transition: 0.2s;
      cursor: pointer;
      &:last-child {
        margin-right: 0;
      }
      &:hover,
      &.active {
        border-bottom: 3px solid var(--color-primary);
        color: var(--color-primary);
      }
      .line {
        width: 50px;
        height: 3px;
        background: rgba(255, 255, 255, 0.6);
        border-radius: 1.5px;
        margin: -11px auto 0px;
        transition: width 0.8s;
      }
    }
    h3 {
      font-family: 'PingFang SC';
      font-style: normal;
      font-weight: 400;
      font-size: 14px;
    }
  }
}
</style>
