import axios from "axios";
import router from "@/router";
import Cookies from "js-cookie";
import qs from "qs";

// import Vue from "vue";
// const baseURL = "http://1shoudan.com"; // 正式环境线上 废弃
const baseURL = "http://idaotian.com"; // 正式环境线上
// const baseURL = "http://idagou.cn"; // 正式环境线上
// console.log(baseURL); 
// const baseURL = "https://d.matripe.com.cn"; // 正式环境本地
// const baseURL = "http://bl7.matripe.com.cn:8001"; // 测试环境本地
// const baseURL = "http://1shoudan.renminshitang.com.cn"; // 测试环境线上
// const baseURL = "http://localhost:8001";
// const data1 = require.context("./", false, /\.js$/); // 测试用
// console.log(data1.keys());
axios.defaults.withCredentials = true; //添加这行代码
// axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded"
// console.log(axios);
const service = axios.create({
	// baseURL: "/api_prod", // url = base url + request url  测试
	baseURL: baseURL, //  baseURL: "/api", // url = base url + request url 正式
	withCredentials: true, // send cookies when cross-domain requests
	timeout: 60000, // request timeout
	crossDomain: true,
});
service.interceptors.request.use(
	(req) => {
		// console.log(req);
		// if (req.method == "post" && req.headers["Content-type"]) {
		// 	if (req.headers["Content-type"].indexOf("multipart/form-data") == -1 && req.headers["Content-type"].indexOf("application/x-www-form-urlencoded") == -1) {
		// 		let dataObj = qs.stringify(req.data);
		// 		console.log(dataObj);
		// 		req.data = dataObj;
		// 	}
		// }

		if (localStorage.getItem("LOGIN_DATA")) {
			req.headers.Authorization = "Bearer " + JSON.parse(localStorage.getItem("LOGIN_DATA")).token;
      console.log('getToken++++++++++++++++++++++++++++++++++++++++++++++++++++');
		}
		// application/json
		// if(req.headers.common.Accept.indexOf('application/json') > 0 || req.headers.Accept.indexOf('application/json') > 0){
		//   console.log('is application/json');
		// }
		return req;
	},
	(err) => {
		console.log(err);
	}
);
service.interceptors.response.use(
	(response) => {
		// console.log(response);
		let { msg, status } = response.data;
		// return response;
		// console.log(status);
		if (status == 9999) {
			localStorage.removeItem("LOGIN_DATA");
			router.push("/login");
			// 跳转到登录页面
			// this.$message.warning(msg);
			return Promise.reject(new Error("token过期"));
		}
		if (response.status === 200) {
			return response;
		} else {
			// Message.error(message)
			return Promise.reject(new Error(msg));
		}
	},
	(error) => {
		console.log(error);
		// if (error.toString().indexOf("9999") !== -1) {
		//   router.push("/login");
		//   // Vue.$message.warning(msg)
		// } else if (error.message.indexOf("500") !== -1) {
		// }
		// return Promise.reject(error);
	}
);
export default service;
