// import { message } from 'ant-design-vue';
import { defineStore } from 'pinia';
// import { router } from '/nerv-lib/paas/router';
import { http } from '/nerv-lib/util/http';
import Cookies from 'js-cookie';
import { appConfigStore } from '/nerv-base/store/modules/app-config';
import { isArray } from 'lodash-es';
export const loginService = defineStore({
  id: 'loginService',
  /**
   * module   测试用
   * @returns
   */
  state(): { currentUser: string; currentUserTenant: string; userName: string; isAdmin: boolean } {
    return { currentUser: '', currentUserTenant: '', userName: '', isAdmin: false };
  },
  getters: {},
  actions: {
    isLogin(): boolean {
      const authToken = appConfigStore()?.headers?.extraAuth;
      if (authToken && authToken.includes('nervsid')) {
        const tokenArr = authToken.split('=');
        return !!(isArray(tokenArr) && tokenArr.length > 0 && tokenArr[1]);
      }
      return !!Cookies.get('nervsid');
    },

    /**
     * Get userInfo from nginx
     */
    asyncFetchUserInfo(): Promise<any> {
      return http
        .get('/api/webui/webui/objs/PassportUserInfo')
        .then((body) => {
          const { name, tenant, tenantAlias, isAdmin } = body;
          this.currentUser = name;
          this.currentUserTenant = tenant;
          this.isAdmin = isAdmin;
          http.setHeaders({
            'NERV-TENANT': tenant,
          });
          if (tenantAlias) {
            this.userName = `${name}@${tenantAlias}`;
          } else {
            if (tenant && tenant !== 'nerv') {
              this.userName = `${name}@${tenant}`;
            } else {
              this.userName = name;
            }
          }
          return body;
        })
        .catch((err) => {
          console.log(err);
        });
    },

    /**
     * Get logoutUrl from nginx, then redirect to passport
     *
     * @returns {Promise<string>}
     */
    logout(): Promise<any> {
      if (appConfigStore().layout) {
        return appConfigStore().layout();
      } else {
        return http.get('/api/webui/webui/objs/PassportLogout').then((body) => {
          Cookies.remove('nervsid');
          window.location.href = body.url;
          const user = this.currentUser;
          this.currentUser = '';
          return user;
        });
      }
    },

    async checkUserInfo() {
      if (this.currentUser === '') {
        await this.asyncFetchUserInfo();
      }
    },
  },
});
