import { defineComponent } from "vue";
import styles from './auth.module.less';
import { state, setLogin } from '@/state';
import { browser, setAuth } from "@/helpers/utils";
import { postMessage } from "@/helpers/native-message";
import { RouterView } from "vue-router";
import { Button, Icon } from "vant";
import request from "@/helpers/request";

export default defineComponent({
  name: "Auth",
  data() {
    return {
      loading: false as boolean,
    }
  },
  computed: {
    isNeedView() {
      return state.user.status === 'login' || this.$route.path === '/login';
    }
  },
  mounted() {
    this.setAuth();
  },
  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 {
          let res = await request.get('/api-auth/api/queryUserInfo', {
            initRequest: true // 初始化接口
          })
          // console.log(res)
          setLogin(res.data)
        } catch (e: any) {
          // console.log(e)
        }
        this.loading = false
      }
      if (state.user.status === 'logout') {
        if (browser().isApp) {
          postMessage({ api: 'login' })
        } else {
          try {
            let route = this.$route
            let query = {
              returnUrl: this.$route.path,
              ...this.$route.query,
            } as any;
            if (route.meta.isRegister) {
              query.isRegister = route.meta.isRegister
            }
            this.$router.replace({
              path: '/login',
              query: query
            })
          } catch (error) { }
        }
      }
    }
  },
  render() {
    return (
      <>
        {state.user.status === 'error' ? <div class={styles.error}>
          <div class={styles.info}>
            <Icon name="clear" size="36" color="#ee0a24" />
            <span>加载失败，请重新尝试</span>
          </div>
          <Button type="primary" round onClick={this.setAuth}>重新加载</Button>
        </div> : this.isNeedView ? <RouterView></RouterView> : null}
      </>
    )
  }
})