import axios from 'axios';
import router from '../router';
import qs from 'qs';
import CryptoJS from 'crypto-js';
/* eslint-disable */
let baseUrl = process.env.VUE_APP_BASE_URL;
const axiosInstance = axios.create({
    baseURL: baseUrl
});

function decrypt(content) {
    const key = CryptoJS.enc.Hex.parse('2181E9E80460B852859EE455AC5203D9');
    const cipherText = CryptoJS.enc.Hex.parse(content);
    var decrypted = CryptoJS.AES.decrypt(
        {
            ciphertext: cipherText
        },
        key,
        {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        }
    );
    return decrypted.toString(CryptoJS.enc.Utf8);
}

function encrypt(content) {
    const key = CryptoJS.enc.Hex.parse('2181E9E80460B852859EE455AC5203D9');
    var encrypted = CryptoJS.AES.encrypt(content, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.ciphertext.toString(CryptoJS.enc.Hex);
}

axiosInstance.interceptors.request.use(
    function(config) {
        config.headers = config.headers || {};
        let token = localStorage.getItem('token');
        if (token) {
            config.headers['Authorization'] = 'Bearer ' + token;
        }
        return config;
    },
    function(error) {
        return Promise.reject(error);
    }
);

axiosInstance.interceptors.response.use(
    function(response) {
        if (response.headers['content-encrypted'] === 'true') {
            let decrypted = decrypt(response.data);
            if (response.headers['content-type'].includes('application/json')) {
                response.data = JSON.parse(decrypted);
            } else {
                response.data = decrypted;
            }
        }
        return response;
    },
    function(error) {
        console.log(error);
        if (401 === error.response.status) {
            // if (router.currentRoute.name !== 'login') {
            //     router.replace({
            //         name: 'login',
            //         params: {
            //             from: router.currentRoute.name,
            //         },
            //     });
            // }else{
            // }
        }
        return Promise.reject(error.response.data);
    }
);
export default {
    axios: axiosInstance,
    install(_Vue, options) {
        _Vue.prototype.$baseUrl = baseUrl;
        _Vue.prototype.$axios = axiosInstance;
        _Vue.prototype.$http = {
            get(url, params) {
                params = params || {};
                return new Promise((resolve, reject) => {
                    axiosInstance
                        .get(
                            url,
                            {
                                params: params
                            },
                            { withCredentials: true }
                        )
                        .then(res => {
                            resolve(res.data);
                        })
                        .catch(e => {
                            reject(e);
                        });
                });
            },
            post(url, body, options) {
                options = options || {};
                options.headers = options.headers || {};
                body = body || {};
                if (body instanceof FormData) {
                    //
                } else {
                    body = { ...body };
                    options.headers['Content-Encrypted'] = 'true';
                    if (options.body === 'json') {
                        body = encrypt(JSON.stringify(body));
                        options.headers['content-type'] = 'application/json';
                    } else {
                        for (let key of Object.keys(body)) {
                            if (body[key] != undefined && body[key] !== '') {
                                body[key] = encrypt(body[key] + '');
                            }
                        }
                        body = qs.stringify(body);
                    }
                }
                return new Promise((resolve, reject) => {
                    axiosInstance
                        .post(url, body, { withCredentials: true, headers: { ...options.headers } })
                        .then(res => {
                            resolve(res.data);
                        })
                        .catch(e => {
                            reject(e);
                        });
                });
            },
            encrypt(content) {
                return encrypt(content);
            },
            decrypt(content) {
                return decrypt(content);
            }
        };
    }
};
