import axios from "axios"
import {compile} from "path-to-regexp"
import { message } from "antd"
import {httpUtil} from "./index"
import config from "@/commons"
const {page:{loginpage},headerstring} =config

const requestList:Array<any> = []

axios.interceptors.request.use(
    (config:any) => {
        config.headers['WWW-Authenticate'] = null;
        const requestMark = `${config.method} ${config.url}`; // 请求标识 为了在响应的时候删除请求队列中的数据
        let flagindex:any = null
        const flag = requestList.find((item:any,key:any)=>{
            if(item.requestMark === requestMark)
                flagindex = key
            return item.requestMark === requestMark
        });
        if (flag&&flag.requestMark) {
            requestList.splice(flagindex,1); // 在等待重新发起的请求列表中移除
            if(flag.hashrequest){
                flag.cancel()
            }
        }
        const cancelToken = axios.CancelToken;
        const source:any = cancelToken.source();
        config.cancelToken = source.token; 
        config.cancel = source.cancel;
        config.requestMark = requestMark; //添加唯一标识符
        requestList.push(config);
        return config;
    },
    err => {
        return Promise.reject(err);
});


axios.interceptors.response.use(
    (response) => {
        const config = response.config;
        const requestMark = `${config.method} ${config.url}`; // 请求标识 为了在响应的时候删除请求队列中的数据
        let flagindex:any = null
        const flag = requestList.find((item:any,key:any)=>{
            if(item.requestMark === requestMark)
                flagindex = key
            return item.requestMark === requestMark
        });
        if (flag&&flag.requestMark) {
            requestList.splice(flagindex,1); // 在等待重新发起的请求列表中移除
        }
        return response;
    },
    error => {
        if (error.response) {
            switch (error.response?.status) {
            case 401:
                {
                    const config = {
                        content:"身份信息已过期，正在重新验证……",
                        key:'logout'
                    }
                    message.warning(config)  
                    httpUtil.logout()
                    //window.location.href=`${loginpage}?redirectURL=${encodeURIComponent(window.location.href)}`
                }
            }
        }
        // else if((error.ApiError?.status||'')==='INTERNAL_SERVER_ERROR'){

        // }
        return Promise.reject(error)   // 返回接口返回的错误信息
    }
);



const fetch = (options:any) => {
    let { method = "get", data,urldata , params , url, config={},hashrequest=false}:any = options
    const pathname = window.location.pathname
    if(pathname.includes('staticmeta')){
        let headers:any = null
        let tempconfig:any = config
        if(pathname.includes('staticmeta')){
            const tempheader = config.headers?config.headers:{}
            headers = {
            ...tempheader,
            'Authorization': headerstring
            };
            tempconfig.headers = headers
            tempconfig.hashrequest = hashrequest
        }
        try {
            url = compile(url)(urldata)
    
        } catch (e) {
        }
        switch (method.toLowerCase()) {
            case "get":
                const payloadget:any={params: data?data:params,headers,hashrequest}
                return axios.get(url,payloadget)
            case "delete":
                const payloaddelete:any = {data,params,headers,hashrequest}
                return axios.delete(url,payloaddelete)
            case "post":
                if(params){
                    tempconfig.params = params
                }
                return axios.post(url, data, tempconfig)
            case "put":
                return axios.put(url, data, tempconfig)
            case "patch":
                return axios.patch(url, data, tempconfig)
            case "postdownload":
                return axios({...options,method:'post',headers})
            default:
                return axios({...options,headers})
        }
    }else{
        try {
            url = compile(url)(urldata)
    
        } catch (e) {
            //console.log(e)
        }

        switch (method.toLowerCase()) {
            case "get":
                const payloadget:any={params: data?data:params,hashrequest}
                return axios.get(url,payloadget)
            case "delete":
                const payloaddelete:any = {data,params,hashrequest}
                return axios.delete(url,payloaddelete)
            case "post":
                if(params){
                    config.params = params
                }
                config.hashrequest = hashrequest
                return axios.post(url, data, config)
            case "put":
                return axios.put(url, data, config)
            case "patch":
                return axios.patch(url, data, config)
            case "postdownload":
                return axios({...options,method:'post'})
            default:
                return axios(options)
        }
    }
}

export default function request(options:any, autotip:boolean){
    return new Promise((resolve)=>{
        let result:any = {}
        fetch(options).then(response => {
            console.log('response',response)
            try {
                if(response?.status===200){
                    if(autotip)
                        message.success('操作成功')
                    result.status=200
                    result.data = response?.data
                    result.headers=response.headers
                    resolve(result)
                }else if(response?.status===401){
                    if(!options.url.includes("signin"))
                        httpUtil.logout()
                    else
                        resolve({status:500,data:{}})
                }else{
                    if(autotip)
                        message.error('操作异常')
                    result.status = 500
                    result.data = response?.data
                    result.headers=response.headers
                    resolve(result)
                }
            } catch (error) {
                if(autotip)
                    message.error('操作异常')
                result.status=500
                result = response?.data
                resolve(result)
            }
        }).catch(async (error) => {
            if(autotip)
                message.error('操作异常')
            let data = error.response;
            if(data?.ApiError||data?.status){
                result.status=500
                result.data=data.data
            }
            resolve(result)
        })
    })
    
}
