import { http } from '@/settings/http'
import { useUserStore } from '@/stores/user'
import axios, { InternalAxiosRequestConfig, type AxiosError, type AxiosResponse } from 'axios'
import type { App } from 'vue'
import { notification } from 'ant-design-vue'

export interface GlobalError {
	/** 错误码 */
	code: number
	/** 错误信息 */
	message: string
}

// 获取 HTTP 请求头
export const getHTTPHeaders = (): Record<string, string> => {
	const newHeaders: Record<string, string> = {}
	const token = useUserStore().token
	if (token) {
		newHeaders.Authorization = token
	}
	return newHeaders
}
export function defaultSuccess(data: unknown): void {
	console.log(data)
}
export function defaultError(error: { code: string; error?: string }): void {
	window.console.log(error)
	notification.error({
		message: '操作异常: ',
		placement: 'top',
		description: error.error + '(' + error.code + ')',
		duration: 6,
	})
}
const config = {
	baseURL: http.prefix,
	timeout: http.timeout,
}
const _axios = axios.create(config)
_axios.interceptors.request.use(
	(cfg: InternalAxiosRequestConfig) => {
		cfg.headers = Object.assign(cfg.headers || {}, getHTTPHeaders())
		return cfg
	},
	(err: unknown) => {
		console.warn(err)
		return Promise.reject(new Error('客户端配置错误!'))
	},
)

_axios.interceptors.response.use(
	(response: AxiosResponse) => {
		// 数据成功
		return Promise.resolve(response)
	},
	(error: AxiosError<GlobalError>) => {
		switch (Number(error.response?.status)) {
			case 403 | 401:
				return Promise.reject({ code: Number(error.response?.status) })
			case 404: {
				return Promise.reject({ code: '404' })
			}
			case 500:
			default:
				return Promise.reject({ code: '500', error: error.response?.data.message })
		}
	},
)
export { _axios as http }

export default {
	install: (app: App) => {
		app.config.globalProperties.$http = _axios
	},
}
