
import axios, { AxiosInstance } from "axios"
import {token,userMsg} from '@/util/userInfoUtils'
import router from '@/router'
// import Async from 'async'
import { Toast } from 'vant'
// const url = {
//     development: 'http://172.16.101.135:8001',
//     test: 'http://172.16.101.136:8001',
//     production: ''
// }

async function logoutUser(){
    token.clearToken()
    userMsg.clearUserMsg()
}

export class Service {
    public service: AxiosInstance;

    constructor() {
        this.service = axios.create({
            baseURL:'/proxyApi',
            timeout: 15000,
        })
        const get = this.service.get
        const post = this.service.post
        const resolveData = async (ret: any) => {
            if (ret.code === 200){
                if(ret.data){
                    return ret.data;
                }
                return ret
            }else {

                if(ret.code === 401){
                    await logoutUser().then(()=>{
                        router.push({name:'Login'})
                    })
                }
                Toast.fail(typeof ret.data === "string" ? ret.data : ret.message)
                throw new Error(ret.message)
            }
        }
        this.service.get = (...res) => get(...res).then(ret => resolveData(ret.data)).catch(err => {
            resolveData(err.response.data)
        })
        this.service.post = (...res) => post(...res).then(ret => resolveData(ret.data)).catch(err => {
          resolveData(err.response.data)
        });
    }

}