import type { AxiosRequestConfig } from 'axios'
import axios from 'axios'
import { showFailToast } from 'vant'
import { user } from '~/store/user'
// import router from '../router/index'

const token = user.value?.token
export interface Response {
  code: string
  data: any
  msg: string
  status: any
  statusText: any
  headers: any
  config: any
}

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

instance.interceptors.request.use(
  async (config) => {
    // config.params = Object.assign({ token }, config.params)
    if (config.method?.toLocaleLowerCase() === 'get' || config?.data?.file) {
      config.params = Object.assign({ token }, config.params)
    }
    else {
      config.data = Object.assign(
        {
          token: user.value?.token,
          client: 'web',
          api: 'json',
          site: 'aimk',
          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: { data: Response }) => {
    if (response.config.url == "/openapi/wx/wx.php" && response.data.code == '401') {
      return response.data
    }
    if (response.data.code === '10000') {
      showFailToast('登录信息已过期，请重新登录')
      return
    }
    if (response.data.code === undefined)
      return response.data

    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 Promise.reject(response.data)
    }
    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 },
  }),
}

export function download(url: string, data?: object | null) {
  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 as any).GLOBAL_CONFIG.api}${url}?${paramsStr}`
  el.setAttribute('href', href)
  el.click()
}
