import { getValue } from '@/utils/common';
import Axios from 'axios'
Axios.defaults.baseURL = 'https://case.sy-my.net/beelink/public/home/';
if(getValue("time") < (new Date().getTime() - 12 * 60 * 60 * 1000)){
    localStorage.removeItem("token")
    localStorage.removeItem("time")
}
Axios.defaults.headers.common['Authorization'] = "Bearer " + getValue("token");
Axios.defaults.headers.common['Language'] = !getValue("Lanvuage") ? 'zh' : getValue("Lanvuage");
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

interface Data {
    [url: string]: {
        data: any;
        time: number;
    };
}

class Huancun {
    data: Data = {}
    has(url: string){
        // console.log(this.data)
        // if(!this.data[url]){
        //     return false;
        // }
        // console.log(new Date().getTime() - 60000 < this.data[url].time,"time")
        // if(this.data[url] && new Date().getTime() - 60000 < this.data[url].time){
        //     return this.data[url]
        // }else {
        //     return false
        // }
        return false;
    }
    save(url: string,data: any){
        this.data[url] = {data,time: new Date().getTime()}
    }

}

const huancun =  new Huancun()

Axios.interceptors.response.use((res)=>{
    console.log(res,"data")
    if(res.config.url){
        huancun.save(res.config.url,res);
    }
    return res;

})

const axios = Axios.create({
    adapter: config =>{
        // 判断是否存在mock数据
        let has: any;
        if(config.url){
            has = huancun.has(config.url)
        }
        console.log(has,"has")
        // 调用默认请求接口, 发送正常请求及返回
        if(!has){
        
            // 删除配置中的 adapter, 使用默认值
            delete config.adapter
            
            // 通过配置发起请求
            return Axios(config)
            
        }
        
        // 模拟服务，返回mock数据
        return new Promise((res) =>{
            
            
            console.log(has.data)
            
            // 调用响应函数
            res(has.data)
             
        })
        
    }
    
})


export default axios