import router           from '@/router';
import { createAlova }  from 'alova';
import fetchAdapter     from 'alova/fetch';
import VueHook          from 'alova/vue';
import { notification } from 'ant-design-vue';
import mockAdapter      from './mock';
import { getToken }     from './tools';

let key = '';
const request = createAlova({
  baseURL: '/manager/',
  statesHook: VueHook,
  requestAdapter: import.meta.env.DEV ? mockAdapter() : fetchAdapter(),
  async beforeRequest(method) {
    if ( !method.config.meta?.ignoreToken ) method.config.headers.Authorization ??= getToken();
  },
  responded: {
    async onSuccess(response, method) {
      let ignoreException = false;
      try {
        if ( response.status >= 400 ) throw new Error(`${ response.statusText }(${ response.status })`);

        const result = await response.json();
        /* 接口修正 code */
        if ( result.success !== false && result.code === 200 ) result.code = 0;
        const {
          error = false, warn = false, code = error || warn ? -1 : 0,
          msg: message = '未知错误',
          data, total, rows, ..._data
        } = result;
        if ( code === 0 ) {
          return method.meta?.unconvert
                 ? { ..._data, data }
                 : total != null && Array.isArray(rows)
                   ? { total, data: rows }
                   : data;
        } else if ( code === 401 ) {
          key = code;
          await router.replace('/login');
        } else if ( warn ) {
          ignoreException = true;
          notification.warning({
            message: method.url,
            description: `${ message }(${ code })`,
            key: method.url,
          });
        }
        throw new Error(`${ message }(${ code })`);
      } catch ( e: any ) {
        if ( !ignoreException && !method.meta?.ignoreException ) {
          notification.error({
            message: key ? '请重新登录' : method.url,
            description: e?.message,
            key: key || method.url,
          });
        }
        throw e;
      }
    },
  },
});
export default request;
