import axios from "axios"
import { getCookie } from '@/utils/cookie'
import router from '@/router'
import { Message } from 'element-ui'


const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API,
	timeout: 60000, // 请求超时时间 毫秒
	// withCredentials: true,
	headers: {
		"Content-Type": "application/json",
	},
})

service.interceptors.request.use(
	(config) => {
		config.headers.satoken = getCookie('cmnw_token')
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
)

service.interceptors.response.use(
	(response) => {
		const res = response.data;
		if(res.msg&&res.msg.includes('Token无效')) {
			Message.error('登录已过期')
			router.push({
				name: 'Login'
			}).catch(err => { console.log(err) })
		}
		return res;
	},
	(error) => {
		return Promise.reject(error);
	}
)


const service_city = axios.create({
	baseURL: process.env.VUE_APP_CITY_API,
	timeout: 60000, // 请求超时时间 毫秒
	// withCredentials: true,
	headers: {
		"Content-Type": "application/json",
	},
})

service_city.interceptors.request.use(
	(config) => {
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
)

service_city.interceptors.response.use(
	(response) => {
		const res = response.data;
		return res;
	},
	(error) => {
		return Promise.reject(error);
	}
)


const requestFormDataInstance = axios.create({
	baseURL: 'http://10.121.226.85:8888/',
	timeout: 60000,
	// withCredentials,
	method: 'post',
	headers: {

		"Content-Type": "application/x-www-form-urlencoded"
	},
	transformRequest: [(data) => {

		if (data) {
			let params = new FormData()
			let keys = Object.keys(data)
			keys.forEach(key => {
				params.append(key, data[key])
			})
			return params
		}
		return data
	}]
})
requestFormDataInstance.interceptors.request.use((config) => {
	console.log(config)
	return config
}, (error) => {
	return new Error(error)
})
requestFormDataInstance.interceptors.response.use(function (res) {
	return res.data
}, function (error) {

	throw new Error(error)
})


export {
	service,
	service_city,
	requestFormDataInstance
}