import { useStationStore } from './station';
import { usePollingStore } from './polling';
import { userClient, type LoginParams, type LoginResult, type Station } from '@/apis';
import { NDM_USER_STORE_ID } from '@/constants';
import type { Result } from '@/types';
import { AesEncryption, getAppEnvConfig } from '@/utils';
import axios, { AxiosError } from 'axios';
import dayjs from 'dayjs';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';

const getHeaders = () => {
  const { lampAuthorization, lampClientId, lampClientSecret } = getAppEnvConfig();
  const newAuthorization = window.btoa(`${lampClientId}:${lampClientSecret}`);
  const authorization = lampAuthorization.trim() !== '' ? lampAuthorization : newAuthorization;
  return {
    'content-type': 'application/json',
    'accept-language': 'zh-CN,zh;q=0.9',
    accept: 'application/json, text/plain, */*',
    ApplicationId: '1',
    TenantId: '1',
    Authorization: authorization,
  };
};

const aesEncryption = new AesEncryption();

export const useUserStore = defineStore(
  NDM_USER_STORE_ID,
  () => {
    const userLoginResult = ref<LoginResult | null>(null);
    const userInfo = ref<any>(null);
    const lampLoginResultRecord = ref<Record<string, LoginResult> | null>(null);

    const isLamp = computed(() => userInfo.value?.['id'] === '2');

    const resetStore = () => {
      userLoginResult.value = null;
      userInfo.value = null;
      lampLoginResultRecord.value = null;
    };

    const userLogin = async (loginParams: LoginParams) => {
      const { username, password, code, key, grantType } = loginParams;
      const body = {
        username: aesEncryption.encryptByAES(username),
        password: aesEncryption.encryptByAES(password),
        code,
        key,
        grantType,
      };
      // 如果发生 http 错误，会被登录页中的 useMutation 捕获，此处无需 try-catch
      const { data: result } = await axios.post<Result<LoginResult>>(`/api/oauth/anyTenant/login`, body, { headers: getHeaders() });
      // 尽管请求成功，但需要判断是否发生业务错误
      // 如果发生业务错误，则需要显式抛出，登录页会捕获该错误并提示用户
      if (!result.isSuccess) throw new Error(result.msg);
      userLoginResult.value = result.data;
    };

    const userLogout = async () => {
      const [err] = await userClient.post(`/api/oauth/anyUser/logout`, { token: userLoginResult.value?.token });
      if (err) throw err;
      resetStore();
    };

    const userGetInfo = async (options?: { signal?: AbortSignal }) => {
      const { signal } = options ?? {};
      const [err, info] = await userClient.get<any>(`/api/oauth/anyone/getUserInfoById`, { signal });
      if (err || !info) {
        throw err;
      }
      userInfo.value = info;
    };

    const lampLogin = async (stationCode: Station['code']) => {
      const { data: accountRecord } = await axios.get<Record<string, { username: string; password: string }>>(`/minio/ndm/ndm-accounts.json?_t=${dayjs().unix()}`);
      const body = {
        username: aesEncryption.encryptByAES(accountRecord[stationCode]?.username ?? ''),
        password: aesEncryption.encryptByAES(accountRecord[stationCode]?.password ?? ''),
        grantType: 'PASSWORD',
      };
      const { data: respData } = await axios.post<Result<LoginResult>>(`/${stationCode}/api/oauth/anyTenant/login`, body, { headers: getHeaders() });
      // 如果登录返回失败，需要提示用户检查用户名和密码配置，并全局停止轮询
      if (!respData.isSuccess) {
        console.error(respData);
        const stationStore = useStationStore();
        const stationName = stationStore.stations.find((station) => station.code === stationCode)?.name ?? '';
        window.$dialog.destroyAll();
        window.$dialog.error({
          closable: false,
          maskClosable: false,
          draggable: true,
          title: `${stationName}登录失败`,
          content: `请检查该车站的用户名和密码配置，并在确认无误后刷新页面！`,
          positiveText: '刷新',
          onPositiveClick: () => {
            window.$dialog.destroyAll();
            window.location.reload();
          },
        });
        // 登录失败时，需要全局停止轮询
        const pollingStore = usePollingStore();
        pollingStore.stopPolling();
        throw new AxiosError(respData.msg, `${respData.code}`);
      } else {
        if (lampLoginResultRecord.value === null) {
          lampLoginResultRecord.value = {};
        }
        lampLoginResultRecord.value[stationCode] = respData.data;
      }
    };

    return {
      userLoginResult,
      userInfo,
      lampLoginResultRecord,

      isLamp,

      resetStore,
      userLogin,
      userLogout,
      userGetInfo,
      lampLogin,
    };
  },
  {
    persist: true,
  },
);
