import moment from 'moment'
import _ from 'lodash'
import constants from '@/utils/constants'

export const formatDate = (date, format = 'YYYY-MM-DD') => {
  return moment(date).format(format)
}

export const formatTableDate = (dateTime, format = 'YYYY-MM-DD HH:mm:ss') => {
  if (dateTime === 0) {
    return ''
  }
  return moment(new Date(dateTime * 1000)).format(format)
}

export const downLoad = (data, fileName) => {
  let blob = new Blob([data], {type: 'application/force-download'});
  let objectUrl = URL.createObjectURL(blob);
  let element = document.createElement('a');
  element.setAttribute('href', objectUrl);
  element.setAttribute('download', fileName);
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
}

export const getFileName = (type) => {
  return moment().format('YYYYMMDDHHmmss') + '.' + type
}

export const downLoadBase64 = (content, fileName) => {
  let base64ToBlob = function (code) {
    let parts = code.split(';base64,');
    let contentType = parts[0].split(':')[1];
    let raw = window.atob(parts[1]);
    let rawLength = raw.length;
    let uInt8Array = new Uint8Array(rawLength);
    for (let i = 0; i < rawLength; ++i) {
      uInt8Array[i] = raw.charCodeAt(i);
    }
    return new Blob([uInt8Array], {
      type: contentType
    });
  };
  let aLink = document.createElement('a');
  let blob = base64ToBlob(content);
  let evt = document.createEvent("HTMLEvents");
  evt.initEvent("click", true, true);
  aLink.download = fileName;
  aLink.href = URL.createObjectURL(blob);
  aLink.click();
}

export const downLoad2 = (url) => {
  const href = `/api/v2/common/download?url=${encodeURIComponent(url)}`
  const anchor = document.createElement('a');
  const fileName = 'download';
  if ('download' in anchor) {
    anchor.href = href;
    anchor.setAttribute("download", fileName);
    anchor.className = "download-js-link";
    anchor.innerHTML = "downloading...";
    anchor.style.display = "none";
    document.body.appendChild(anchor);
    setTimeout(function () {
      anchor.click();
      document.body.removeChild(anchor);
    }, 66);
    return true;
  }
}

export const findChildren = (arr, fn, result = []) => {
  arr.forEach(item => {
    if (item.children && item.children.length) {
      findChildren(item.children, fn, result)
    } else {
      if (fn(item)) {
        result.push(item)
      }
    }
  })
  return result
}

export const setChildren = (arr, key, value) => {
  arr.forEach(item => {
    if (item.children && item.children.length) {
      setChildren(item.children, key, value)
    } else {
      item[key] = value
    }
  })
  return arr
}

export const random = (min, max) => {
  return Math.floor(Math.random() * (max - min)) + min;
}

export const getRandomArrayElements = (arr, count) => {
  let shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
  if (min < 0) {
    min = 0
  }
  while (i-- > min) {
    index = Math.floor((i + 1) * Math.random());
    temp = shuffled[index];
    shuffled[index] = shuffled[i];
    shuffled[i] = temp;
  }
  return shuffled.slice(min);
}

export const getTreeDataList = (treeList, arr) => {
  for (let i = 0; i < treeList.length; i++) {
    arr.push(treeList[i])
    if (treeList[i].children && treeList[i].children.length) {
      getTreeDataList(treeList[i].children, arr)
    }
  }
  return arr
}

export const getTreeLastChildren = (treeList, arr) => {
  for (let i = 0; i < treeList.length; i++) {
    if (treeList[i].children && treeList[i].children.length) {
      getTreeLastChildren(treeList[i].children, arr)
    } else {
      arr.push(treeList[i])
    }
  }
  return arr
}

export const handleTree = (data) => {
  data.forEach(function (item) {
    delete item.children
  })
  let map = {}
  data.forEach(function (item) {
    map[item.id] = item
  })
  let val = []
  data.forEach(function (item) {
    let parent = map[item.parentId]
    if (parent) {
      (parent.children || (parent.children = [])).push(item)
    } else {
      val.push(item)
    }
  })
  return val
}

export const getTotalPage = (total, size) => {
  return Math.ceil(total / size)
}

export const findTreeEq = (treeList, key) => {
  const dataList = getTreeDataList(treeList, [])
  const parentId = _.uniq(dataList.map(item => item.parentId))
  let dataObj = {}
  if (dataList.length === 0) {
    return '请添加选项'
  }
  if (!dataList.map(item => item.name).every(item => !!item)) {
    return '选项不能为空'
  }
  parentId.map(id => {
    dataObj[id] = dataList.filter(item => item.parentId === id).map(item => item.name)
  })
  for (let data in dataObj) {
    if (dataObj[data].length !== _.uniq(dataObj[data]).length) {
      let name = ''
      if (parseInt(data) === 0) {
        name = '主'
      } else {
        name = dataList.find(item => item.id === parseInt(data)).name
      }
      return `${name}节点名称重复`
    }
  }
  return false;
}

export const renderSize = (value) => {
  if (null === value || value === '') {
    return "0 Bytes";
  }
  const unitArr = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  let index = 0;
  let srcSize = parseFloat(value);
  index = Math.floor(Math.log(srcSize) / Math.log(1024));
  let size = srcSize / Math.pow(1024, index);
  size = size.toFixed(2);
  return size + unitArr[index];
}

export const getPatentCountry = (patentNo) => {
  return patentNo.substr(0, 2)
}