/**
 * 数据请求相关公共方法
 */
import amosRequest, { singleFetch } from 'amos-processor/lib/fetch/amosRequest';
import { AmosFetch } from 'amos-processor/lib/fetch';
import formatUrl from 'amos-processor/lib/utils/urlFormat';
import payload from './payload';
import { urlEncode, trimObjectData } from './tools';
import globalConfig from './global';

/**
 * 获取平台提供的请求头对象信息
 */
export const compleHeaders = () => {
  return {
    ...globalConfig.getRequestHeader()
  };
};
/**
 * Url拼接（IP:port + applicationName + url）
 * @param {*} uri
 */
export const completePrefix = (uri) => (...args) => {
  if (args.length === 1) {
    return `${globalConfig.getURI(uri)}${args[0]}`;
  } else {
    return `${globalConfig.getURI(uri)}${args[0]}${args[0] ? '/' : ''}${args[1]}`;
  }
};

/**
 * 根据url获取文件流
 * @param {string} url
 */
export const getFileBoleAction = (url) => {
  return AmosFetch.get(url).then(res => {
    return res.blob();
  });
};

/**
 * 分页URL拼接(使用与江西电建等项目)
 * @param {*} param
 */
export const formatPageUrl = ({ url, page, size, filter, params }) => {
  let newUrl = formatUrl(url, params || {});
  const urlFilter = urlEncode(filter);
  if (page !== undefined && size !== undefined) {
    newUrl = `${newUrl}${newUrl.includes('?') ? '&' : '?'}pageNumber=${page}&pageSize=${size}&isAll=0${urlFilter}`;
  } else {
    newUrl = `${newUrl}${newUrl.includes('?') ? '&' : '?'}&isAll=1${urlFilter}`;
  }
  return newUrl;
};
/**
 * 分页URL拼接(标准拼接)
 * @param {*} param
 */
export const buildPageUrl = ({ url, page, size, filter, params }) => {
  let newUrl = formatUrl(url, params || {});
  const urlFilter = urlEncode(filter);
  if (page !== undefined && size !== undefined) {
    newUrl = `${newUrl}${newUrl.includes('?') ? '&' : '?'}current=${page}&size=${size}${urlFilter}`;
  }
  return newUrl;
};

/**
 * 构建分页(后端分页参数pageNum、pageSize)
 * @param {*} param
 */
export const buildPageable = ({ url, page, size, filter, params }) => {
  let newUrl = formatUrl(url, params || {});
  const urlFilter = urlEncode(filter);
  if (page !== undefined && size !== undefined) {
    newUrl = `${newUrl}${newUrl.includes('?') ? '&' : '?'}pageNum=${page}&pageSize=${size}${urlFilter}`;
  }
  return newUrl;
};

/**
 * URL拼接（对象转字符串URL参数）
 * @param {*} param
 */
export const formatObjUrl = ({ url, filter, params })  => {
  let newUrl = formatUrl(url, params || {});
  let urlFilter = urlEncode(trimObjectData(filter || {}));
  if (urlFilter && urlFilter.startsWith('&')) {
    urlFilter = urlFilter.substring(1);
  }
  newUrl = `${newUrl}${newUrl.includes('?') ? '&' : '?'}${urlFilter}`;
  return  newUrl;
};

/**
 * 删除全局变量requests中的地址
 * @param {*} url
 * @param {*} method
 */
const delRequest = (url, method) => {
  if (window.requests && window.requests.length > 0) {
    window.requests = window.requests.filter(e => e.url !== url && e.method !== method);
  }
};

const defaultTimeout = 10000000; // 默认超时时间

export function commonInterfaceGet(url,header) {
  header.token = compleHeaders().token;
  return amosRequest(url, {
    timeout: defaultTimeout,
    method: 'GET',
    headers: header,
    reject(error){
      delRequest(url, 'GET');
    }
  }).then(data => payload(data));
}
/**
 * 公共GET请求
 * @param {*} url
 */
export function commonGet(url) {
  return amosRequest(url, {
    timeout: defaultTimeout,
    method: 'GET',
    headers: compleHeaders(),
    reject(error){
      delRequest(url, 'GET');
    }
  }).then(data => payload(data));
}
/**
 * 公共POST请求
 * @param {*} url
 * @param {*} data body对象
 */
export function commonPost(url, data, isFormData = false) {
  return amosRequest(url, {
    timeout: defaultTimeout,
    method: 'POST',
    headers: compleHeaders(),
    body: data,
    isFormData,
    reject(error){
      delRequest(url, 'POST');
    }
  }).then(res => payload(res));
}
/**
 * 公共PUT请求
 * @param {*} url
 * @param {*} data body对象
 */
export function commonPut(url, data) {
  return amosRequest(url, {
    timeout: defaultTimeout,
    method: 'PUT',
    headers: compleHeaders(),
    body: data,
    reject(error){
      delRequest(url, 'PUT');
    }
  }).then(res => payload(res));
}
/**
 * 公共DELETE请求
 * @param {*} url
 * @param {*} data body对象
 */
export function commonDelete(url, data) {
  return amosRequest(url, {
    timeout: defaultTimeout,
    method: 'DELETE',
    headers: compleHeaders(),
    body: data
  }).then(res => payload(res));
}
/**
 * 接口请求下载文件(一般用于post请求下载文件)
 * @param {*} param
 */
export const readFile = ({ url, data, fileName, method = 'GET', isDownload }) => {
  return AmosFetch[method.toLocaleLowerCase()](url,
    {
      params: {
        headers: {
          'Accept': 'application/json, */*',
          ...compleHeaders()
        },
        ...method.toLocaleLowerCase() !== 'get' ? {
          body: JSON.stringify(data || {})
        } : {}
      }
    }
  ).then((response) => {
    return new Promise((resolve, reject) => {
      if (response.ok) {
        response.blob().then((blob) => {
          const downUrl = window.URL.createObjectURL(blob);
          if (isDownload) {
            const a = window.document.createElement('a');
            const filename = fileName || response.headers.get('Content-Disposition').split('filename=')[1].split('.');
            a.href = downUrl;
            a.download = `${decodeURI(filename[0])}.${filename[1]}`;
            a.click();
            window.URL.revokeObjectURL(downUrl);
          }
          resolve(downUrl);
        }).catch(d => reject('读取失败'));
        return { state: 1 };
      } else {
        reject('读取失败');
      }
    });
  });
};
/**
 * 文件下载
 * @param {*} param
 */
export const fileDownload = ({ url, data, fileName, method = 'GET' }) => {
  return AmosFetch[method.toLocaleLowerCase()](url,
    {
      params: {
        headers: {
          'Accept': 'application/json, */*',
          ...compleHeaders()
        },
        ...method.toLocaleLowerCase() !== 'get' ? {
          body: JSON.stringify(data || {})
        } : {}
      }
    }
  ).then((response) => {
    if (response.ok) {
      response.blob().then((blob) => {
        const a = window.document.createElement('a');
        const downUrl = window.URL.createObjectURL(blob);// 获取 blob 本地文件连接 (blob 为纯二进制对象，不能够直接保存到磁盘上)
        const filename = (fileName && fileName.split('.')) || response.headers.get('Content-Disposition').split('filename=')[1].split('.');
        a.href = downUrl;
        a.download = `${decodeURIComponent(filename[0])}.${filename[1]}`;
        a.click();
        window.URL.revokeObjectURL(downUrl);
      });
      return { state: 1 };
    } else {
      throw new Error('');
    }
  });
};
export const downLoadZIP = ({ url, data, fileName, method = 'POST' }) => {
  return AmosFetch[method.toLocaleLowerCase()](url,
    {
      params: {
        headers: {
          'Accept': 'application/json, */*',
          ...compleHeaders()
        },
        ...method.toLocaleLowerCase() !== 'get' ? {
          body: JSON.stringify(data || {})
        } : {}
      }
    }
  ).then((response) => {
    if (response.ok) {
      response.blob().then((blob) => {
        const a = window.document.createElement('a');
        const downUrl = window.URL.createObjectURL(blob);// 获取 blob 本地文件连接 (blob 为纯二进制对象，不能够直接保存到磁盘上)
        a.href = downUrl;
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(downUrl);
      });
      return { state: 1 };
    } else {
      throw new Error('');
    }
  });
};

export { amosRequest, formatUrl, singleFetch };
