import axios from 'axios'
import type { AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import { user } from '~/store/index'
const token = user.value?.token

export interface Response {
  code: string
  data: any
  msg: string
}

const instance = axios.create({
  baseURL: window.GLOBAL_CONFIG.api,
  timeout: 180 * 1000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  method: 'post',
})

instance.interceptors.request.use(
  async (config) => {
    if (config.method?.toLocaleLowerCase() === 'get') {
      config.params = Object.assign({ token }, config.params)
    }
    else {
      config.data = Object.assign(
        {
          token,
          client: 'web',
          api: 'json',
          site: 'txwx',
          issubmit: (config.url?.endsWith('add') || config.url?.endsWith('edit')) ? '1' : undefined,
        },
        config.data)
      if (config.data.M5jxrcL == undefined) {
        const href = location.href
        if (href.includes('manage')) {
          config.data.M5jxrcL = '76D5tE'
        } else if (href.includes('jsd') || href.includes('xsd')) {
          config.data.M5jxrcL = 'DaKFNRE'
        } else {
          config.data.M5jxrcL = ''
        }
      }
    }
    return config
  },
  (error) => {
    console.error('request error: ', error)
    return Promise.reject(error)
  },
)

// response interceptor
instance.interceptors.response.use(
  (response: { data: Response }) => {
    response.data.code = response.data?.code?.toString()
    response.data.msg = response.data.msg.replaceAll(/<.*?>/g, ' ')
    const { code, msg } = response.data
    if (code !== '1')
      ElMessage.error(msg)

    return response.data
  },
  (error) => {
    console.error(`response error: ${error}`)
    return Promise.reject(error)
  },
)

export default (config: AxiosRequestConfig): Promise<Response> => instance.request(config)

const obj2form = (data: { [key: string]: any }) => {
  const formData = new FormData()
  Object.keys(data).forEach(key => formData.append(key, data[key]))
  return formData
}

export const REQUEST = {
  empty: axios,
  default: instance,
  import: (c: Partial<AxiosRequestConfig>) => instance({
    timeout: 10 * 60 * 1000,
    transformRequest: [obj2form],
    ...c,
  }),
  upload: (c: Partial<AxiosRequestConfig>) => instance({
    timeout: 3 * 60 * 1000,
    transformRequest: [obj2form],
    ...c,
  }),
  download: (c: Partial<AxiosRequestConfig>) => instance({
    timeout: 1 * 60 * 1000,
    method: 'get',
    params: { token, limit: 10000, page: 1, api: 'xls', ...c },
  }),
}

export function download(url: string, data?: object | null) {
  let M5jxrcL = '';
  const str = location.href
  if (str.includes('manage')) {
    M5jxrcL = '76D5tE'
  } else if (str.includes('jsd') || str.includes('xsd')) {
    M5jxrcL = 'DaKFNRE'
  } else {
    M5jxrcL = ''
  }
  const params = Object.assign({ token, limit: 10000, page: 1, api: 'xls', M5jxrcL }, data)
  const paramsStr = Object.entries(params).map(([k, v]) => `${k}=${v}`).join('&')
  const el = document.createElement('a')
  const href = `${window.GLOBAL_CONFIG.api}${url}?${paramsStr}`
  el.setAttribute('href', href)
  el.click()
}
