import axios from 'axios'
import router from '../router.js'
import md5 from 'js-md5'
import sha1 from './sha1.js'
// import {
// 	MessageBox,
// 	Toast
// } from 'mint-ui'
import {
	Message
} from 'element-ui'
import store from '../store.js'
// create an axios instance
const service = axios.create({
	baseURL: store.state.www, // url = base url + request url
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
	config => {
		let token = localStorage.getItem("token") || ''
		let sign_time = new Date().getTime()
		let sys_appid = 'jzsred2022224'
		let sys_appsecret = '2022224jzsred'
		let sys_token = md5(md5(sys_appid + sys_appsecret) + sign_time + sha1(sys_appsecret + sign_time))
		if(!config.headers) {
			config.headers = {
				"sys-appid": sys_appid,
				"sign-time": sign_time,
				"sys-token": sys_token,
				"token": token
			}
		}else {
			config.headers['sys-appid'] = sys_appid
			config.headers['sign-time'] = sign_time
			config.headers['sys-token'] = sys_token
			config.headers['token'] = token
		}
		return config
	},
	error => {
		// do something with request error
		console.log(error) // for debug
		return Promise.reject(error)
	}
)

service.interceptors.response.use(
	response => {
		const res = response.data
		console.log(res)
		// 解析字符串为数字
		if (res.code != 1) {
			Message.error('加载错误请刷新重试')
			console.log(res,'扑街');
			return Promise.reject(new Error(res.msg || 'Error'))
		} else {
			return res
		}
		// return res
	},
	error => {
		console.log('err' + error) // for debug
		// Toast({
		// 	message: '加载错误请刷新重试！',
		// 	duration: 1 * 1000
		// })
		Message.error('加载错误请刷新重试')
		return Promise.reject(error)
	}
)
export default service