import { createAlova } from 'alova';
import adapterFetch    from 'alova/fetch';
import VueHook         from 'alova/vue';
import adapterMock     from '@/request/mock';

import { getPinia, useAccountStore, usePlatformStore } from '@/stores';
import router from '@/router';

export default createAlova({
  baseURL: import.meta.env.SIX_REQUEST_BASE ?? '/',
  statesHook: VueHook,
  requestAdapter: import.meta.env.DEV ? adapterMock() : adapterFetch(),
  async beforeRequest(method) {
    const pinia = getPinia();
    method.config.headers.warrant ??= usePlatformStore(pinia).serialNumber;
    if ( !method.config.meta?.ignoreToken ) method.config.headers.Authorization ??= useAccountStore(pinia).token;
  },
  responded: {
    async onSuccess(response, method) {
      try {
        if ( response.status >= 400 ) throw new Error(`${ response.statusText }(${ response.status })`);

        let result = await response.json();
        if (method.url.startsWith(`${location.origin}${import.meta.env.BASE_URL}database`)) result = { code: 0, data: result };
        /* 接口修正 code */
        if ( result.ResultCode != null && result.code == null ) result.code = result.ResultCode;
        if ( result.Data && result.data == null ) result.data = result.Data;
        if ( result.ResultInfo && result.msg == null ) result.msg = result.ResultInfo;
        if ( result.success === true || result.code === 200 ) result.code = 0;
        const { success = false, code = success ? 0 : -1, data, msg: message = '未知错误', ...props } = result;
        if ( code === 0 ) { return data; }
        else if (code === 401) {
          useAccountStore(getPinia()).$reset();
          await router.replace({ name: 'login', replace: true });
        }
        throw { ...props, message: `${ message }` };
      } catch ( e: any ) {
        if ( !method.meta?.ignoreException ) {
          const { Notify } = await import('@/platform/notify.ui');
          Notify.error(e?.message);
        }
        throw e;
      }
    },
    async onError(error, method) {
      if ( !method.meta?.ignoreException && error.name !== 'AbortError' ) {
        const { Notify } = await import('@/platform/notify.ui');
        Notify.error(`${ error.message }`);
      }
    },
    onComplete() {},
  },
});
