/*
 * @Author: your name
 * @Date: 2021-10-13 09:28:02
 * @LastEditTime: 2021-11-11 10:45:00
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /data-show/src/request/index.js
 */
import axios from 'axios';
import qs from 'qs';
import router from "@/permission"
import { message} from 'ant-design-vue'
function filterRequestData(obj) {
    let o = {};
    for(let key in obj) {
        let b1 = obj[key] === 0;
        let b2 = obj[key] === false;
        if(obj[key] || b1 || b2) {
            o[key] = obj[key]
        }
    }
    return o;
}
//创建axios的实例
const httpService = axios.create({
    baseURL: 'http://cloud.sws010.com',// TODO:具体的配置可以根据项目情况而来
    timeout: 5000
})

//axios的拦截--request
httpService.interceptors.request.use(config => {
    // 请求成功处理
    // if(localStorage.getItem('token')){//判断浏览器中的cookie中是否存在项目的token
    //     config.headers.token = localStorage.getItem('token')
    // }
    const rqParams = filterRequestData(config.params);
    const rqData = filterRequestData(config.data);
    // post 'Content-Type' === 'application/x-www-form-urlencoded'
    // 	manage-login-token
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    if(config.method === 'post') {
        config.data = qs.stringify(rqData);
    } else {
        config.data = rqData;
        config.params = rqParams;
    }
    return config;
},err => {
    Promise.reject(err);// 请求错误处理
})

//4、axios的拦截--response
httpService.interceptors.response.use(response => {
	// TODO:具体的code对应的处理可继续添加修改
    let data = null;
    let data1 = null;
    let msg = '';
    let res = response.data;
    let totalNum = 0;
    if(res.Code == 1){
        data = res.Data || [];
        data1 = res.Data1 || [];
        msg = res.Msg || "";
        totalNum = res.totalNum || 0;
        return {data,data1, msg, totalNum};
    } else {
        msg = res.Msg || "";
        message.error(msg);
        return Promise.reject(new Error(msg))
    }
},err => {
	// TODO:具体的code对应的处理可继续添加修改
    if(err.response.Code === 301){
         //登录过期跳转登录页面，并将要浏览的页面fullPath传过去，登录成功后跳转需要访问的页面 ---主页(index) 或者 退出到登录前的浏览的页面
        //这样登录页面登录接口成功之后可以进行跳转 主页(index) 或者 退出到登录前的页面： let path = this.$route.query.redirect || '/index.js';   this.$router.push(path);
        setTimeout(() => {
          router.replace({
            path: '/login',
            query: {
              redirect: router.currentRoute.fullPath
            }
          });
        }, 1000);
    }
    return Promise.reject(err);
})

export default httpService