import { utils, UUID, trim, _amosTool } from 'amos-tool';
import { isString } from 'util';
import SysConsts from 'amos-processor/lib/config/consts';

const num = 4;

export const extractLabel = (datas = [], label = 'label') => {
  return (datas || []).map(d => utils.isObject(d) ? d[label] : d);
};

export const extractSeries = (datas = [], value = 'value') => {
  return (datas || []).map(d => utils.isObject(d) ? d[value] : d);
};

export const parse2string = (obj) => {
  return utils.isEmpty(obj) ? '' : JSON.stringify(obj);
};

export const parse2object = (str) => {
  return utils.isEmpty(str) ? null : JSON.parse(str);
};

export  const deepClone = (obj) => {
  if (!obj) {
    return obj;
  }
  var str, newobj = obj.constructor === Array ? [] : {};
  if (typeof obj !== 'object'){
    return;
  } else if (window.JSON){
    str = JSON.stringify(obj), //序列化对象
    newobj = JSON.parse(str); //还原
  } else {//如果不支持以上方法
    for (let i in obj){
      newobj[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i];
    }
  }
  return newobj;
};

export const deepCopy = (source) => {
  return Object.assign({},source);
};

export const strRGB2object = (str) => {
  let rgb = str.split(',');
  let r = parseInt(rgb[0].split('(')[1]);
  let g = parseInt(rgb[1]);
  if (rgb.length > num){
    let b = parseInt(rgb[2]);
    let a = parseInt(rgb[3].split(')')[0]);
    return { r, g, b, a };
  } else {
    let b = parseInt(rgb[2].split(')')[0]);
    let a = 1;
    return { r, g, b, a };
  }
};

export const objRGB2str = (color) => {
  return `rgba(${color.r},${color.g},${color.b},${color.a ? color.a : 1})`;
};

export const offSet = (curEle) => {
  let totalLeft = null;
  let totalTop = null;
  let par = curEle.offsetParent;
    //首先把自己本身的相加
  totalLeft += curEle.offsetLeft;
  totalTop += curEle.offsetTop;
  //现在开始一级一级往上查找，只要没有遇到body，我们就把父级参照物的边框和偏移相加
  while (par){
    if (navigator.userAgent.indexOf('MSIE 8.0') === -1){
        //不是IE8我们才进行累加父级参照物的边框
      totalTop += par.clientTop;
      totalLeft += par.clientLeft;
    }
    //把父级参照物的偏移相加
    totalTop += par.offsetTop;
    totalLeft += par.offsetLeft;
    par = par.offsetParent;
  }
  return { left: totalLeft,top: totalTop };
};

export const downloadFile = (url, fileName) => {
  let aLink = document.createElement('a');
  let evt = document.createEvent('MouseEvent');
  evt.initEvent('click', false, false);
  aLink.download = fileName;
  aLink.href = url;
  aLink.dispatchEvent(evt);
  if (navigator.userAgent.indexOf('Firefox') >= 0) {
    aLink.click();//FF的支持,可能不需要
  }
};


const defaultLen = 16;

export const uuid = (len = defaultLen) => {
  return UUID.uuid(len);
};

/**
 * 浏览器类型
 */
export const browserType = function() {
  let userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  let isOpera = userAgent.indexOf('Opera') > -1; //判断是否Opera浏览器
  let isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 && !isOpera; //判断是否IE浏览器
  let isEdge = userAgent.indexOf('Windows NT 6.1; Trident/7.0;') > -1 && !isIE; //判断是否IE的Edge浏览器
  let isFF = userAgent.indexOf('Firefox') > -1; //判断是否Firefox浏览器
  let isSafari = userAgent.indexOf('Safari') > -1 && userAgent.indexOf('Chrome') === -1; //判断是否Safari浏览器
  let isChrome = userAgent.indexOf('Chrome') > -1 && userAgent.indexOf('Safari') > -1; //判断Chrome浏览器

  if (isIE) {
    let reIE = new RegExp('MSIE (\\d+\\.\\d+);');
    reIE.test(userAgent);
    let fIEVersion = parseFloat(RegExp['$1']);
    if (fIEVersion === 7)
    { return 'IE7';}
    else if (fIEVersion === 8)
    { return 'IE8';}
    else if (fIEVersion === 9)
    { return 'IE9';}
    else if (fIEVersion === 10)
    { return 'IE10';}
    else if (fIEVersion === 11)
    { return 'IE11';}
    else
    { return '0'; }//IE版本过低
  }//isIE end

  if (isFF) { return 'FF';}
  if (isOpera) { return 'Opera';}
  if (isSafari) { return 'Safari';}
  if (isChrome) { return 'Chrome';}
  if (isEdge) { return 'Edge';}
};

export const browserScrollWidth = function() {
  const type = browserType();
  const defaultWidth = 15;
  if (type === 'IE7') {
    return defaultWidth;
  } else if (type === 'IE7') {
    return defaultWidth;
  } else if (type === 'IE8') {
    return defaultWidth;
  } else if (type === 'IE9') {
    return defaultWidth;
  } else if (type === 'IE10') {
    return defaultWidth;
  } else if (type === 'IE11') {
    return defaultWidth;
  } else if (type === '0') {
    return defaultWidth;
  } else if (type === 'FF') {
    return defaultWidth;
  } else if (type === 'Opera') {
    return defaultWidth;
  } else if (type === 'Safari') {
    return defaultWidth;
  } else if (type === 'Chrome') {
    return 10;
  } else if (type === 'Edge') {
    return defaultWidth;
  }
};

export const filterList = function(list, searchValue, varName) {
  searchValue = trim(`${searchValue || ''}`);
  if (!searchValue) {
    return list;
  } else {
    return list.filter(e => e[varName].toLocaleUpperCase().indexOf(searchValue.toLocaleUpperCase()) > -1);
  }
};

export const scrollToBottom = function(dom) {
  dom.scrollTo = dom.scrollHeight;
};

export const convetStrToHtml = (str) => {
  if (isString(str)) {
    str = str.replace(/\ +/g, '&nbsp;&nbsp;');
    str = str.replace(/[\r\n]/g, '<br />');
    return str;
  }
  return str;
};
/**
 * 全屏
 * @param {*} element
 */
export const fullScreen = (element) => {
  let requestMethod = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullScreen;
  if (requestMethod) {
    requestMethod.call(element);
  } else if (typeof window.ActiveXObject !== 'undefined') {
    let wscript = new window.ActiveXObject('WScript.Shell');
    if (wscript !== null) {
      wscript.SendKeys('{F11}');
    }
  }
};
/**
 * 退出全屏
 * @param {*} element
 */
export const cancleFullScreen = () => {
  const element = document;
  let requestMethod = element.cancelFullScreen || element.webkitCancelFullScreen || element.mozCancelFullScreen || element.exitFullScreen;
  if (requestMethod) {
    requestMethod.call(element);
  } else if (typeof window.ActiveXObject !== 'undefined') {
    let wscript = new window.ActiveXObject('WScript.Shell');
    if (wscript !== null) {
      wscript.SendKeys('{F11}');
    }
  }
};

export const checkFullScreen = () => {
  let isFull = document.fullscreenEnabled || window.fullScreen || document.webkitIsFullScreen || document.msFullscreenEnabled;
  //to fix : false || undefined == undefined
  if (isFull === undefined) { isFull = false; }
  return isFull;
};

// const apiKey = SysConsts.api_key;
const token = SysConsts.token;

export const exportExcel = ({ url, method, body }, fileName) => {
  window.fetch(url, {
    method,
    headers: {
      'Accept': 'application/vnd.ms-excel',
      'Content-Type': 'application/json; charset=utf-8',
      'X-Access-Token': window.localStorage.getItem(token),
      'token': window.localStorage.getItem(token),
      'appKey': 'YH-PATROL',
      'product': 'YH-PATROL_WEB'
    },
    body: body ? JSON.stringify(body) : undefined
  }).then((e) => {
    e.blob().then((blob) => {
      const a = window.document.createElement('a');
      const downUrl = window.URL.createObjectURL(blob);
      a.href = downUrl;
      a.download = `${fileName}.xls`;
      a.click();
      window.URL.revokeObjectURL(downUrl);
    });
  }).catch((e) => {

  });
};
