import { computed, defineComponent, onMounted, reactive, watch } from 'vue';
import styles from './auth.module.less';
import { state, setLogin, setLogout, setLoginError } from '@/state';
import { browser } from '@/helpers/utils';
import { storage } from '@/helpers/storage';
import { ACCESS_TOKEN } from '@/store/mutation-types';
import { postMessage } from '@/helpers/native-message';
import { RouterView, useRoute, useRouter } from 'vue-router';
import request from '@/helpers/request';
import MHeader from '@/components/m-header';
import MEmpty from '@/components/m-empty';

export default defineComponent({
  name: 'Auth-loayout',
  setup() {
    const route = useRoute();
    const router = useRouter();
    const data = reactive({
      loading: false
    });
    const isExternal = computed(() => {
      //  该路由在外部连接打开是否需要登录
      // 只判断是否在学员端打开
      return route.meta.isExternal || false;
    });
    const isNeedView = computed(() => {
      return (
        state.user.status === 'login' ||
        route.path === '/login' ||
        isExternal.value
      );
    });

    const setAuth = async () => {
      const { query } = route;
      const token = query.userInfo || query.Authorization;

      if (token) {
        storage.set(ACCESS_TOKEN, token);
      }
      if (data.loading) {
        return;
      }
      if (state.user.status === 'init' || state.user.status === 'error') {
        data.loading = true;
        try {
          const res = await request.get('/edu-app/user/getUserInfo', {
            initRequest: true, // 初始化接口
            requestType: 'form',
            hideLoading: true
          });
          if (res?.code === 200) {
            setLogin(res.data);
          }
        } catch (e: any) {
          const message = e.message;
          if (
            message.indexOf('5000') === -1 &&
            message.indexOf('authentication') === -1
          ) {
            setLoginError();
          } else {
            setLogout();
          }
        }
        data.loading = false;
      }
    };
    const checkAuthStatus = () => {
      if (state.user.status === 'logout') {
        if (browser().isApp) {
          postMessage({ api: 'login' });
        } else {
          try {
            const query = {
              returnUrl: route.path,
              ...route.query
            } as any;
            if (route.meta.isRegister) {
              query.isRegister = route.meta.isRegister;
            }
            router.replace({
              path: '/login',
              query: query
            });
          } catch (error) {
            //
          }
        }
      }
    };
    watch(
      () => state.user.status,
      () => {
        if (state.user.status === 'logout') {
          checkAuthStatus();
        }
      }
    );

    onMounted(() => {
      !isExternal.value && setAuth();
    });
    return () => (
      <>
        {state.user.status === 'error' ? (
          <div class={styles.error}>
            <MHeader />
            <MEmpty
              image="network"
              description="加载失败，请稍后重试"
              buttonText="重新加载"
              showButton
              onClick={setAuth}
            />
          </div>
        ) : isNeedView.value ? (
          <RouterView></RouterView>
        ) : null}
      </>
    );
  }
});
