/*
 * @Author: xujh
 * @Email: xujh@hxmec.com
 * @Date: 2021-11-15 13:49:47
 * @Last Modified by: xujh
 * @Last Modified time: 2021-11-15 13:49:47
 * @Description: 只用来处理富文本上传图片
 */

function getError(action, option, xhr) {
    let msg;
    if (xhr.response) {
        msg = `${xhr.response.error || xhr.response}`;
    } else if (xhr.responseText) {
        msg = `${xhr.responseText}`;
    } else {
        msg = `fail to post ${action} ${xhr.status}`;
    }
  
    const err = new Error(msg);
    err.status = xhr.status;
    err.method = 'post';
    err.url = action;
    return err;
}
  
function getBody(xhr) {
    const text = xhr.responseText || xhr.response;
    if (!text) {
        return text;
    }
  
    try {
        return JSON.parse(text);
    } catch (e) {
        return text;
    }
}
function httpUpload(option) {
    const xhr = new XMLHttpRequest();
    const { url } = option;
    const formData = new FormData();

    formData.append(option.filename, option.file);
    xhr.onerror = function error(e) {
        option.onError(e);
    };
    
    // eslint-disable-next-line consistent-return
    xhr.onload = function onload() {
        if (xhr.status < 200 || xhr.status >= 300) {
            return option.onError(getError(url, option, xhr));
        }

        option.onSuccess(getBody(xhr));
    };
    xhr.open('post', url, true);
    
    if (option.withCredentials && 'withCredentials' in xhr) {
        xhr.withCredentials = true;
    }

    const headers = option.headers || {};

    // eslint-disable-next-line no-restricted-syntax
    for (const item in headers) {
        // eslint-disable-next-line no-prototype-builtins
        if (headers.hasOwnProperty(item) && headers[item] !== null) {
            xhr.setRequestHeader(item, headers[item]);
        }
    }
    xhr.send(formData);
    return xhr;
}
export default httpUpload;
