import adapterMock                                  from '@/request/mock';
import pinia, { useAccountStore, usePlatformStore } from '@/stores';

import { createAlova } from 'alova';
import adapterFetch    from 'alova/fetch';
import VueHook         from 'alova/vue';


export default createAlova({
  baseURL: import.meta.env.SIX_REQUEST_BASE ?? '/',
  statesHook: VueHook,
  requestAdapter: import.meta.env.DEV ? adapterMock() : adapterFetch(),
  async beforeRequest(method) {
    const store = usePlatformStore(pinia);
    method.config.headers.warrant ??= store.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 })`);

        const result = await response.json();
        /* 接口修正 code */
        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 {}
        throw { ...props, message: `${ message }(${ code })` };
      } 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 }(${ error?.code })`);
      }
    },
    onComplete() {},
  },
});
