import axios from 'axios';
import { ElMessage } from 'element-plus';
import { getUserData } from '@/utils/user';

const env = import.meta.env;
const w: any = window;
const $wujie: any = w.$wujie;

const service = axios.create({
  baseURL: env.VITE_API_BASE_URL,
  timeout: 60000,
  headers: {
    'Content-Type': 'application/json;application/xml;charset=utf-8;',
  },
});

const company = 'carsafe';
let userId = $wujie?.props?.USER_ID || localStorage.getItem('USER_ID') || '';
let token = $wujie?.props?.TOKEN || localStorage.getItem('TOKEN') || '';
let tenantId = $wujie?.props?.TENANT_ID || localStorage.getItem('TENANT_ID') || '';

service.interceptors.request.use(
  (config) => {
    const configData = config.data || config.params || {};
    if (configData.token) {
      userId = configData.userId;
      token = configData.token;
      tenantId = configData.tenantId;
    }
    config.headers['company'] = company;
    config.headers['jobNumber'] = getUserData().username || '';
    config.headers['token'] = token;
    config.headers['userId'] = userId;
    config.headers['tenantId'] = tenantId;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (res) => {
    // 判断响应类型，如果是 blob，返回完整响应对象
    if (res.config.responseType === 'blob') {
      return res;
    }
    // 普通接口返回原来的 res.data
    if (res.data.code !== 200) {
      ElMessage.warning(res.data.message);
    }
    return res.data;
  },
  (error) => {
    ElMessage.warning('系统繁忙，请稍后再试');
    return Promise.reject(error);
  }
);

const get = (url: string, params = {}) => {
  return service.get(url, { params });
};

const post = (url: string, data = {}) => {
  return service.post(url, data);
};

const upload = (url: string, formData = {}, onProgress?: any) => {
  return service.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    onUploadProgress: (event: any) => {
      if (onProgress) {
        onProgress({
          loaded: event.loaded,
          total: event.total,
        });
      }
    },
  });
};

const download = (url: string, params = {}, filename = 'download') => {
  return service
    .post(url, params, {
      responseType: 'blob',
    })
    .then(async (res: any) => {
      if (res.data.type === 'application/json') {
        const text = await res.data.text();
        const result = JSON.parse(text);
        if (result.code !== 200) {
          ElMessage.warning(result.message);
          return;
        }
      }

      const contentDisposition =
        res.headers?.['content-disposition'] || res.headers?.['Content-Disposition'] || '';
      let fileName = filename;

      if (contentDisposition) {
        const parts = contentDisposition
          .split(';')
          .map((p: string) => p.trim())
          .filter(Boolean);
        const paramsMap: Record<string, string> = {};
        parts.forEach((part: string) => {
          const idx = part.indexOf('=');
          if (idx === -1) return;
          const key = part.slice(0, idx).trim().toLowerCase();
          let val = part.slice(idx + 1).trim();
          if (val.startsWith('"') && val.endsWith('"')) {
            val = val.slice(1, -1);
          }
          paramsMap[key] = val;
        });

        if (paramsMap['filename*']) {
          const val = paramsMap['filename*'];
          const rfcMatch = val.match(/^([^']*)''(.*)$/);
          if (rfcMatch) {
            const encoded = rfcMatch[2];
            try {
              fileName = decodeURIComponent(encoded);
            } catch {
              fileName = encoded;
            }
          } else {
            if (/^utf-?8$/i.test(val) && paramsMap['filename']) {
              const candidate = paramsMap['filename'];
              try {
                fileName = candidate.includes('%') ? decodeURIComponent(candidate) : candidate;
              } catch {
                fileName = candidate;
              }
            } else {
              try {
                fileName = val.includes('%') ? decodeURIComponent(val) : val;
              } catch {
                fileName = val;
              }
            }
          }
        } else if (paramsMap['filename']) {
          const candidate = paramsMap['filename'];
          try {
            fileName = candidate.includes('%') ? decodeURIComponent(candidate) : candidate;
          } catch {
            fileName = candidate;
          }
        }
      }

      const blob = new Blob([res.data]);
      const link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(link.href);
    })
    .catch(() => {
      ElMessage.warning('下载失败');
    });
};

export { get, post, upload, download };
