import axios from 'axios';
import StoreUtil from "@/utils/document/StoreUtil.js";
import {saveAs} from 'file-saver'
import WindowUtil from "@/utils/document/WindowUtil";

/**
 * 默认axios实例
 */
const defaultService = axios.create({
    baseURL: process.env.VUE_APP_REQUEST, // 基本路径
    timeout: 10000, // 超时时间
    responseType: 'json', // 服务器响应的数据类型
    responseEncoding: 'utf8',
    // maxContentLength: 10000, // 允许的响应内容的最大尺寸
});
/**
 * 请求拦截器
 */
defaultService.interceptors.request.use((config) => {
    const token = StoreUtil.getLocal("token").body;
    if (token) {
        config.headers.token = token;
    }
    return config;
}, (error) => {
    return Promise.reject(error);
},);
/**
 * 响应拦截器
 */
defaultService.interceptors.response.use((response) => {
    return response;
}, (error) => {
    return Promise.reject(error);
},);

const fileTypes = ['pdf','wps','word','xml','json','xsl']

export default class HttpUtil {


    /**
     * get请求json形式
     * @param url
     * @param options
     * @returns {Promise<{msg: string, code: number, data: any}|{msg, code: number, data: any}|any>}
     */
    static async getForJson(url, options = {}) {
        let responseObj
        try {
            const {data: result, status, statusText, headers, config, request} = await defaultService.get(url, options)
            if (status !== 200) {
                responseObj = {
                    code: status, data: null, msg: statusText,
                }
            } else {
                responseObj = {
                    code: result.code, data: result.data, msg: result.message
                }
            }
        } catch (e) {
            responseObj = {
                code: 500, data: null, msg: e.message,
            };
        }

        if (process.env.NODE_ENV === 'development') {
            console.log(`请求接口: ${url},`, ` 入参:`, options.params, ` 响应:`, responseObj);
        }
        return responseObj
    }

    /**
     * post请求json形式
     * @param url
     * @param data
     * @param options
     * @returns {Promise<{msg: string, code: number, data: null}>}
     */
    static async postForJson(url, data = {}, options = {}) {
        let responseObj
        try {
            const {
                data: result, status, statusText, headers, config, request
            } = await defaultService.post(url, data, options)
            if (status !== 200) {
                responseObj = {
                    code: status, data: null, msg: statusText,
                }
            } else {
                responseObj = {
                    code: result.code, data: result.data, msg: result.message
                }
            }
        } catch (e) {
            responseObj = {
                code: 500, data: null, msg: e.message,
            };
        }
        if (process.env.NODE_ENV === 'development') {
            console.log(`请求接口: ${url},`, ` 入参:`, data, ` 响应:`, responseObj);
        }
        return responseObj;
    }

    static async upload(url, file, data = {}, options = {}) {
        const formData = new FormData()
        Object.keys(data).forEach(key => {
            formData.append(key, data[key])
        })
        if (file) {
            formData.append("file", file)
        }
        let responseObj
        try {
            const {
                data: result, status, statusText, headers, config, request
            } = await defaultService.post(url, formData, {
                ...options,
                'Content-type': 'multipart/form-data',
                timeout: 1000 * 60,
            })
            if (status !== 200) {
                responseObj = {
                    code: status, data: null, msg: statusText,
                }
            } else {
                responseObj = {
                    code: result.code, data: result.data, msg: result.message
                }
            }
        } catch (e) {
            responseObj = {
                code: 500, data: null, msg: e.message,
            };
        }
        if (process.env.NODE_ENV === 'development') {
            console.log(`请求接口: ${url},`, ` 入参:`, data, ` 响应:`, responseObj);
        }
        return responseObj;
    }

    /**
     * 文件下载
     * @param url
     * @param fileName
     * @returns {Promise<void>}
     */
    static async download(url, fileName) {
        const {data} = await defaultService.get(url, {
            responseType: 'blob'
        })
        if (data) {
            let blob = new Blob([data])
            if (!fileName){
                let contentType = data.type
                let type = fileTypes.find(item=>contentType.includes(item))
                if (type){
                    fileName = WindowUtil.uuid()+`.${type}`
                }else {
                    fileName = WindowUtil.uuid()
                }
            }
            saveAs(blob, fileName)
        }

    }

}
