/*
 * @Description: file content
 * @Version: 2.0
 * @Author: ljl
 * @Date: 2022-06-21 09:48:00
 * @LastEditors: ljl
 * @LastEditTime: 2022-07-15 10:07:41
 * @FilePath: \zyypt-ssb-vue_app\src\utils\request.js
 */
import axios from 'axios';
import Vue from "vue";
import { Toast } from "vant";
Vue.use(Toast)
import {
	getToken,
} from '@/utils/auth'
import SM2 from "@/utils/sm2";
const service = axios.create({
	baseURL: ipConfig.baseURL,
	timeout: 5000
});

service.interceptors.request.use(
	config => {
		//用户userId 加密项
		if (getToken()) {
			config.headers['token'] = SM2.encrypt(getToken())
		}
		// console.log(config.data)
		config.headers['Content-Type'] = 'application/json'
		config.data = { sign: SM2.encrypt(JSON.stringify(config.data)) };
		// console.log(config.data)
		return config;
	},
	error => {
		Promise.reject(error);
	}
);

// response interceptor
service.interceptors.response.use(
	/**
	 * If you want to get http information such as headers or status
	 * Please return  response => response
	 */

	/**
	 * Determine the request status by custom code
	 * Here is just an example
	 * You can also judge the status by HTTP Status Code
	 */
	response => {
		let res = response.data
		// console.log(res)
		// if the custom code is not 20000, it is judged as an error.
		if (res.code == 0) {
			if (res.result && res.result.data) {
				if (SM2.decrypt(res.result.data)) {
					res.data = JSON.parse(SM2.decrypt(res.result.data))
				}
			}
			return res
		} else if (res.code == 203) {
			window.location.href = ipConfig.userURL + "getAppUrl"
		}
		// else if (res.code == 205) {
		// 	Toast('两人非亲属关系，不可添加')
		// }
		else {
			if (res.error.msg) {
				Toast(res.error.msg)
				return res.error
			}
			// return Promise.reject(new Error(res.message || 'Error'))
		}
	},
	error => {
		console.log('err' + error) // for debug
		return Promise.reject(error)
	}
)

export default service;
