import { Message } from "element-ui";
import { parseTime } from './ruoyi';

/**
 * 表格时间格式化
 */
export function formatDate(cellValue) {
  if (cellValue == null || cellValue == "") return "";
  var date = new Date(cellValue);
  var year = date.getFullYear();
  var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
  var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
  var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
  var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return '刚刚';
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前';
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前';
  } else if (diff < 3600 * 24 * 2) {
    return '1天前';
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    );
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url;
  const search = url.substring(url.lastIndexOf('?') + 1);
  const obj = {};
  const reg = /([^?&=]+)=([^?&=]*)/g;
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1);
    let val = decodeURIComponent($2);
    val = String(val);
    obj[name] = val;
    return rs;
  });
  return obj;
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length;
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s += 2;
    if (code >= 0xDC00 && code <= 0xDFFF) i--;
  }
  return s;
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = [];
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return '';
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return '';
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key]);
    })
  ).join('&');
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ');
  if (!search) {
    return {};
  }
  const obj = {};
  const searchArr = search.split('&');
  searchArr.forEach(v => {
    const index = v.indexOf('=');
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  return obj;
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div');
  div.innerHTML = val;
  return div.textContent || div.innerText;
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {};
  }
  if (Array.isArray(source)) {
    return source.slice();
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property];
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty);
    } else {
      target[property] = sourceProperty;
    }
  });
  return target;
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return;
  }
  let classString = element.className;
  const nameIndex = classString.indexOf(className);
  if (nameIndex === -1) {
    classString += '' + className;
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length);
  }
  element.className = classString;
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90;
  } else {
    return new Date(new Date().toDateString());
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result;

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp;

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };

  return function (...args) {
    context = this;
    timestamp = +new Date();
    const callNow = immediate && !timeout;
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone');
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr));
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + '';
  const randomNum = parseInt((1 + Math.random()) * 65536) + '';
  return (+(randomNum + timestamp)).toString(32);
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls;
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
    ele.className = ele.className.replace(reg, ' ');
  }
}

export function makeMap(str, expectsLowerCase) {
  const map = Object.create(null);
  const list = str.split(',');
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true;
  }
  return expectsLowerCase
    ? val => map[val.toLowerCase()]
    : val => map[val];
}

export const exportDefault = 'export default ';

export const beautifierConf = {
  html: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'separate',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: false,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true
  },
  js: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'normal',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: true,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true
  }
};

// 首字母大小
export function titleCase(str) {
  return str.replace(/( |^)[a-z]/g, L => L.toUpperCase());
}

// 下划转驼峰
export function camelCase(str) {
  return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase());
}

export function toHump(lineStr) {
  return lineStr.replace(/\_(\w)/g, (all, letter) => letter.toUpperCase());
}

/**
 * 驼峰转下划线
 * @param {string} humpStr 
 * @returns 
 */
export function toLine(humpStr) {
  return humpStr.replace(/([A-Z])/g, "_$1").toLowerCase();
}

export function isNumberStr(str) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str);
}

/**
 * 
 * @param {string} originUrl 需要获取参数的url 默认当前url
 * @param {RegExp} reg key需要剔除的特殊字符 默认过滤问号
 * @returns {{[key : string] : any}} 查询对象 键值对
 */
export const getUrlSearchQuery = (originUrl = location.href, reg = new RegExp("\\?", "gi")) => {
  const url = new URL(originUrl);
  const params = url.searchParams.entries();
  let _temp = {};
  for (const [key, value] of params) {
    _temp[key.replace(reg, "")] = (value ? decodeURIComponent(value) : "");
  }
  return _temp;
};

/**
 * 对象转换为查询字符串
 * @param {{[key:string] : any}} query 
 */
export const paramsToQuery = (query) => {
  try {
    if (Object.prototype.toString.call(query) !== "[object Object]") return "";
    const params = new URLSearchParams(query);
    let searchStrArray = [];
    params.forEach((value, key) => {
      if (params.has(key)) {
        searchStrArray.push(`${key}=${decodeURIComponent(value)}`);
      }
    });
    return searchStrArray.join("&");
  } catch (error) {
    console.log(error);
  }
};

/**
 * 查询字符串转对象
 * @param {string} text 
 */
export const searchTextToQuery = (text) => {
  try {
    if (text) {
      const url = new URLSearchParams(text);
      const _temp = {};
      url.forEach((value, key) => {
        _temp[key] = value;
      });
      return JSON.parse(JSON.stringify(_temp));
    }
  } catch (error) {
    console.log(error);
  }
};

/**
 * 验证链接是否是url
 * @param {string} url 
 * @returns 
 */
export function isUrl(url) {
  return /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*[\u4e00-\u9fa5\w]*)$/.test(url);
}

// 对查询关键字中的特殊字符进行编码
export function encodeSearchKey(key) {
  const encodeArr = [{
    code: '%',
    encode: '%25'
  }, {
    code: '?',
    encode: '%3F'
  }, {
    code: '#',
    encode: '%23'
  }, {
    code: '&',
    encode: '%26'
  }, {
    code: '=',
    encode: '%3D'
  }];
  return key.replace(/[%?#&=]/g, ($, index, str) => {
    for (const k of encodeArr) {
      if (k.code === $) {
        return k.encode;
      }
    }
  });
}

/**
 * 去除json 换行空格符号
 * @param {string} str 
 * @returns 
 */
export function jsonEscape(str) {
  return str.replace(/(\r\n|\n|\r)/gm, "");
}

/**
 * json递归特殊参数处理
 * @param {object} target 
 */
export function jsonTraversal(target, decode = false) {
  try {
    if (Object.prototype.toString.call(target) != "[object Object]") throw new Error("传入参数不是一个对象");
    for (const key in target) {
      // 传入指定key 或者 key数组长度未0 默认全编码
      if (Object.prototype.toString.call(target[key]) == "[object Object]") {
        target[key] = jsonTraversal(target[key], decode);
      } else {
        if (decode) {
          isencodingStr(target[key]) ? target[key] = decodeURIComponent(target[key]) : null;
        } else {
          needEncodeComponent(target[key]) ? target[key] = encodeURIComponent(target[key]) : null;
        }
      }
    }
    return target;
  } catch (error) {
    console.log(error);
  }
}

/**
 * url查询参数中需要编码的特殊字符
 * @param {string} componentStr 
 * @returns 
 */
export function needEncodeComponent(componentStr) {
  const reg = /[^a-zA-Z0-9\-_.!~*'()]/gim;
  return reg.test(componentStr);
}

/**
 * 字符串是否被编码过
 * @param {string} checkStr 
 * @returns 
 */
export function isencodingStr(checkStr) {
  const reg = /%[0-9A-Fa-f]{2}/gim;
  return reg.test(checkStr);
}

let messageSingleton = null;
/**
 * element message 弹窗单例模式
 * @param {string} type 
 * @param {string} messgage 
 */
export async function elementMessageSingleton(type = "success", messgage = "") {
  try {
    if (messageSingleton) {
      messageSingleton.close();
    }
  } catch (error) {
    console.log(error);
  } finally {
    messageSingleton = Message[type](messgage);
  }
}

/**
 * 检测数组对象中是否有重复数据
 * @param {Array} arr 
 * @param {string | null} mapKey 
 * @returns
 */
export function hasDuplicates(arr, mapKey = null) {
  try {
    const map = new Map();
    for (const item of arr) {
      const key = mapKey ? item[mapKey] : JSON.stringify(item);
      if (map.has(key)) {
        return { hasRepeat: true, repeatKey: key };
      }
      map.set(key, true);
    }
    return { hasRepeat: false };
  } catch (error) {
    console.log(error);
  }
}

/**
 * 表单查询条件过滤
 * @param {Object} params 
 */
export function queryConditionFiltering(params) {
  try {
    if (Object.prototype.toString.call(params) != "[object Object]") throw new Error("传入查询条件不是一个对象");
    const _temp = JSON.parse(JSON.stringify(params));
    const keys = Object.keys(_temp);;
    const len = keys.length;
    const result = {};
    for (let index = 0; index < len; index++) {
      const key = keys[index];
      if (_temp.hasOwnProperty(key)) {
        // 数组内部不处理
        if (_temp[key] instanceof Array && _temp[key]?.length) {
          result[key] = _temp[key];
          continue;
        }
        // 如果是对象 递归处理
        if (Object.prototype.toString.call(_temp[key]) == "[object Object]") {
          result[key] = queryConditionFiltering(_temp[key]);
          continue;
        }
        // 过滤无效值 0为有效数据 object在此处作为无效值
        if (typeof _temp[key] != "object" && (_temp[key] || _temp[key] == "0")) {
          result[key] = _temp[key];
          continue;
        }
      }
    }
    return result;
  } catch (error) {
    console.warn(error);
  }
}

/**
 * 三级联动选择 过滤省市区 兼容父子互不关联情况
 * @param {Array<object>} selectList 
 * @returns 
 */
export function getTreeSelectAreaList(node, tree) {
  try {
    if (Object.prototype.toString.call(node) != "[object Object]") throw new Error("传入参数不是一个对象");

    const _result = [];
    const _tempTree = JSON.parse(JSON.stringify(tree));

    // 多树形结构
    if (Object.prototype.toString.call(_tempTree) == "[object Array]") {
      if (_tempTree.length) {
        for (const iterator of _tempTree) {
          const nodeAncestors = findNodeAndAncestors(iterator, node.value, "value");
          // 查找到
          if (nodeAncestors) {
            console.log(nodeAncestors);
            // 找父节点 拿到父节点的child 数量 跟 length 没有父节点 就是顶级节点
            const parent = findParentNode(nodeAncestors, node.value, "value");
            console.log(parent);
          }
        }
      }
    }

    // 单树形结构
  } catch (error) {
    console.log(error);
  }
}


/**
 * 根据节点 id 获取父节点
 * @param {*} tree 
 * @param {*} targetId 
 * @param {*} parentNode 
 * @returns 
 */
export function findParentNode(tree, targetId, idKey = "id", parentNode = null) {
  if (tree[idKey] === targetId) {
    // 找到目标节点，返回其父节点
    return parentNode;
  }

  if (tree?.children?.length) {
    for (const child of tree.children) {
      const result = findParentNode(child, targetId, idKey, tree);
      if (result) {
        // 如果找到目标节点，返回其父节点
        return result;
      }
    }
  }

  // 如果未找到目标节点，返回 null
  return null;
}

/**
 * 根据节点信息 找到当前节点到祖先辈组成的树形结构
 * @param {*} tree 
 * @param {*} targetId 
 * @returns 
 */
export function findNodeAndAncestors(tree, targetId, idKey = "id", directAncestorsOnly = true) {
  if (tree[idKey] === targetId) {
    // 找到目标节点，directAncestorsOnly 只找直系节点的情况下 如果是根节点(没有parent父级)，返回节点本身不带子节点，否则返回节点的树形结构
    return directAncestorsOnly && !tree.parent ? { ...tree, children: null } : tree;
  }

  if (tree?.children?.length) {
    for (const child of tree.children) {
      const result = findNodeAndAncestors(child, targetId, idKey, directAncestorsOnly);
      if (result) {
        // 如果找到目标节点，将该节点加入祖先辈的树形结构中
        if (directAncestorsOnly) {
          return {
            ...tree,
            children: [result]
          };
        } else {
          return {
            ...tree,
            children: tree?.children?.map(c => (c[idKey] === result[idKey] ? result : c))
          };
        }
      }
    }
  }

  // 如果未找到目标节点，返回null
  return null;
}

/**
 * 根据节点唯一标识查找节点信息
 * @param {*} tree 
 * @param {*} targetId 
 * @param {*} idKes 
 */
export function findNodeFromTree(tree, targetId, idKes = "id") {
  if (tree[idKes] == targetId) {
    return tree;
  }

  if (tree?.children?.length) {
    for (const child of tree.children) {
      // 递归到孙子集查找
      const result = findNodeFromTree(child, targetId);
      if (result) {
        // 如果找到目标节点，返回目标节点
        return result;
      }
    }
  }

  return null;
}

/**
 * 删除某个属性节点
 * @param node 
 */
export function removeAncestors(node, removeKey = "ancestors") {
  delete node[removeKey];
  for (const child of node.children) {
    removeAncestors(child, removeKey);
  }
}

/**
 * 根据id 数组 生成直系关系树形结构 并排除不需要的属性
 * @param tree 
 * @param targetIds 
 * @returns 
 */
export function generateDirectSubtreeAndRemove(tree, targetIds) {
  const findNodeById = (node, id, ancestors = []) => {
    if (node.id === id) {
      return { ...node, ancestors };
    }
    for (const child of node.children) {
      const foundNode = findNodeById(child, id, [...ancestors, node]);
      if (foundNode) {
        return foundNode;
      }
    }
    return null;
  };

  const result = { ...tree, children: [] };

  for (const targetId of targetIds) {
    const targetNode = findNodeById(tree, targetId);
    if (targetNode) {
      // Include the target node and its ancestors in the result
      let currentNode = result;
      for (const ancestor of targetNode.ancestors) {
        const existingNode = currentNode.children.find((child) => child.id === ancestor.id);
        if (existingNode) {
          currentNode = existingNode;
        } else {
          const newNode = { ...ancestor, children: [] };
          currentNode.children.push(newNode);
          currentNode = newNode;
        }
      }

      // Add the target node to the result
      currentNode.children.push({ ...targetNode, children: [] });
    }
  }

  // Remove the ancestors property from the result
  removeAncestors(result);

  return result.children; // Return only the direct children of the new root
}

// 甲方详情左侧菜单映射
export const detailSideBar = new Map([
  // 企业速览
  ["holderinfo", "ownershipStructure"],
  // 高管信息
  ["execuinfo", "leadingMember"],
  // 对外投资
  ["overseas", "outboundInvestment"],
  // 分支机构
  ["branch", "branch"],
])

