import { computed, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { defineStore } from 'pinia';
import { useLoading } from '@sa/hooks';
import { SetupStoreId } from '@/enum';
import { useRouterPush } from '@/hooks/common/router';
import { fetchGetUserInfo, fetchLogin } from '@/service/api';
import { localStg } from '@/utils/storage';
import { $t } from '@/locales';
import { useRouteStore } from '../route';
import { useTabStore } from '../tab';
import { clearAuthStorage, getToken } from './shared';
import { api_login } from '@/api/index.ts';
import axios from 'axios'

export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
  const route = useRoute();
  const routeStore = useRouteStore();
  const tabStore = useTabStore();
  const { toLogin, redirectFromLogin } = useRouterPush(false);
  const { loading: loginLoading, startLoading, endLoading } = useLoading();

  const routes = reactive([
    {
      name: '403',
      path: '/403',
      component: 'layout.blank$view.403',
      meta: {
        title: '403',
        i18nKey: 'route.403',
        constant: true,
        hideInMenu: true
      }
    },
    {
      name: '404',
      path: '/404',
      component: 'layout.blank$view.404',
      meta: {
        title: '404',
        i18nKey: 'route.404',
        constant: true,
        hideInMenu: true
      }
    },
    {
      name: '500',
      path: '/500',
      component: 'layout.blank$view.500',
      meta: {
        title: '500',
        i18nKey: 'route.500',
        constant: true,
        hideInMenu: true
      }
    },
    {
      name: 'alarmcenter',
      path: '/alarmcenter',
      component: 'layout.base',
      meta: {
        title: 'alarmcenter',
        i18nKey: 'route.alarmcenter',
        order: 7,
        icon: 'ic:twotone-hearing'
      },
      children: [
        {
          name: 'alarmcenter_alarmlog',
          path: '/alarmcenter/alarmlog',
          component: 'view.alarmcenter_alarmlog',
          meta: {
            title: 'alarmcenter_alarmlog',
            i18nKey: 'route.alarmcenter_alarmlog',
            icon: 'ic:sharp-receipt-long'
          }
        },
        {
          name: 'alarmcenter_alarmpush',
          path: '/alarmcenter/alarmpush',
          component: 'view.alarmcenter_alarmpush',
          meta: {
            title: 'alarmcenter_alarmpush',
            i18nKey: 'route.alarmcenter_alarmpush',
            icon: 'ic:sharp-notifications-active'
          }
        },
        {
          name: 'alarmcenter_alarmreminder',
          path: '/alarmcenter/alarmreminder',
          component: 'view.alarmcenter_alarmreminder',
          meta: {
            title: 'alarmcenter_alarmreminder',
            i18nKey: 'route.alarmcenter_alarmreminder',
            icon: 'ic:baseline-legend-toggle'
          }
        }
      ]
    },
    {
      name: 'algorithmconfiguration',
      path: '/algorithmconfiguration',
      component: 'layout.base$view.algorithmconfiguration',
      meta: {
        title: 'algorithmconfiguration',
        i18nKey: 'route.algorithmconfiguration',
        order: 2,
        icon: 'ic:outline-storage'
      }
    },
    {
      name: 'home',
      path: '/home',
      component: 'layout.base$view.home',
      meta: {
        title: 'home',
        i18nKey: 'route.home',
        icon: 'mdi:monitor-dashboard',
        order: 0
      }
    },
    {
      name: 'iframe-page',
      path: '/iframe-page/:url',
      component: 'layout.base$view.iframe-page',
      props: true,
      meta: {
        title: 'iframe-page',
        i18nKey: 'route.iframe-page',
        constant: true,
        hideInMenu: true,
        keepAlive: true
      }
    },
    {
      name: 'login',
      path: '/login/:module(pwd-login|code-login|register|reset-pwd|bind-wechat)?',
      component: 'layout.blank$view.login',
      props: true,
      meta: {
        title: 'login',
        i18nKey: 'route.login',
        constant: true,
        hideInMenu: true
      }
    },
    {
      name: 'manage',
      path: '/manage',
      component: 'layout.base',
      meta: {
        title: 'manage',
        i18nKey: 'route.manage',
        icon: 'carbon:cloud-service-management',
        order: 9,
      },
      children: [
        {
          name: 'manage_role',
          path: '/manage/role',
          component: 'view.manage_role',
          meta: {
            title: 'manage_role',
            i18nKey: 'route.manage_role',
            icon: 'carbon:user-role',
            order: 2,
          }
        },
        {
          name: 'manage_user',
          path: '/manage/user',
          component: 'view.manage_user',
          meta: {
            title: 'manage_user',
            i18nKey: 'route.manage_user',
            icon: 'ic:round-manage-accounts',
            order: 1,
          }
        }
      ]
    },
    {
      name: 'user-center',
      path: '/user-center',
      component: 'layout.base$view.user-center',
      meta: {
        title: 'user-center',
        i18nKey: 'route.user-center',
        hideInMenu: true
      }
    },
    {
      name: 'videoanalysistask',
      path: '/videoanalysistask',
      component: 'layout.base$view.videoanalysistask',
      meta: {
        title: 'videoanalysistask',
        i18nKey: 'route.videoanalysistask',
        order: 3,
        icon: 'ic:outline-candlestick-chart'
      }
    },
    {
      name: 'webcamconfiguration',
      path: '/webcamconfiguration',
      component: 'layout.base$view.webcamconfiguration',
      meta: {
        title: 'webcamconfiguration',
        i18nKey: 'route.webcamconfiguration',
        order: 2,
        icon: 'ic:outline-video-camera-back'
      }
    }
  ]);


  const token = ref(getToken());

  const userInfo: Api.Auth.UserInfo = reactive({
    userId: '',
    routes:[],
    userName: '',
    roles: [],
    buttons: []
  });

  /** is super role in static route */
  const isStaticSuper = computed(() => {
    const { VITE_AUTH_ROUTE_MODE, VITE_STATIC_SUPER_ROLE } = import.meta.env;

    return VITE_AUTH_ROUTE_MODE === 'static' && userInfo.roles.includes(VITE_STATIC_SUPER_ROLE);
  });

  /** Is login */
  const isLogin = computed(() => Boolean(token.value));

  /** Reset auth store */
  async function resetStore() {
    const authStore = useAuthStore();

    clearAuthStorage();

    authStore.$reset();

    if (!route.meta.constant) {
      await toLogin();
    }

    tabStore.cacheTabs();
    routeStore.resetStore();
  }

  // ============================================================================= Login Function | S
  /**
   * Login Page
   * @param userName User name
   * @param password Password
   * @param [redirect=true] Whether to redirect after login. Default is `true`
   */
  async function login(userName: string, password: string, redirect = true) {

    startLoading();

    // let loginToken;
    // let error;


    const toLogin = async (userName, password) => {
      return await axios.post('/logins/login', { userName, password });
    };


    // 登录注册
    // try {
    //   await toLogin(userName, password);
    // } catch (e) {
    //   error = e;
    // }
    // ================= 登录注册 | E

    const { data: loginToken, error } = await toLogin(userName, password);

    // let loginToken = data.data;

    console.log('res =============== ||| ======', loginToken)

    // ================================================================== api_login
    if (!error) {
      const pass = await loginByToken(loginToken);

      //校验通过
      if (pass) {
        await routeStore.initAuthRoute();

        if (redirect) {
          await redirectFromLogin();
        };

        if (routeStore.isInitAuthRoute) {
          window.$notification?.success({
            title: $t('page.login.common.loginSuccess'),
            content: $t('page.login.common.welcomeBack', { userName: userInfo.userName }),
            duration: 4500
          });
        };
      }


    } else {
      // 返回登录界面
      resetStore();
    }

    endLoading();
  }

  async function loginByToken(loginToken: Api.Auth.LoginToken) {
    // 1. stored in the localStorage, the later requests need it in headers
    localStg.set('token', loginToken.token);
    localStg.set('refreshToken', loginToken.refreshToken);

    // 2. get user info
    // const pass = await getUserInfo();

    // if (pass) {
    //   token.value = loginToken.token;
    //   return true;
    // }

    return false;
  }

  async function getUserInfo() {
    const { data: info, error } = await fetchGetUserInfo();

    if (!error) {
      // update store
      Object.assign(userInfo, info);

      return true;
    }

    return false;
  }

  async function initUserInfo() {
    const hasToken = getToken();

    // if (hasToken) {
    //   // const pass = await getUserInfo();

    //   if (!pass) {
    //     resetStore();
    //   }
    // }
  }

  return {
    token,
    userInfo,
    isStaticSuper,
    isLogin,
    loginLoading,
    resetStore,
    login,
    routes,
    initUserInfo
  };
});
