import axios from 'axios'
import store from '../store'


const instance = axios.create({
    baseURL: process.env.VUE_APP_API_URL,
    timeout: 5000,
    withCredentials: true
})

instance.interceptors.request.use(
    config => {
        // if(config.data.showloading || config.params.showloading){
        //     console.log('showloading')
        // }
        if (sessionStorage.getItem('token')) {  // 判斷是否存在token，如果存在的話，則每個http header都加上token
            config.headers.Authorization = `${sessionStorage.getItem('token')}`;
        }


        if (config.method === 'post') {
            
            config.data = {        
              uid: sessionStorage.getItem('uid'),
              ...config.data
            }

            // if(config.data.showloading){
            //     console.log('showloading')
            //     delete config.data.showloading
            // }

        } else if (config.method === 'get') {
        
            config.params = {        
                uid: sessionStorage.getItem('uid'),
                ...config.params
            }

            // if(config.params.showloading){
            //     console.log('showloading')
            //     delete config.params.showloading
            // }

        }

        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

instance.interceptors.response.use(
    response => {
        refreshToken(response)

        return response
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 返回 401 清除token資訊並跳轉到登入頁面
                    store.commit(types.LOGOUT);
                    router.replace({
                        path: 'login',
                        query: {redirect: router.currentRoute.fullPath}
                    })
            }
        }
        return Promise.reject(error.response.data)   // 返回介面返回的錯誤資訊
});

function refreshToken(response) {
    let token = response.headers.authorization
    if (token) {
        console.log('change token')
        sessionStorage.setItem('token', token);
    }
}

export default async function ajax( url , data={} , type='GET' ){
    
    let result
    if(type.toUpperCase() === 'GET' ){
        let queryStr = ''

        Object.keys(data).forEach(key=>{
            queryStr +=  key + '=' + data[key] + '&'
        })

        if(queryStr !== ''){
            queryStr = queryStr.substring(0,queryStr.lastIndexOf('&'))
            url += '?' + queryStr
        }

        result = await instance.get(url)
    }else{

        result = await instance.post(url,data)
    }
    return result.data
}

/*生成指定長度的隨機數*/
function randomCode(length) {
    let chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    let result = "";
    for (let i = 0; i < length; i++) {
        let index = Math.ceil(Math.random() * 9);
        result += chars[index];
    }
    return result;
}