import axios from 'axios'
import { ElMessage } from 'element-plus'

const GLOBAL_CONFIG: any = {
  web_pc: 'https://jltweb.bozedu.net',
  api: 'https://uc.bozedu.net/',
  openapi: 'https://openapi.bozedu.net',
  uc: 'https://uc.bozedu.net/',
  qqyxt: 'https://qqyxt.bozedu.net',
}
import { user } from "~/store/user"

const token = user.value?.token || ''

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

instance.interceptors.request.use(
  async (config: any) => {
    // console.log('config : ', config)
    config.api = config.api || 'openapi'
    config.baseURL = GLOBAL_CONFIG[config.api]
    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: 'qqyxt',
          apptag: 'zhkt',
          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)
  },
)
instance.interceptors.response.use(
  (response) => {

    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') {
      ElMessage.error(msg)
      return Promise.reject(response.data)
    }
    return response.data
  },
  (error) => {
    console.error(`response error: ${error}`)
    return Promise.reject(error)
  },
)

export default (config: any) => instance.request(config) as Promise<any>
