import axios from 'axios'
import type { AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import { user } from '~/store/user'

const token = user.token

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

const instance = axios.create({
  baseURL: 'https://ycxcktapi.bozedu.net',
  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: 'qqyxt',
          issubmit: (config.url?.endsWith('add') || config.url?.endsWith('edit')) ? '1' : undefined,
        },
        config.data)
    }
    return config
  },
  (error) => {
    console.error('request error: ', error)
    return Promise.reject(error)
  },
)

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

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

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

function 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 },
  }),
}
