import axios from 'axios';
axios.defaults.withCredentials = true;
export default class Net {
    static get(url, params) {
        return new Promise((resolve, reject) => {
            axios({
                method: 'get',
                url,
                params,
                headers: {
                    // Authorization: localStorage.getItem('token') || ""
                    Authorization: localStorage.getItem('token') ? JSON.parse(localStorage.getItem('token')) : "",
                    'ccbhousing-auth': localStorage.getItem('token') ? JSON.parse(localStorage.getItem('token')) : "",
                }
            })
                .then((res) => {
                    this.successTodo(resolve, reject, res);
                })
                .catch((error) => {
                    this.errTodo(error, url);
                });
        });
    }

    static post(url, params) {
        return new Promise((resolve, reject) => {
            const headers =
                localStorage.getItem('token') ? {
                    Authorization: JSON.parse(localStorage.getItem('token')),
                    'ccbhousing-auth': JSON.parse(localStorage.getItem('token')),
                    'Content-Type': 'application/json;charset=utf-8',
                } : {
                    Authorization: '',
                    'ccbhousing-auth': '',
                    'Content-Type': 'application/json;charset=utf-8',
                };
            axios({
                method: 'post',
                url,
                data: JSON.stringify(params),
                headers: headers
            })
                .then((res) => {
                    this.successTodo(resolve, reject, res);
                })
                .catch((error) => {
                    this.errTodo(error, url);
                });
        });
    }

    // 处理异常方法
    static successTodo(resolve, reject, val) {
        let retcode = parseInt(val.data.code);
        if (retcode === 200) {
            resolve(val.data.data);
        } else if (retcode === 201) {
            // router.push('/login');
            // localStorage.removeItem('token');
            reject(val.data.msg);
        } else {
            reject(val.data.msg);
        }
    }

    // 处理异常方法
    static errTodo(error) {
        console.log(error)
    }
}