import request from '../utils/request'
import { hashcode } from '../utils/baseUtils'

// 防抖控制
function debounce(option) {
    return new Promise(function (resolve, reject) {
        let timeKey = hashcode(option);
        window['key-' + timeKey] && window.clearTimeout(window['key-' + timeKey]);
        window['key-' + timeKey] = window.setTimeout(() => {
            return resolve();
        }, 200);
    })
}
export function fetch(option) {
    let { url, method, body, timeout, allow } = option;
    const token = window.sessionStorage.getItem("token");
    return debounce({ url, method, body }).then(() => {
        // 除非特殊许可，Token不存在时不发送请求
        if(token || allow) {
            let opt = {
                method: method || 'POST',
            };
            if(method === 'GET') {
                opt.headers = {
                    token: token,
                    'Content-Type': 'application/json'
                }
                if (body) {  
                    let paramsArray = [];  
                    //拼接参数  
                    Object.keys(body).forEach(key => paramsArray.push(key + '=' + body[key]))  
                    if (url.search(/\?/) === -1) {  
                        url += '?' + paramsArray.join('&')  
                    } else {  
                        url += '&' + paramsArray.join('&')  
                    }  
                }
            }else {
                opt.headers = {
                    'Content-Type': 'application/json'
                }
                opt.body = JSON.stringify(body);

                if(!!token) {
                    opt.headers.token = token
                }
            }

            return request(url, opt, timeout);
        }else {
            // 使用一个空的Promise阻止后续链式方法的调用
            return new Promise(() => {});
        }
    })
}