import { Data } from './../../node_modules/_vite@2.9.15@vite/dist/node/index.d';
import Axios, { AxiosResponse, AxiosRequestConfig, AxiosError } from 'axios'

import message from '../utils/message'
import { i18n } from '../boot/i18n'
import router from '../router'
// import { message } from 'ant-design-vue'
// import Store from '../store'
// import { Notify } from 'quasar'
import * as OpenCC from 'opencc-js'
import { ApiResult } from 'src/@types/enumHelper';
import { dispatchAction } from 'src/store/utils';
import { UserActionsType } from 'src/store/modules/user/actions';
let {locale,t} =i18n.global
let converterTW = OpenCC.Converter({ from: 'cn', to: 'tw' }) //转繁
let datas: AxiosResponse  // 接收需要转繁数据


/**
 * get status code
 * @param {AxiosResponse} response Axios  response object
 */
const getErrorCode2text = (response: AxiosResponse): string => {
	/** http status code */
	const code = response.status
	/** notice text */
	let message = 'Request Error'
	switch (code) {
		case 400:
			message = 'Request Error'
			break
		case 401:
			message = 'Unauthorized, please login'
			break
		case 403:
			message = '拒绝访问'
			break
		case 404:
			message = '访问资源不存在'
			break
		case 408:
			message = '请求超时'
			break
		case 500:
			message = '位置错误'
			break
		case 501:
			message = '承载服务未实现'
			break
		case 502:
			message = '网关错误'
			break
		case 503:
			message = '服务暂不可用'
			break
		case 504:
			message = '网关超时'
			break
		case 505:
			message = '暂不支持的 HTTP 版本'
			break
		default:
			message = '位置错误'
	}
	return message
}

/**
 * @returns  {AxiosResponse} result
 * @tutorial see more:https://github.com/onlyling/some-demo/tree/master/typescript-width-axios
 * @example
 * service.get<{data: string; code: number}>('/test').then(({data}) => { console.log(data.code) })
 */
const service = Axios.create({
	baseURL: process.env.BASE_APP_API,
	timeout: 20000,
	headers: {
		'User-Type': 'bus',
		'Content-Type': 'application/json;charset=UTF-8'
	}
})



/**
 * @description 请求发起前的拦截器
 * @returns {AxiosRequestConfig} config
 */
service.interceptors.request.use(
	async (config: AxiosRequestConfig) => {

		// 如果是获取token接口：
		// if (config.url === '/auth/oauth/token') {
		// 	//TODO:用户登录的特殊处理，
		// } else {
		// 	// 如果保存有token，则取，否则不添加Authorization
		// 	if (Store.state && Store.state.user?.token) {
		// 		//TODO:Access_TOKEN 的获取，需要根据实际业务情况进行调整
		// 		const token = Store.state.user?.token
		// 		const tokenType = token.token_type
		// 		const accessToken = token.access_token
		// 		config.headers.Authorization = `${tokenType} ${accessToken}`
		// 	}

		// 	//TODO:包装一层MSG，但是微服务应该去掉此步骤
		// 	config.data = {
		// 		Msg: config.data
		// 	}
		// }

		return config
	},
	error => {
		//TODO:  新增网络请求异常处理业务
		return Promise.reject(error)
	}
)

/**
 * @description 响应收到后的拦截器
 * @returns {}
 */
service.interceptors.response.use(

	/** 请求有响应 */
	async (response: AxiosResponse) => {
		if (response.status === 200) {
      if(response.data.resultCode == ApiResult.TOKEN_ILLEGAL || response.data.resultCode == ApiResult.TOKEN_INVALID){
        //router.push('/auth/login')
        dispatchAction<UserActionsType>('user', 'setUserSignout', null)
        window.location.reload()
      }
			if(locale.value=='zhTW'){
				let stringifyData = converterTW(JSON.stringify(response))
				datas = JSON.parse(stringifyData)
			}else{
				datas = response
			}
			return Promise.resolve(datas)
		} else {
			const __text = getErrorCode2text(response)
			return Promise.reject(new Error(__text))
		}
	},
	/** 请求无响应 */
	(error: AxiosError) => {
		let __emsg: string = error.message || ''

		if (error.message) {
			__emsg = error.message
		}

		if (error.response) {
			__emsg = error.response.data.message ? error.response.data.message : error.response.data.data
		}
		// timeout
		if (__emsg.indexOf('timeout') >= 0) {
			__emsg = t('timeout')
		}

		//TODO: 结合接口实际情况进行权限判断
		// if (error?.response?.status === 401) {
		// 	if (router.currentRoute.value.path !== '/auth/login') {
		// 		// Notify.create({
		// 		// 	message: '登录凭证已过期，请重新登录',
		// 		// 	color: 'warning',
		// 		// 	textColor: 'dark',
		// 		// 	icon: 'announcement'
		// 		// })
		// 		message.errorMsg(t('loginout'));
		// 		router.push('/auth/login')
		// 	}
		// 	return Promise.reject(new Error('401'))
		// }
		return Promise.reject(new Error(__emsg))
	}
)

export default service
