import Handsontable from "handsontable-pro"
import localMenusList from '@/data/menus'

const tools = {}

let arrX = []
let arrY = []
tools.getPointDetails = (arr) => {
  arr.map(item => {
    if (item.PointList && item.PointList.length) {
      item.PointList.map(em => {
        arrX.push(em.X)
        arrY.push(em.Y)
      })
    }
  })
}
/**
 *
 * @param {*} obj 将point标签的x,y进行比对
 * @return object 返回数组，其中包括最大值最小值X,Y
 */
tools.getPoint = function (obj) {
  arrX = []
  arrY = []
  for (let i in obj) {
    tools.getPointDetails(obj[i])
  }
  let maxX = Math.max.apply(null, arrX)
  let minX = Math.min.apply(null, arrX)
  let maxY = Math.max.apply(null, arrY)
  let minY = Math.min.apply(null, arrY)
  let data = {
    maxX,
    minX,
    maxY,
    minY
  }
  return data
}

/**
 *
 * @param {*} array  比较数组1
 * @param {*} array2 比较数组2
 *
 * 返回两个数组中不同的元素
 */
tools.compareArr = function (array, array2) {
  var arr3 = [];
  for (key in array) {
    var stra = array[key];
    var count = 0;
    for (var j = 0; j < array2.length; j++) {
      var strb = array2[j];
      if (stra == strb) {
        count++;
      }
    }
    if (count === 0) { //表示数组1的这个值没有重复的，放到arr3列表中
      arr3.push(stra);
    }
  }
  return arr3;
}

/**
 *
 * @param {*} arr 需要改变的数组
 * @param {*} k   其中Y值需要变换的倍数
 * @param {*} name arr中的key值
 *
 * 返回arr map 后arr[mapIndex]name * k 的数组
 */
tools.changeMap = function (arr, k, name) {
  let data = arr.map(items => {
    if (items[name] && items[name].length) {
      items[name].map(children => {
        if (Array.isArray(children)) {
          return children.map(res => {
            res.Y = res.Y * k
            return res
          })
        } else {
          children.Y = children.Y * k
          return children
        }
      })
    }
  })
  return data
}

tools.getMouseCanvas = function (view, e) {
  let bbox = view.canvasView.getBoundingClientRect();
  let x = e.clientX - bbox.left,
    y = e.clientY - bbox.top;
  return view.mapToScene({
    x: x,
    y: y
  });
}

/**
 *
 * @param {*} view graphy class
 * @param {*} e    mouse元素e
 */
tools.mouseInElement = function (view, e, type) {
  let mouse = tools.getMouseCanvas(view, e),
    falg = false,
    items = view.scene.root.children,
    i = 0,
    t = type || 3;
  for (; i < items.length; i++) {
    if (items[i].type == t) {
      if (items[i].contains(mouse)) {
        falg = true
        break
      }
    }
  }
  return {
    falg,
    item: items[i] || [],
    index: i
  }
}

/**
 *
 * @param {graphy中的所有children} items
 * @param {类型} type
 * @param {list} codes
 * @param {item中的code} code
 */
tools.clear = function (items, type, codes, code) {
  let indexArr = [];
  if (items && items.length) {
    let i = 0;
    for (i; i < items.length; i++) {
      let j = 0;
      for (j; j < codes.length; j++) {
        if (items[i][type] = type && items[i][code] == codes[j][code]) {
          indexArr.push(i)
        }
      }
    }
  }
  return indexArr
}

tools.getText = function (arr, name) {
  let text = '';
  if (arr && arr.length) {
    arr.map(item => {
      text += (!!text ? '、' : '') + item[name]
    })
  }
  return text
}

tools.cutString = function (string, num, text) {
  return string.substring(0, num) + '...' + text
}

tools.deepCopy = function (obj) {
  var out = [],
    i = 0,
    len = obj.length;
  for (; i < len; i++) {
    if (obj[i] instanceof Array) {
      out[i] = tools.deepCopy(obj[i]);
    } else out[i] = obj[i];
  }
  return out;
}

tools.copyArr = (source) => {
  if (!source || typeof source !== 'object') {
    throw new Error('error arguments', 'shallowClone');
  }
  var targetObj = source.constructor === Array ? [] : {};
  for (var keys in source) {
    if (source.hasOwnProperty(keys)) {
      if (source[keys] && typeof source[keys] === 'object') {
        targetObj[keys] = source[keys].constructor === Array ? [] : {};
        targetObj[keys] = tools.copyArr(source[keys]);
      } else {
        targetObj[keys] = source[keys];
      }
    }
  }
  return targetObj;
}

tools.deepCopyObj = function (v) {
  var o = v.constructor === Array ? [] : {};
  for (var key in v) {
    o[key] = typeof v[key] === 'Object' ? tools.deepCopyObj(v[key]) : v[key];
  }

  return o;
}

tools.deepClone = (obj) => {
  var proto = Object.getPrototypeOf(obj);
  return Object.assign({}, Object.create(proto), obj);
}

//hansontable插件的修改
tools.customDropdownRenderer = function (
  instance,
  td,
  row,
  col,
  prop,
  value,
  cellProperties
) {
  var selectedId;
  var optionsList = cellProperties.chosenOptions.data;
  if (
    typeof optionsList === "undefined" ||
    typeof optionsList.length === "undefined" ||
    !optionsList.length
  ) {
    Handsontable.renderers.TextRenderer(
      instance,
      td,
      row,
      col,
      prop,
      value,
      cellProperties
    );
    return td;
  }
  var values = (value + "").split(",");
  value = [];
  for (var index = 0; index < optionsList.length; index++) {
    if (optionsList[index].content && optionsList[index].content.length) {
      for (let i = 0; i < optionsList[index].content.length; i++) {
        if (
          optionsList[index].content[i] &&
          optionsList[index].content[i].length
        ) {
          for (let j = 0; j < optionsList[index].content[i].length; j++) {
            if (
              values.indexOf(
                optionsList[index].content[i].content[j].Code + ""
              ) > -1
            ) {
              selectedId = optionsList[index].content[i].content[j].Code;
              value.push(optionsList[index].content[i].content[j].Name);
            }
          }
        } else {
          if (
            values.indexOf(optionsList[index].content[i].Code + "") > -1
          ) {
            selectedId = optionsList[index].content[i].Code;
            value.push(optionsList[index].content[i].Name);
          }
        }
      }
    } else {
      if (values.indexOf(optionsList[index].Code + "") > -1) {
        selectedId = optionsList[index].Code;
        value.push(optionsList[index].Name);
      }
    }
  }
  value = value.join(", ");
  Handsontable.renderers.TextRenderer(
    instance,
    td,
    row,
    col,
    prop,
    value,
    cellProperties
  );
  return td;
}

//hansontable插件的修改
tools.multipleDropdownRenderer = function (
  instance,
  td,
  row,
  col,
  prop,
  value,
  cellProperties
) {
  var selectedId;
  var optionsList = cellProperties.chosenOptions;
  if (
    typeof optionsList === "undefined" ||
    typeof optionsList.length === "undefined" ||
    !optionsList.length
  ) {
    Handsontable.renderers.TextRenderer(
      instance,
      td,
      row,
      col,
      prop,
      value,
      cellProperties
    );
    return td;
  }
  try {
    var values = value;
    let text = [];
    for (var index = 0; index < optionsList.length; index++) {
      if (optionsList[index].content && optionsList[index].content.length) {
        for (let i = 0; i < optionsList[index].content.length; i++) {
          if (
            optionsList[index].content[i] &&
            optionsList[index].content[i].length
          ) {
            for (let j = 0; j < optionsList[index].content[i].length; j++) {
              if (
                values.findIndex((val) => {
                  return val == optionsList[index].content[i].content[j].Code + ""
                }) > -1
              ) {
                selectedId = optionsList[index].content[i].content[j].Code;
                text.push(optionsList[index].content[i].content[j].Name);
              }
            }
          } else {
            if (
              values.findIndex((val) => { return val == optionsList[index].content[i].Code + "" }) > -1
            ) {
              selectedId = optionsList[index].content[i].Code;
              text.push(optionsList[index].content[i].Name);
            }
          }
        }
      } else {
        if (values.findIndex((val) => { return val == optionsList[index].Code + "" }) > -1) {
          selectedId = optionsList[index].Code;
          text.push(optionsList[index].Name);
        }
      }
    }
    text = text.join(",");
    Handsontable.renderers.TextRenderer(
      instance,
      td,
      row,
      col,
      prop,
      text,
      cellProperties
    );
    return td;
  } catch (e) {
    Handsontable.renderers.TextRenderer(
      instance,
      td,
      row,
      col,
      prop,
      "",
      cellProperties
    );
    return td;
  }
}


//hansontable插件查看详情
tools.lookDetails = function (instance, td, row, col, prop, value, cellProperties) {
  td.style.color = "#409EFF";
  td.style.cursor = "pointer";
  if (!!value) {
    if (typeof (value) == 'object') {
      td.innerHTML = "已有值，查看";
    } else {
      td.innerHTML = value
    }
  } else {
    td.innerHTML = "查看详情";
  }
  return td;
}

//是否关联
tools.hasRelation = function (instance, td, row, col, prop, value, cellProperties) {
  if (value) {
    td.innerHTML = "已关联";
  } else {
    td.innerHTML = "未关联";
  }
  return td;
}

//关联的资产
tools.LinkEquipLocalName = function (instance, td, row, col, prop, value, cellProperties) {
  if (value) {
    td.innerHTML = value == 'null' ? '' : value;
  } else {
    let html = instance.getDataAtRowProp(row, 'linkEquipName');
    td.innerHTML = html == 'null' ? '' : html;
  }
  return td;
}

tools.num = function (instance, td, row, col, prop, value, cellProperties) {
  td.style.color = "#409EFF";
  td.style.cursor = "pointer";
  td.innerHTML = value;
  return td;
}

tools.setItem = (key, value) => {
  if (typeof value == 'string') {
    localStorage.setItem(key, value);
  } else {
    localStorage.setItem(key, JSON.stringify(value));
  }
}

tools.getItem = (key) => {
  const re = /^\[|\{|\}|\]$/g //判断字符中是否有[]{}
  let getIt = localStorage.getItem(key)
  if (re.test(getIt)) {
    return JSON.parse(getIt)
  } else {
    return getIt
  }
}

tools.removeItem = (key) => {
  localStorage.removeItem(key)
}

//取两个数组的差值
tools.differenceArr = (a, b) => {
  return a.concat(b).filter(v => !a.includes(v) || !b.includes(v))
}

//取两个数组的相同值
tools.sameArr = (a, b) => {
  return a.filter(v => b.includes(v))
}

tools.sortArr = (arr, key, sequence) => {
  function compare(property) {
    return function (a, b) {
      var value1 = a[property];
      var value2 = b[property];
      if (sequence) {
        return value1 - value2;
      } else {
        return value2 - value1
      }
    }
  }

  return arr.sort(compare(key))
}

tools.pagination = (pageNo, pageSize, array) => {
  let offset = (pageNo - 1) * pageSize;
  return offset + pageSize >= array.length ?
    array.slice(offset, array.length) :
    array.slice(offset, offset + pageSize);
}

tools.getSameItems = (arr1, key1, arr2, key2) => {
  let data = []
  arr1.map(item => {
    arr2.map(child => {
      if (item[key1] == child[key2]) {
        data.push(item)
      }
    })
  })
  return data
}

tools.isIn = (x, y, json) => {
  let nCross = 0,
    point = typeof (x) == 'object' ? [x.x, x.y] : [x, y],
    APoints = json,
    length = APoints.length,
    p1, p2, i, xinters;
  p1 = APoints[0];
  for (i = 1; i <= length; i++) {
    p2 = APoints[i % length];
    if (
      point[0] > Math.min(p1[0], p2[0]) &&
      point[0] <= Math.max(p1[0], p2[0])
    ) {
      if (point[1] <= Math.max(p1[1], p2[1])) {
        if (p1[0] != p2[0]) {
          //计算位置信息
          xinters = (point[0] - p1[0]) * (p2[1] - p1[1]) / (p2[0] - p1[0]) + p1[1];
          if (p1[1] == p2[1] || point[1] <= xinters) {
            nCross++
          }
        }
      }
    }
    p1 = p2;
  }
  if (nCross % 2 == 0) {
    return false
  } else {
    return true
  }

}

tools.arrayUnique = (arr, name) => {
  var hash = {};
  return arr.reduce(function (item, next) {
    hash[next[name]] ? '' : hash[next[name]] = true && item.push(next);
    return item;
  }, []);
}

tools.dateAddYear = function (date, yearCount) {
  var tempDate = dateToDate(date);
  var count = parseInt(yearCount);
  var oldYear = tempDate.getFullYear();
  var oldMonth = tempDate.getMonth();
  var oldDate = tempDate.getDate();
  var newYear = oldYear + count;
  var newDate = new Date(newYear, oldMonth, oldDate);
  //防止月份数不一致，进行微调
  while (newDate.getMonth() != oldMonth) {
    oldDate--;
    newDate = new Date(newYear, oldMonth, oldDate);
  }
  var month = newDate.getMonth() + 1;
  var day = newDate.getDate();
  month = (month.toString().length == 1) ? ("0" + month) : month;
  day = (day.toString().length == 1) ? ("0" + day) : day;

  var result = newDate.getFullYear() + '-' + month + '-' + day; //当前日期

  return result;
}
tools.formatDate = (now) => {
  let year = now.getFullYear();
  let month = now.getMonth() + 1;
  let date = now.getDate();
  let hour = now.getHours();
  let minute = now.getMinutes();
  let second = now.getSeconds();
  return year + "-" + (month > 10 ? month : '0' + month) + "-" + (date > 10 ? date : '0' + date) + " " + hour + ":" + (minute > 10 ? minute : '0' + minute) + ":" + (second > 10 ? second : '0' + second);
};
tools.formatDataSource = function (data) {
  let options
  let arr = []
  function recursion(data) {
    let arr = []
    data.map((item) => {
      if (item.code && item.name)
        arr.push({ Code: item.code, Name: item.name })
      if (item.content && item.content.length)
        arr = arr.concat(recursion(item.content))
    })
    return arr
  }
  try {
    if (data instanceof Array) {
      options = data
    } else {
      options = JSON.parse(data)
    }
    if (options) {
      return recursion(options)
    } else {
      return arr
    }
  } catch (err) {
    console.log(err);
    return arr
  }
}

tools.isObjectValueEqual = function (a, b) {//判断两个对象的可枚举属性值是否相等(认为null,"",undefinde相等)
  //取对象a和b的属性名
  var aProps = Object.keys(a)
  var bProps = Object.keys(b)
  //判断属性名的length是否一致
  if (aProps.length != bProps.length) {
    return false
  }

  //循环取出属性名，再判断属性值是否一致
  for (var i = 0; i < aProps.length; i++) {
    var propName = aProps[i]
    if (!(a[propName] instanceof Object || b[propName] instanceof Object)) {
      if (!(a[propName] == b[propName] || (!a[propName] && !b[propName]))) {
        return false
      }
    } else {
      if (!tools.isObjectValueEqual(a[propName], b[propName])) {
        return false
      }
    }
  }
  return true

}

tools.dataForKey = function (data, key) {
  let arr = key.split(".")
  if (arr && arr[0]) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i] && data[arr[i]]) {
        data = data[arr[i]]
      } else {
        return ''
      }
    }
    return data
  }
}

tools.setDataForKey = function (data, key, value) {
  let arr = key.split(".")
  if (arr && arr[0]) {
    for (let i = 0; i < arr.length; i++) {
      if (!(arr[i] && data[arr[i]])) {
        data[arr[i]] = {}
      }
      if (value !== undefined) {
        if (i == arr.length - 1) {
          data[arr[i]] = value
        }
      } else {
        if (i == arr.length - 1) {
          data[arr[i]] = ''
        }
      }
      data = data[arr[i]]
    }
  }
}
tools.flattenKeys = function (obj) {
  if (obj == undefined) return
  let res = {}
  function isObject(val) {
    return typeof val === 'object' && !Array.isArray(val)
  }

  function digKeys(prev, obj) {
    Object.entries(obj).forEach(([key, value]) => {
      const currentKey = prev ? `${prev}.${key}` : key
      if (isObject(value)) {
        digKeys(currentKey, value)
      } else {
        res[currentKey] = value
      }
    })
  }

  digKeys('', obj)
  return res
}
function dateToDate(date) {
  var sDate = new Date();
  if (typeof date == 'object' && typeof new Date().getMonth == "function") {
    sDate = date;
  } else if (typeof date == "string") {
    var arr = date.split('-');
    if (arr.length == 3) {
      sDate = new Date(arr[0] + '-' + arr[1] + '-' + arr[2]);
    }
  }
  return sDate;
}

/**
 * 处理菜单函数
 */
tools.formatMenu = (originaMenuList) => {
  /**
   * 改为解析运维平台的根据用户ID获取用户信息的接口的返回
   * nh 2021.10.25
   */
  var newMenuList = [];
  var tempNewMenuList = [];
  var menuNameList = [];
  (originaMenuList || []).forEach(originaMenu => {
    for (var i = 0; i < localMenusList.length; i++) {
      var localMenu = localMenusList[i];
      if (localMenu.name == originaMenu.authorizationName) {
        //---------------------------------------------加上一级菜单
        if (menuNameList.indexOf(originaMenu.productName) == -1) {
          var firstLocalMenu = localMenusList.filter(_c => {
            return _c.name == originaMenu.productName;
          })[0];
          if (firstLocalMenu) {
            tempNewMenuList.push(JSON.parse(JSON.stringify(firstLocalMenu)));
            menuNameList.push(originaMenu.productName);
          }
        }
        //二级菜单
        tempNewMenuList.push(localMenu);

        //三级菜单
        var _menuChildrens = JSON.parse(JSON.stringify(localMenu.menuChildrens || []));
        for (var j = 0; j < _menuChildrens.length; j++) {
          var _childLocalMenu = _menuChildrens[j];
          if (originaMenuList.filter(_c => { return _c.authorizationName == _childLocalMenu.name; }).length == 0) {
            _menuChildrens.splice(j, 1);
            --j;
          }
        }
        localMenu.menuChildrens = _menuChildrens;

        menuNameList.push(localMenu.name);
        break;
      }
    }
  });
  tempNewMenuList.sort((_c1, _c2) => {
    return _c1.orders - _c2.orders;
  });
  return tempNewMenuList;



  const menuList = [];
  menu.forEach(item => {
    let children = {}
    if (item.menuChildrens) {
      children = item.menuChildrens;
      delete item.menuChildrens;
    }
    item.disabled = true;
    menuList.push(item, ...children);
  })
  return menuList;
}

export default tools
