import config from "@/commons"
import {notification,message} from "antd"

const {page} = config

export const httpUtil={
    checkSuccess:(data:any,type:number)=>{
        if(type===1){
            if(data.status===200){
                return true
            }else{
                return false
            }
        }else{
            return false;
        }
    },
    logout:()=>{
        const url = window.location.href;
        if(!url.includes("/view/login")){
            window.location.href=`${page.loginpage}?redirectURL=${encodeURIComponent(window.location.href)}`;
        }
    },
    showError:(data:any,type:number,title?:string)=>{
        console.log('error')
        console.log((data.data||{}).ApiError||(data||{}).ApiError||(data||{}).message||(data.data||{}).message)
        if(data.status&&((data.data||{}).ApiError||(data||{}).ApiError||(data||{}).message||(data.data||{}).message)){
            let messages = '未知异常';
            try {
                messages=data.data.ApiError.cnMessage
            } catch (error) {
                try {
                    messages=data.ApiError.cnMessage
                } catch (error) {
                    try {
                        messages=data.data.message
                    } catch (error) {
                        messages='获取异常信息异常'
                    }
                }
            }
            if(type===1){
                notification['error']({
                    message:'系统异常',
                    description:messages,
                    duration:5
                })
            }else if(type===2){
                notification['info']({
                    message:'提示',
                    description:"系统暂无环境，请先在环境管理中新增环境",
                    duration:null
                })
            }else if(type===3){
                notification['error']({
                    message:title,
                    description:<pre>{messages}</pre>,
                    duration:5
                })
            }
            else{
                message.error(messages)
            }
        }
    },
    getUrlByLevel:(url:string,level:number)=>{
        let paths = (url||'').split('/')
        let temp = []
        for(let i=0;i<level;i++){
            temp.push(paths[i]||'')
        }
        return temp.join('/')
    },
    getQueryVariable:(variable:string,url:string)=>{
        const query = (url||'?').substring(1);
        const vars = query.split("&");
        for (let i=0;i<vars.length;i++) {
            let pair = vars[i].split("=");
            let params = [...pair]
            params.shift()
            if(pair[0] == variable){return params.join('=')}
        }
        return(false);
    }
}