import request from '../utils/request'
import deepAssign from '../utils/deepAssign'
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, headers, body, timeout, allow, requestType, fileName } = 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 = deepAssign({
                    token: token,
                    'Content-Type': 'application/json'
                }, headers);
                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 = deepAssign({
                    token: token,
                    'Content-Type': 'application/json'
                }, headers);
                opt.body = JSON.stringify(body);

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

            return request(url, opt, timeout).then(data=> {
                if(!data) {
                    throw new Error('请求异常');
                }
                return data;
            }).then(data => {
                if(requestType === 'file') {
                    let blob = data.blob().then(blob => {
                        if (window.navigator.msSaveOrOpenBlob) {
                            navigator.msSaveBlob(blob);  //兼容ie10
                        } else {
                            var a = document.createElement('a');
                            document.body.appendChild(a) //兼容火狐，将a标签添加到body当中
                            var url = window.URL.createObjectURL(blob);   // 获取 blob 本地文件连接 (blob 为纯二进制对象，不能够直接保存到磁盘上)
                            a.href = url;
                            a.download = fileName;
                            a.target='_blank'  // a标签增加target属性
                            a.click();
                            a.remove()  //移除a标签
                            window.URL.revokeObjectURL(url);
                        }
                    });
                    return blob;
                }
                return data.json();
            });
        }else {
            // 使用一个空的Promise阻止后续链式方法的调用
            return new Promise(() => {});
        }
    })
}