import axios, { Axios } from 'axios'
// import { AxiosRequestConfig } from 'axios';
import type { AxiosPromise, AxiosRequestConfig, AxiosInstance } from 'axios'
import { ElMessage } from 'element-plus'
import { user } from '~/store/user'
declare module 'axios' {
  interface IAxios {
    code: string
    msg: string
  }
  export interface AxiosResponse<T = any> extends IAxios { }
}


export const token = user.token
// 'cbd0vATxKw_aDfTiYv7jhvp1knerG8bjL5F5j0uhTyB8okTNxBHhgzvHDbqZ3wbP0n3HLlpfDxEi9tnaqNpN9rCxeOn6gr58'
// "77f0qj6wBe_aT4tk0IsY1K6LhTe2wx_b0bo7BEKOMa5UTYf61dY_arnEKJUFUEM1BpdWY5043KnfSyAm8RcwIoojL_a_aekwKUwk"
// "1979XbLIvdcVcIS_blnpvHLUr_apC25hP7kOa_amRUKKJX4uJeobRX9y_b9BkbRD5DHvx_aSL3_bTGZx94L6kqROfb_bax73q4Z_afyxgjI"

type MyAxiosRequestConfig = AxiosRequestConfig & {
  $type?: string
}

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

Request.interceptors.request.use(
  async (config: MyAxiosRequestConfig) => {
    if (config.method?.toLocaleLowerCase() === 'get') {
      config.params = Object.assign(
        {
          token,
        },
        config.params || {}
      )
    } else {
      if (config.data instanceof FormData) {
        //
      } else {
        config.data = Object.assign(
          {
            token,
            client: 'web',
            api: 'json',
            admin:'1',
            issubmit: (config.url?.endsWith('/add') || config.url?.endsWith('/edit')) ? '1' : undefined,
          },
          config.data ?? {}
        )
      }
    }

    if (config.$type === 'import') {
      config.timeout = 1000 * 60 * 20
      config.transformRequest = [function (data, headers) {
        const formData = new FormData()
        Object.keys(data).forEach(key => formData.append(key, data[key]))
        return formData;
      }]
    }
    if (config.$type === 'upload') {
      config.timeout = 1000 * 60 * 2
      config.transformRequest = [function (data, headers) {
        const formData = new FormData()
        Object.keys(data).forEach(key => formData.append(key, data[key]))
        return formData;
      }]
    }
    return config
  },
  (error) => {
    // do something with request error
    console.error('request error: ', error) // for debug
    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') {
      ElMessage.error(msg)
    }
    return response.data
  },
  (error) => {
    console.error('response error: ' + error) // for debug
    return Promise.reject(error)
  }
)

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.GLOBAL_CONFIG.api}${url}?${paramsStr}`
  el.setAttribute('href', href)
  el.click()
}

export default Request

