import axios from '../axios/axiosConfig';
import { config as appConfig } from '../config.js';
import * as api from '../axios/api.js';
import qs from 'qs';
import whiteList from '../axios/whiteList';
//import { reject, resolve } from 'core-js/fn/promise';


if (!appConfig.BASE_URL) {
    appConfig.BASE_URL = appConfig.REAL_URL;
} else if (!appConfig.REAL_URL) {
    appConfig.REAL_URL = appConfig.BASE_URL;
}
//获取url
function getUrl(url) {
    let urlPre = url.split('?')[0];
    let flag = false;
    $.each(api, (key, val) => {
        if (urlPre == val) {
            $.each(whiteList, (_, wl) => {
                if (wl.key == key && wl.isMock) {
                    flag = true;
                    return false;
                }
            });
        }
    });
    if (!flag) {
        url = appConfig.REAL_URL + url;
    }
// console.log(url);
    return url;
}

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function httpGet(url, params = {}) {
    url = getUrl(url);
    // log(url);
    return new Promise((resolve, reject) => {
        //这几个几url始终使用mokc数据
        if (url.indexOf('alarm/bigScreen/alertComponent') > -1) {
            resolve(alertComponen());
        } else if (url.indexOf('alarm/bigScreen/securityComponent') > -1) {
            resolve(securityComponent());
        } else {
            axios
                .get(url, {
                    params: params
                })
                .then(response => {
                    resolve(response.data);
                })
                .catch(err => {
                    reject(err);
                });
        }
    });
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function httpPost(url, data = {}) {
    url = getUrl(url);
    
    return new Promise((resolve, reject) => {
        // console.log(url);
        axios.post(url, qs.stringify(data)).then(
            response => {
                resolve(response.data);
            },
            err => {
                reject(err);
            }
        );
    });
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function patch(url, data = {}) {
    url = getUrl(url);
    return new Promise((resolve, reject) => {
        axios.patch(url, data).then(
            response => {
                resolve(response.data);
            },
            err => {
                reject(err);
            }
        );
    });
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function put(url, data = {}) {
    url = getUrl(url);
    return new Promise((resolve, reject) => {
        axios.put(url, qs.stringify(data)).then(
            response => {
                resolve(response.data);
            },
            err => {
                reject(err);
            }
        );
    });
}
/**
 * 封装put请求 参数放在body
 * @param url
 * @param data
 * @returns {Promise}
 */
export function putForJson(url, data = {}) {
    url = getUrl(url);
    return new Promise((resolve, reject) => {
        axios({
            method: 'put',
            url: url,
            data: data,
            headers: { 'Content-Type': 'application/json;charset=UTF-8' }
        }).then(
            response => {
                resolve(response.data);
            },
            err => {
                reject(err);
            }
        );
    });
}

/**
 * 封装del请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function httpDel(url, data = {}) {
    url = getUrl(url);
    return new Promise((resolve, reject) => {
        axios.delete(url, { params: data }).then(
            response => {
                resolve(response.data);
            },
            err => {
                reject(err);
            }
        );
    });
}

export function httpDelForJson(url, data = {}) {
    url = getUrl(url);
    return new Promise((resolve, reject) => {
        axios({
            method: 'delete',
            url: url,
            data: data,
            headers: { 'Content-Type': 'application/json;charset=UTF-8' }
        }).then(
            response => {
                resolve(response.data);
            },
            err => {
                reject(err);
            }
        );
    });
}

export function httpPostForJson(url, data = {}) {
    url = getUrl(url);
    return new Promise((resolve, reject) => {
        axios({
            method: 'post',
            url: url,
            data: data,
            headers: { 'Content-Type': 'application/json;charset=UTF-8'}
        }).then(
            response => {
                resolve(response.data);
            },
            error => {
                resolve(error.response.data);
            }
        );
    });
}
export function httpGetFile(url, params = {}) {
    url = getUrl(url);
    return new Promise((resolve, reject) => {
        axios({
            method: 'get',
            url: url,
            params: params,
            responseType: 'blob'
        }).then(
            response => {
                resolve(response.data);
            },
            error => {
                if (error.response) {
                    console.log(error.response.status)
                    switch (error.response.status) {
                        case 403:
                            Message({
                                message: "登录凭证失效，请重新登录",
                                type: 'warning'
                            });
                            window.location.href = '#/login';
                            error.message = "登录凭证失效，请重新登录";
                            bus.$emit("todoDetailWebsocket");
                            break
                        case 401:
                            Message({
                                // message: '未授权，请重新登录',
                                message: '网络异常，请重新登录',
                                type: 'warning'
                            });
                            // error.message = '未授权，请重新登录';
                            error.message = '网络异常，请重新登录';
                            break
                        // localStorage.removeItem(appConfig.TOKEN_KEY)
                        // localStorage.removeItem(appConfig.USER_KEY)
                        // router.replace({
                        //     path: '/login',
                        //     // query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
                        // })
                        case 400:
                            error.message = '网络异常'
                        case 404:
                            error.message = '网络异常'
                            break
                        case 405:
                            error.message = '网络异常'
                            break
                        case 408:
                            error.message = '网络异常'
                            break
                        case 500:
                            Message({
                                message: '内部服务器错误，请联系管理员',
                                type: 'warning'
                            });
                            break
                        case 501:
                            error.message = '网络未实现'
                            break
                        case 502:
                            error.message = '网络错误'
                            break
                        case 503:
                            error.message = '服务不可用'
                            break
                        case 504:
                            error.message = '网络超时'
                            break
                        case 505:
                            error.message = 'http版本不支持该请求'
                            break
                        default:
                            error.message = `连接错误${error.response.status}`
                    }
                } else {
                    Message({
                        message: "网络异常",
                        type: 'warning'
                    });
                }
                return Promise.reject(error)
            }
        );
    });
}

export function httpGetExport(url, params = {}) {
    url = getUrl(url);
    return new Promise((resolve, reject) => {
        axios
            .get(url, {
                params: params,
                responseType: 'arraybuffer'
            })
            .then(response => {
                resolve(response.data);
            })
            .catch(err => {
                reject(err);
            });
    });
}

export function httpPostExport(url, params = {}) {
    url = getUrl(url);
    return new Promise((resolve, reject) => {
        axios
            .post(url, {
                params: qs.stringify(params),
                responseType: 'arraybuffer'
            })
            .then(response => {
                resolve(response.data);
            })
            .catch(err => {
                reject(err);
            });
    });
}

export function apiDownLoad(url,data) {
    url = getUrl(url);
    return new Promise((resolve,reject) => {
        axios
            .get(url,{
                params:data,
                responseType:'blob'
            }).then( res => {
                resolve(res.data)
            }).catch( err => {
                resolve(err)
            })
    })
}
export function fileDownload(data, fileName) {
    let blob = new Blob([data], {
        type: 'application/octet-stream;charset=utf-8'
    });
    let filename = fileName || 'filename';
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, filename);
    } else {
        var blobURL = window.URL.createObjectURL(blob);
        var tempLink = document.createElement('a');
        tempLink.style.display = 'none';
        tempLink.href = blobURL;
        tempLink.setAttribute('download', filename);
        if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank');
        }
        document.body.appendChild(tempLink);
        tempLink.click();
        document.body.removeChild(tempLink);
        window.URL.revokeObjectURL(blobURL);
    }
}

export function httpUpload(url, data = {}) {
    url = getUrl(url);
    return new Promise((resolve, reject) => {
        axios({
            method: 'post',
            url: url,
            data: data,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(
            response => {
                resolve(response.data);
            },
            err => {
                reject(err);
            }
        );
    });
}
// // 下载方法
// export function fileDownload (data, fileName) {
//   let blob = new Blob([data], {
//       type: "application/octet-stream"
//   });
//   let filename = fileName || "filename";
//   if (typeof window.navigator.msSaveBlob !== "undefined") {
//       window.navigator.msSaveBlob(blob, filename);
//   } else {
//       var blobURL = window.URL.createObjectURL(blob);
//       var tempLink = document.createElement("a");
//       tempLink.style.display = "none";
//       tempLink.href = blobURL;
//       tempLink.setAttribute("download", filename);
//       if (typeof tempLink.download === "undefined") {
//           tempLink.setAttribute("target", "_blank");
//       }
//       document.body.appendChild(tempLink);
//       tempLink.click();
//       document.body.removeChild(tempLink);
//       window.URL.revokeObjectURL(blobURL);
//   }
// }
