import type { Recordable, UserInfo } from '@vben/types';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { LOGIN_PATH } from '@vben/constants';
import { preferences } from '@vben/preferences';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';
import { useStorage } from '@vben/utils';

import { ElNotification } from 'element-plus';
import { defineStore } from 'pinia';

import {
  // getAccessCodesApi,
  getLoginCaptchaApi,
  loginApi,
  logoutApi,
} from '#/api';
import { $t } from '#/locales';

export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();

  const loginLoading = ref(false);

  const userStorage = useStorage('user');

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   */

  async function getLoginCaptcha(data: { uuid: string }) {
    const res = await getLoginCaptchaApi(data);
    return res as unknown as ArrayBuffer;
  }

  async function authLogin(
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    // 异步处理用户登录操作并获取 accessToken
    let userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;
      const storage = useStorage('captcha-uuid');
      const res = await loginApi({
        account: params.username,
        pwd: params.password,
        code: params.captcha,
        uuid: storage.getItem() as string,
      });

      // "bmid": 76,
      // "bm": null,
      // "token": "a2fd3e10a990c2f7a34de2c7160139a4",
      // "gw": "销售装维",
      // "workerid": "1",
      // "accountid": "1",
      // "timeout": 7200,
      // "nickname": "超级管理员",
      // "account": "admin",
      // "popedom": "1401,1413,1412,1411,1410,1409,1406,1404,1402,1392,1399,1398,1397,1396,1395,1394,1393,1390,1389,1383,1376,1405,1403,1391,1387,1386,1385,1384,1381,1380,1379,1378,1377,333,346,331,280,289,330,287,286,285,284,1426,1414,367,366,329,328,311,299,298,282,278,345,335,334,332,313,312,310,309,307,305,304,303,302,301,279,277,276,275,274,273,269,288,283,272,271,270,306,255,234,232,354,353,352,351,350,349,348,297,293,268,267,266,265,264,263,261,260,259,258,257,256,362,361,64,63,62,19,308,300,181,178,167,125,123,101,92,91,87,86,85,84,83,82,81,80,54,23,22,21,20,2,290,296,295,294,292,291,147,146,145,144,143,142,141,60,59,58,57,55,229,228,93,18,7,1400,171,170,169,168,5,14,4,156,132,131,16,15,3,130,129,128,127,17,281,233,230,61,1,6",
      // "grouplist": "1"

      const { token: accessToken } = res;
      userStorage.setItem(res);

      // 如果成功获取到 accessToken
      if (accessToken) {
        // 将 accessToken 存储到 accessStore 中
        accessStore.setAccessToken(accessToken);

        // 获取用户信息并存储到 accessStore 中
        const fetchUserInfoResult = (await fetchUserInfo()) as UserInfo;
        const accessCodes = fetchUserInfoResult.popedom.split(',') || [];
        // const [fetchUserInfoResult, accessCodes] = await Promise.all([
        //   fetchUserInfo(),
        //   getAccessCodesApi(),
        // ]);

        userInfo = fetchUserInfoResult as UserInfo;

        userStore.setUserInfo(userInfo);
        accessStore.setAccessCodes(accessCodes);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          onSuccess
            ? await onSuccess?.()
            : await router.push(
                userInfo.homePath || preferences.app.defaultHomePath,
              );
        }

        if (userInfo?.realName) {
          ElNotification({
            message: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
            title: $t('authentication.loginSuccess'),
            type: 'success',
          });
        }
      }
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  async function logout(redirect: boolean = true) {
    try {
      await logoutApi();
    } catch {
      // 不做任何处理
    }
    resetAllStores();
    accessStore.setLoginExpired(false);

    // 回登录页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: redirect
        ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
        : {},
    });
  }

  async function fetchUserInfo() {
    const userInfoData = userStorage.getItem() as UserInfo;
    // let userInfo: null | UserInfo = null;
    // userInfo = await getUserInfoApi();
    userStore.setUserInfo(userInfoData);
    return userInfoData;
  }

  function $reset() {
    loginLoading.value = false;
  }

  return {
    $reset,
    authLogin,
    fetchUserInfo,
    loginLoading,
    logout,
    getLoginCaptcha,
  };
});
