import axios from 'axios'
import qs from 'qs'
// import store from '@/store'
import router from '@/router'

import {
	DecryptCBC,
	EncryptCBC,
	DecryptECB,
	EncryptECB,
	EncryptRAS,
	getUUID,
} from '@/axios/crypto.js'

// import {
// 	useRouter
// } from 'vue-router'
// const router = useRouter()
// import {
//   Message
// } from 'element-ui';

const baseApi = import.meta.env.VITE_BASE_API

var encryptFlag = '0'
var url = ''
//test
axios.defaults.baseURL = baseApi //store.state.app.serverName
//设置默认请求头
axios.defaults.headers = {
	'Content-Type': 'application/x-www-form-urlencoded',
	//'Content-Type': 'application/json',
}
axios.defaults.timeout = 60000

//请求拦截器
axios.interceptors.request.use(config => {
	url = config.url
	// console.log('axios.interceptors.request url：：：' + url)
	// console.log("url：" + url)
	var bool1 = url.indexOf("queryPublicKey")
	var bool2 = url.indexOf("upload")
	var bool3 = url.indexOf("download")
	var bool4 = url.indexOf("show")
	var bool5 = url.indexOf("import")
	var bool6 = url.indexOf("export")
	var bool7 = url.indexOf("fr/webroot/decision")
	if (bool7 > -1) {
		return config
	}
	// if(encryptFlag == '1' && config.url.indexOf('activiti/service/model')){
	//   encryptFlag= '0'
	// }else {
	//    encryptFlag= '1'
	// }

	config.headers.token = localStorage.getItem('token')
	config.headers.userId = localStorage.getItem('userId')
	config.headers.userName = localStorage.getItem('userName')
	config.headers.menuId = localStorage.getItem('menuId')
	config.headers.belongId = localStorage.getItem('belongId')
	config.headers.systemCode = 'safeplat'
	config.headers.os = 'h5'

	var publicKey = localStorage.getItem('publicKey')
	var KEY = getUUID()
	var IV = getUUID()
	config.headers.key = EncryptRAS(KEY, publicKey)
	config.headers.iv = EncryptRAS(IV, publicKey)
	config.headers.publicKey = publicKey
	config.headers.encryptFlag = encryptFlag



	if (bool1 > 0 || bool2 > 0 || bool3 > 0 || bool4 > 0 || bool5 > 0 || bool6 > 0) {
		return config
	}
	// if (!config.params) {
	// 	return config
	// }

	// console.log("encryptFlag：" + encryptFlag)
	// console.log("config.method：" + config.method)
	// console.log("Content-Type：" + config.headers["Content-Type"])
	if (config.method == 'get') {
		if (encryptFlag == '0') {
			//get不加密
			for (let key of Object.keys(config.params)) {
				if (config.params[key] || config.params[key] == 0) {
					config.params[key] = encodeURIComponent(config.params[key].toString())
				} else {
					config.params[key] = encodeURIComponent('')
				}
			}
		} else {
			//get加密
			for (let key of Object.keys(config.params)) {
				if (config.params[key] || config.params[key] == 0) {

					// console.log(config.params[key].toString())
					// console.log(KEY)
					// console.log(IV)
					// console.log(publicKey)
					config.params[key] = EncryptCBC(encodeURIComponent(config.params[key].toString()),
						KEY, IV)
				} else {
					config.params[key] = EncryptCBC(encodeURIComponent(''), KEY, IV)
				}
			}
			config.params['getParam'] = EncryptCBC(encodeURIComponent(''), KEY, IV)
		}
	} else if (config.method == 'post') {
		if (encryptFlag == '0') {
			//post不加密 application/json不需要处理
			//application/x-www-form-urlencoded
			if (config.headers["Content-Type"] == 'application/x-www-form-urlencoded') {
				for (let key of Object.keys(config.data)) {
					if (config.data[key] || config.data[key] == 0) {
						config.data[key] = encodeURIComponent(config.data[key].toString())
					} else {
						config.data[key] = encodeURIComponent('')
					}
				}
				config.data['postParam'] = encodeURIComponent('')
				config.data = qs.stringify(config.data);
			}
		} else {
			//post加密
			// console.log('config.headers["Content-Type"]' + config.headers["Content-Type"])
			if (config.headers["Content-Type"] == 'application/json') {
				//application/json
				config.data = EncryptCBC(JSON.stringify(config.data), KEY, IV)
				// console.log('json 加密：'+config.data)
			} else {
				//application/x-www-form-urlencoded

				for (let key of Object.keys(config.data)) {
					// console.log(config.data[key].toString())
					// console.log(KEY)
					// console.log(IV)
					// console.log(publicKey)
					if (config.data[key] || config.data[key] == 0) {
						config.data[key] = EncryptCBC(encodeURIComponent(config.data[key].toString()), KEY, IV)
					} else {
						config.data[key] = EncryptCBC(encodeURIComponent(''), KEY, IV)
					}
				}
				config.data['postParam'] = EncryptCBC(encodeURIComponent(''), KEY, IV)
				config.data = qs.stringify(config.data);
			}
		}
	}

	return config


}, error => {
	// console.log('axios.interceptors.request error：：：' + error)
	return Promise.reject(error)
})

//响应拦截器即异常处理
axios.interceptors.response.use(response => {
	// url.indexOf('download') > 0 || url.indexOf('export') > 0 ||
	if (url.indexOf('fr/webroot/decision') > -1) {
		// console.log("url.indexOf('fr/webroot/decision'):::"+url.indexOf('fr/webroot/decision'))
		return response
	}
	if (encryptFlag == '1' && url.indexOf('activiti/service/model') < 0) {
		var a = DecryptCBC(response.data)
		response.data = JSON.parse(a)
	}

	// console.log(response.data.code)
	if (response.data.code == '0') {
		var t = typeof response.data.data
		// console.log(t)
		if (t == 'string') {
			try {
				response.data.data = JSON.parse(response.data.data)
			} catch (e) {
				return response
			}
		}
		return response
	} else {
		return response
		// Message({
		//   type: 'error',
		//   message: '操作失败!error code:' + response.data.code + ';' + response.data.msg
		// })
		// return Promise.reject()
	}
}, err => {
	// console.log("axios.interceptors.response err:::" + err)
	// console.log("axios.interceptors.response err:::" + JSON.stringify(err))
	if (err && err.response) {

		switch (err.response.status) {
			case 203:
				err.message = '登录超时，请重新登录'
				router.replace({
					path: '/login',
					query: {
						error: err.message
					},
				})
				break;
			case 400:
				err.message = '错误请求'
				break;
			case 401:
				err.message = '未授权，请重新登录'
				router.replace({
					path: '/login401',
					query: {
						error: err.message
					},
				})
				break;
			case 403:
				err.message = '拒绝访问'
				break;
			case 404:
				err.message = '请求错误,未找到该资源'
				break;
			case 405:
				err.message = '请求方法未允许'
				break;
			case 408:
				err.message = '请求超时'
				break;
			case 413:
				err.message = '上传文件大小请控制在10M以内'
				break;
			case 500:
				err.message = '服务器端出错，请联系开发人员'
				break;
			case 501:
				err.message = '微服务重启，暂未获取心跳，请稍等'
				break;
			case 502:
				err.message = '网络错误'
				break;
			case 503:
				err.message = '服务不可用'
				break;
			case 504:
				err.message = '网络超时'
				break;
			case 505:
				err.message = 'http版本不支持该请求'
				break;
			case 600:
				err.message = '登录超时，请重新登陆'
				router.push({
					path: '/login',
					query: {
						error: err.message
					},
					replace: true
				})
				break;
			case 601:
				err.message = '用户在另一地点登录！'
				router.push({
					path: '/login',
					query: {
						error: err.message
					},
					replace: true
				})
				break;
			default:
				err.message = `连接错误${err.response.status}`
		}

	} else {
		err.message = "连接到服务器失败"
	}
	console.log('axiox err----'+err.message)

	// var result = {
	//   data: {
	//     code: err.response.status,
	//     data: '',
	//     msg: err.message
	//   }
	// }
	return Promise.reject()
})



export default {
	//get请求
	get(url, param) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'get',
				url,
				params: param
			}).then(response => {
				//response.data=JSON.parse(Decrypt(response.data) )
				resolve(response)
			}).catch(error => {
				reject(error)
			})
		})
	},

	//post请求
	post(url, param, contentType = 'application/x-www-form-urlencoded') {
		//默认  如果json，再传一个参数
		// console.log('arguments.length:' + arguments.length)
		if (arguments.length > 2) {
			contentType = arguments[2]
		}
		// console.log('arguments[2]:' + arguments[2])
		return new Promise((resolve, reject) => {
			axios({
				method: 'post',
				url,
				data: param,
				headers: {
					"Content-Type": contentType
				}
			}).then(response => {
				//response.data=JSON.parse(Decrypt(response.data) )
				resolve(response)
			}).catch(error => {
				reject(error)
			})
		})
	}
};
