import axios from 'axios';
import { ElNotification, ElMessageBox } from 'element-plus';
import sysConfig from "@/config";
import tool from '@/utils/tool';
import router from '@/router';
import i18n from '@/locales'
import common from "@/utils/common"

axios.defaults.baseURL = '/api'

axios.defaults.timeout = sysConfig.TIMEOUT

// HTTP request 拦截器
axios.interceptors.request.use(
	(config) => {
		config.ISPage = false;
		config.ISNEEDINDEX = false;
		let token = tool.data.get("TOKEN");
		let auth = tool.data.get("SignAuth");

		if(token||config.data.params[0].Token){
			config.headers[sysConfig.TOKEN_NAME] = sysConfig.TOKEN_PREFIX + token;
			config.headers["Authorization"] = auth;
			config.headers["Content-Type"] = "application/octet-stream";
			config.headers["Access-Control-Allow-Origin"] = "*";
			config.headers["Access-Control-Allow-Methods"] = "PUT,GET,POST,HEAD";
			config.headers["Access-Control-Expose-Headers"] = "ETag,Content-Length,x-cos-request-id";
			if (config.data)
			{
				if (config.data.params && config.data.params.length > 0)
				{
					if(config.data.params[0].Token==""||config.data.params[0].Token==undefined)
					{
						config.data.params[0].Token = token;
					}
					if (config.data.params[0].PageSize && config.data.params[0].PageSize > 0)
					{
						config.ISPage = true;
					}
					if (config.data.params[0].IsNeedIndex)
					{
						config.ISNEEDINDEX = true;
					}
				}
			}
		}
		if(!sysConfig.REQUEST_CACHE && config.method == 'get'){
			config.params = config.params || {};
			config.params['_'] = new Date().getTime();
		}
		Object.assign(config.headers, sysConfig.HEADERS)
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

// HTTP response 拦截器
axios.interceptors.response.use(
	(response) => {
		if (response.data && response.data.error)
		{
			if (response.data.error.code >=1 && response.data.error.code <=5)
			{
				//token失效，验证失败，清理token
				tool.data.remove("TOKEN");
				router.replace({path: '/reportTemplateDesigner'});
			}
			console.log(response.data.error)
			response.data.result = response.data.error;
			if(response.data.result.message!=undefined)
			{
				response.data.result.message = http.TurnMsg(response.data.result.code,response.data.result.message);
			}
			return response;
		}
		if (response.config.ISPage)
		{
			if (response.data && response.data.result)
			{
				var resultInfo = response.data.result;
				if (resultInfo && resultInfo.CurrentPage && resultInfo.CurrentPage > 0)
				{
					var resultData = []
					if (response.config.ISNEEDINDEX)
					{
						if (resultInfo.PageData.length > 0)
						{
							for(var i = 0; i < resultInfo.PageData.length; i++)
							{
								var dataItem = resultInfo.PageData[i];
								dataItem.DefaultIndex = i;
								resultData.push(dataItem);
							}
						}
					}
					else
					{
						resultData = resultInfo.PageData;
					}
					var newData1 = {
						total: resultInfo.DataCount,
						page: resultInfo.CurrentPage,
						pageSize: resultInfo.PageSize,
						rows: resultData,
						summary: {}
					}
					response.data.result = newData1;
					return response;
				}
				else if (resultInfo && resultInfo.PageIndex && resultInfo.PageIndex > 0)
				{
					var resultData2 = []
					if (response.config.ISNEEDINDEX)
					{
						if (resultInfo.PageData.length > 0)
						{
							for(var j = 0; j < resultInfo.PageData.length; j++)
							{
								var dataItem2 = resultInfo.PageData[j];
								dataItem2.DefaultIndex = j;
								resultData2.push(dataItem2);
							}
						}
					}
					else
					{
						resultData2 = resultInfo.PageData;
					}
					var newData2 = {
						total: resultInfo.TotalCount,
						page: resultInfo.PageIndex,
						pageSize: resultInfo.PageSize,
						rows: resultData2,
						summary: {}
					}
					response.data.result = newData2;
					return response;
				}
			}
			return response;
		}
		return response
	},
	(error) => {
		if (error.response) {
			if (error.response.status == 404) {
				ElNotification.error({
					title: i18n.global.tc('error.requestError'),
					message: i18n.global.tc('error.response404')
				});
			} else if (error.response.status == 500) {
				console.log(error.response.data.message)
				ElNotification.error({
					title: i18n.global.tc('error.requestError'),
					message: i18n.global.tc('error.response500'),
				});
			} else if (error.response.status == 401) {
				ElMessageBox.confirm(i18n.global.tc('error.LoginTimeOut'), i18n.global.tc('systemError'), {
					type: 'error',
					closeOnClickModal: false,
					center: true,
					confirmButtonText: i18n.global.tc('error.againLogin'),
					cancelButtonText: i18n.global.tc('dialogBox.cancelButtonText')
				}).then(() => {
					router.replace({path: '/login'});
				}).catch(() => {})
			} else {
				console.log(error.response.data.message);
			}
		} else {
			ElNotification.error({
				title: i18n.global.tc('error.requestError'),
				message: i18n.global.tc('error.UnResponse')
			});
		}

		return Promise.reject(error.response);
	}
);

var http = {

	/** get 请求
	 * @param  {接口地址} url
	 * @param  {请求参数} params
	 * @param  {参数} config
	 */
	get: function(params={}, url='/IManagementService/', config={}) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'get',
				url: url,
				params: params,
				...config
			}).then((response) => {
				resolve(response.data.result);
			}).catch((error) => {
				console.log(error)
				reject(i18n.global.tc('requestError'));
			})
		})
	},

	/** post 请求
	 * @param  {接口地址} url
	 * @param  {请求参数} data
	 * @param  {参数} config
	 */
	post: function(method, data, url='/IManagementService/', config={}) {

		var params = {
			"jsonrpc": "2.0",
			"id": common.guid(),
			"method": method,
			"params": [data]
		}
		return new Promise((resolve, reject) => {
			axios({
				method: 'post',
				url: url,
				data: params,
				...config
			}).then((response) => {
				resolve(response.data.result);
			}).catch((error) => {
				console.log(error)
				reject(i18n.global.tc('requestError'));
			})
		})
	},

	/** put 请求
	 * @param  {签名} authorization
	 * @param  {接口地址} url
	 * @param  {请求参数} data
	 */
	 put: function(authorization, data, url) {
		tool.data.set("SignAuth", authorization);
		return new Promise((resolve, reject) => {
			axios({
				headers: {
					"Authorization": authorization,
					"Access-Control-Allow-Origin":"*"
				},
				method: 'put',
				url: url,
				data: data
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				reject(error);
			})
		})
	},

	/** patch 请求
	 * @param  {接口地址} url
	 * @param  {请求参数} data
	 * @param  {参数} config
	 */
	patch: function(data={}, url='/',config={}) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'patch',
				url: url,
				data: data,
				...config
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				reject(error);
			})
		})
	},

	/** delete 请求
	 * @param  {接口地址} url
	 * @param  {请求参数} data
	 * @param  {参数} config
	 */
	delete: function(data={}, url='/',config={}) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'delete',
				url: url,
				data: data,
				...config
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				reject(error);
			})
		})
	},

	/** jsonp 请求
	 * @param  {接口地址} url
	 * @param  {JSONP回调函数名称} name
	 */
	jsonp: function(name='jsonp',url='/',  defaultProxy=''){
		if (defaultProxy.length > 0)
		{
			axios.defaults.baseURL = defaultProxy
		}
		return new Promise((resolve) => {
			var script = document.createElement('script')
			var _id = `jsonp${Math.ceil(Math.random() * 1000000)}`
			script.id = _id
			script.type = 'text/javascript'
			script.src = url
			window[name] =(response) => {
				resolve(response)
				document.getElementsByTagName('head')[0].removeChild(script)
				try {
					delete window[name];
				}catch(e){
					window[name] = undefined;
				}
			}
			document.getElementsByTagName('head')[0].appendChild(script)
		})
	},
	TurnMsg:function(code,message)
	{
		var returnMsg = i18n.global.tc(message);
		return returnMsg;
  }
}

export default http;
