import axios, { AxiosRequestConfig } from 'axios';
import qs from 'querystring';
import { ElMessage } from 'element-plus';
import useMainStore from '@/store/useMainStore';
import { BaseLoginUrl, DA_HUA_URL_PREFIX } from '@/constants/constants';
import { useDaHuaStore } from '@/store';

// const ENV = import.meta.env;
//     console.log('ENV', ENV.VITE_MAP_SERVER);//获取环境变量

// const baseURL =
//   process.env.NODE_ENV === 'production'
//     ? 'http://sqpcbg.xt.wenhq.top:8083/api'
//     : '/api';

const baseURL =
  (process.env.NODE_ENV === 'prod' || process.env.NODE_ENV === 'test')
    ? (import.meta.env.VITE_API_SERVER as string) + '/YJZH-SQ/api'
    : '/api';

const CancelToken = axios.CancelToken;
const source = CancelToken.source();
let timer: NodeJS.Timeout;

axios.interceptors.request.use((config) => {
  const main = useMainStore();
  config.cancelToken = new axios.CancelToken((cancel) => {
    main.pushReqToken(cancel);
  });
  return config;
});

axios.interceptors.response.use(
  (res) => {
    if (res.status >= 200 && res.status < 300) {
      if (res.data?.code === 200) {
        return res.data;
      }
      if (res.data?.code === 401) {
        ElMessage.error({
          // message: `401. 没有权限访问该接口: ${res.config.url}`,
          message: `401. 没有权限访问该接口`,
        });
        const main = useMainStore();
        main.clearReqToken();
        window.localStorage.setItem('Authorization', '');
        window.location.href = BaseLoginUrl;

        throw Error(res.statusText);
      }
      if (res.data?.code === 404) {
        ElMessage.error({ message: '404. 未找到该接口!' });
        throw Error(res.statusText);
      }
      if (res.data?.code >= 500) {
        ElMessage.error({ message: res.data?.msg ?? '系统异常, 请稍后重试!' });
        throw Error(res.statusText);
      }
    }
    if (res.status === 401) {
      ElMessage.error({
        message: `401. 没有权限访问该接口: ${res.config.url}`,
      });
      throw Error(res.statusText);
    }
    if (res.status === 404) {
      ElMessage.error({ message: '404. 未找到该接口!' });
      throw Error(res.statusText);
    }

    if (res.status >= 500) {
      ElMessage.error({ message: '系统异常, 请稍后重试!' });
      throw Error(res.statusText);
    }

    return res.data;
  },
  (error) => {
    // ElMessage.error({ message: '系统异常, 请稍后重试!' });
    const {
      status,
      config: { url },
    } = error.response;
    if (status === 401 && url?.includes(DA_HUA_URL_PREFIX)) {
      clearTimeout(timer);
      const dahuaStore = useDaHuaStore();
      dahuaStore.timer && clearInterval(dahuaStore.timer);

      timer = setTimeout(() => {
        dahuaStore.DAHUALogin();
      }, 1000);
    }
    throw Error(error);
  },
);

export default function request<T>(
  method: AxiosRequestConfig['method'] = 'GET',
  confifg: AxiosRequestConfig & {},
): Promise<T> {
  return axios.request({
    method,
    baseURL,
    ...confifg,
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      AppId: '3bcb760743ea456faba29a1dfb247bf4',
      Authorization:
        'Bearer ' + window.localStorage.getItem('Authorization') ?? '',
      ...confifg.headers,
    },
  });
}



