import { defineComponent } from 'vue'
import styles from './index.module.less'
import { state, setLogin, setLogout, setLoginError } from '@/state'
import { browser, removeAuth } from '@/helpers/utils'
import { setAuth } from './utils'
import { RouterView } from 'vue-router'

import request from './request-home'
import ColResult from '@/components/col-result'
import { promisefiyPostMessage } from '@/helpers/native-message'

const browserInfo = browser()
export default defineComponent({
  name: 'Auth-loayout',
  data() {
    return {
      loading: false as boolean
    }
  },
  computed: {
    isExternal() {
      // 该路由在外部连接打开是否需要登录
      // 只判断是否在学生端打开
      return (this.$route.meta.isExternal && !browserInfo.isStudent) || false
    },
    isNeedView() {
      return (
        state.user.status === 'login' ||
        this.$route.path === '/home-auth' ||
        this.$route.path === '/home-login' ||
        this.$route.path === '/home-layout-center' ||
        (this as any).isExternal
      )
    }
  },
  mounted() {
    !this.isExternal && this.setAuth()
    if (!state.orchestraInfo.unionId) {
      removeAuth()
    }
  },
  methods: {
    async setAuth() {
      const { query } = this.$route
      const token = query.userInfo || query.Authorization
      if (token) {
        setAuth(token)
      }
      if (this.loading) {
        return
      }
      if (state.user.status === 'init' || state.user.status === 'error') {
        this.loading = true

        try {
          // 判断是否已经有关联编号
          if (state.orchestraInfo.unionId) {
            const res = await request.post('/api-auth/smsLogin', {
              requestType: 'form',
              data: {
                clientId: 'student',
                clientSecret: 'student',
                phone: state.orchestraInfo.phone,
                token: state.orchestraInfo.token,
                isSurportRegister: true
              }
            })
            const { authentication } = res.data
            setAuth(
              authentication.token_type + ' ' + authentication.access_token
            )
            promisefiyPostMessage({
              api: 'setCache',
              content: {
                key: 'h5-colexiu-token',
                value:
                  authentication.token_type + ' ' + authentication.access_token
              }
            })
          }

          const res = await request.get('/api-student/student/queryUserInfo', {
            initRequest: true, // 初始化接口
            requestType: 'form'
          })
          setLogin(res.data)
        } catch (e: any) {
          // console.log(e, 'e')
          const message = e.message
          if (
            message.indexOf('5000') === -1 &&
            message.indexOf('authentication') === -1
          ) {
            setLoginError()
          } else {
            setLogout()
          }
        }
        this.loading = false
      }
      if (state.user.status === 'logout') {
        try {
          const route = this.$route
          const query = {
            returnUrl: this.$route.path,
            ...this.$route.query
          } as any
          if (route.meta.isRegister) {
            query.isRegister = route.meta.isRegister
          }
          this.$router.replace({
            path: '/home-auth',
            query: query
          })
        } catch (error) {
          //
        }
      }
    }
  },
  render() {
    return (
      <>
        {state.user.status === 'error' ? (
          <div class={styles.error}>
            <ColResult
              type="notFond"
              classImgSize="CERT"
              tips="加载失败，请稍后重试"
              buttonText="重新加载"
              plain={true}
              onClick={this.setAuth}
            />
          </div>
        ) : this.isNeedView ? (
          <RouterView></RouterView>
        ) : null}
      </>
    )
  }
})
