import axios from 'axios'
import qs from "qs";
import {ElMessage} from 'element-plus'
import { useFiltersStore } from '@/store/filter.js'
import { webSiteFlagRelation, webSiteLanguageRelation } from "../utils/common";

const timeout = 10000

const instance = axios.create({
    baseURL: apiUrl,
    // baseURL: 'http://localhost:8001/',
    timeout: timeout
})

export const get = async (url, data = {}) => {
    let res = await initRequestHeader('get', url, data);
    const filtersStore = useFiltersStore()
    data = res.data;
    return new Promise((resolve, reject) => {
        instance.get(res.url, { params: data, headers: res.headers }).then((response) => {
            if (response.data.state == 266) {
                // filtersStore.setLoginStatus(false);
                // filtersStore.setToken('');
                // filtersStore.setRefreshToken('')
                // // ElMessage.warning('请重新登录')
                // navigateTo('/login')
            } else {
                resolve(response.data)
            }
        }, err => {
            showMessage({
                message: err.message,
                type: 'error'
            })
            reject(err)
        })
    })
}

export const post = async (url, data = {}, timeout,type = 'urlencoded') => {
    let res = await initRequestHeader('post', url, data, type);
    return new Promise((resolve, reject) => {
        instance.post(res.url, res.data,{
            headers: res.headers,
            timeout:timeout
        } ).then((response) => {
            resolve(response.data)
        }, err => {
            console.log(err)
            if(err.code == 'ECONNABORTED'){
                showMessage({
                    message: 'The request timed out. Please try again later',
                    type: 'error'
                })
            } else {
                showMessage({
                    message: err.message,
                    type: 'error'
                })
            }
            reject(err)
        }).finally(()=>{
            resolve()
        })
    })
}

// const token = useCookie('token')

/**
 * 初始化请求头和数据
 * @zjf-2020-12-25
 */
const initRequestHeader = async (method, url, data = {}, type = 'urlencoded') => {
    let result = {};
    const config = useRuntimeConfig()
    let headers = {};
    const filtersStore = useFiltersStore()
    //用户登录状态下，每次更新refresh_token58分钟之后需要更新access_token
    if (filtersStore.getToken) {
        let cur_time = new Date().getTime();
        if (cur_time - filtersStore.getTime * 1 > 58 * 60 * 1000) {

            let param = new FormData();
            param.append('grant_type', 'refresh_token');
            param.append('refresh_token', filtersStore.getRefreshToken);
            await instance.post('v3/frontLogin/oauth/token', param, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'Authorization': 'Basic VVcxS2FsSnVTblppYmxFOTpVMjFHTWxsVlFrUmlNMEkxVlcxc2JtRklVa0ZWTW5oMldrYzVkUT09'
                }
            }).then((response) => {
                if (response.data.state == 200) {
                    filtersStore.setToken(response.data.data.access_token);
                    filtersStore.setTime(new Date().getTime().toString());//存储refresh_token更新时间
                }
            }, err => {
                console.log('更新access_token出错：', err);
            })
        }
    }

    if (method == 'post') {
        if (type == 'urlencoded') {
            headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
            data = qs.stringify(data);
        } else if (type == 'json') {
            headers = { 'Content-Type': 'application/json' };
            data = JSON.parse(JSON.stringify(data));
        } else if (type == 'form') {//form-data
            headers = { 'Content-Type': 'multipart/form-data' };
            let tmp_data = new FormData();
            Object.keys(data).forEach((item) => {
                tmp_data.append(item, data[item])
            });
            data = tmp_data;
        }
    }

    if (url.indexOf('frontLogin/oauth/token') > -1) {
        headers.Authorization = 'Basic VVcxS2FsSnVTblppYmxFOTpVMjFHTWxsVlFrUmlNMEkxVlcxc2JtRklVa0ZWTW5oMldrYzVkUT09';
    } else {
        let token = filtersStore.getToken;
        headers.Authorization = 'Bearer ' + token;
    }

    result = { url, data, headers: {...headers, 'Web-Site': webSiteFlagRelation[config.public.appType], Language: webSiteLanguageRelation[config.public.appType]} };
    return result;
}
