import axios from 'axios'
import Cookies from 'js-cookie';

export const instance = axios.create({
    baseURL: import.meta.env.VITE_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')) {
            config.headers.Authorization = `${sessionStorage.getItem('token')}`;
        }

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

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

        } else if (config.method === 'get') {
            // if (sessionStorage.getItem('uid')) {
                config.params = {
                    lang: Cookies.get('lang'),
                    ...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) {
        sessionStorage.setItem('AgentToken', token);
    }
}

export default async function ajax(url, type = 'GET', data = {}, headers = {}) {

    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, { headers })
    } else {

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

export async function uploadFile(url, data) {
    let res = await axios({
        method: 'post',
        url: import.meta.env.VITE_APP_API_URL + url,
        data: data,
        headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': sessionStorage.getItem('token')
        }
    })

    return res.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;
}
