import axios from 'axios'
const token = ''

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

_request.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', issubmit: '1', }, config.data)
    }
    return config
  },
  (error) => {
    console.error('request error: ', error)
    return Promise.reject(error)
  }
)

// response interceptor
_request.interceptors.response.use(
  (response) => {
    response.data.code = response.data?.code?.toString()
    response.data.msg = response.data.msg.replaceAll(/<.*?>/g, ' ')
    const { code, msg } = response.data
    if (code !== '1') {
      showFailToast(msg)
    }
    return response.data
  },
  (error) => {
    console.error('response error: ' + error)
    return Promise.reject(error)
  }
)

export default _request

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

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

export function download(url, data) {
  const params = Object.assign({ token, limit: 10000, page: 1, api: 'xls' }, 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()
}
