import { parseTime } from '@/utils/ruoyi';

/**
 * 表格时间格式化
 */
export const formatDate = (cellValue) => {
  if (cellValue == null || cellValue == '') return '';
  const date = new Date(cellValue);
  const year = date.getFullYear();
  const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
  const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  const hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
  const minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
  const 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 const formatTime = (time, option) => {
  let t;
  if (('' + time).length === 10) {
    t = parseInt(time) * 1000;
  } else {
    t = +time;
  }
  const d = new Date(t);
  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(t, option);
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分';
  }
};

/**
 * @param {string} url
 * @returns {Object}
 */
export const 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 const byteLength = (str) => {
  // returns the byte length of an utf8 string
  let s = str.length;
  for (let 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 const 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 const 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 const 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 const 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 const 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 const toggleClass = (element, className) => {
  if (!element || !className) {
    return;
  }
  let classString = element.className;
  const nameIndex = classString.indexOf(className);
  if (nameIndex === -1) {
    classString += '' + className;
  } else {
    classString = classString.substring(0, nameIndex) + classString.substring(nameIndex + className.length);
  }
  element.className = classString;
};

/**
 * @param {string} type
 * @returns {Date}
 */
export const 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 const 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 (...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 const 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 const uniqueArr = (arr) => {
  return Array.from(new Set(arr));
};

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

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

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

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

/**
 * @param {string} path
 * @returns {Boolean}
 */
export const isExternal = (path) => {
  return /^(https?:|http?:|mailto:|tel:)/.test(path);
};

export const getTransformScale = (element) => {
  // 获取元素的transform属性值
  const transform = window.getComputedStyle(element).transform || 'none';

  // 检查是否包含scale变换
  if (transform === 'none') {
    return { scaleX: 1, scaleY: 1 };
  }

  // 正则表达式用于匹配scale变换的部分
  // 注意：这个正则表达式假设transform属性只包含一个scale变换，或者scale变换是第一个或最后一个
  // 在更复杂的场景中，你可能需要更复杂的解析逻辑
  const matrixValues = transform.match(
    /^matrix\((\d+\.?\d*e?[\-+]?\d*),\s*(\d+\.?\d*e?[\-+]?\d*),\s*(\d+\.?\d*e?[\-+]?\d*),\s*(\d+\.?\d*e?[\-+]?\d*),\s*(\d+\.?\d*e?[\-+]?\d*),\s*(\d+\.?\d*e?[\-+]?\d*)\)$/
  );

  if (matrixValues) {
    // 矩阵值：a, b, c, d, tx, ty
    // 对于2D的scale变换，a = scaleX, d = scaleY
    const scaleX = parseFloat(matrixValues[1]);
    const scaleY = parseFloat(matrixValues[4]);
    return { scaleX, scaleY };
  }

  // 如果transform属性包含多个变换，并且你想提取scale，你可能需要更复杂的逻辑
  // 这里我们简单处理只包含单个scale变换的情况
  const scaleMatch = transform.match(/scale\(([^)]+)\)/);
  if (scaleMatch) {
    // 如果scale变换是统一的（即scaleX = scaleY），它将是一个单独的数字
    // 否则，它将是一个由逗号分隔的两个数字（scaleX, scaleY）
    const scaleValues = scaleMatch[1].split(',').map(Number);
    if (scaleValues.length === 1) {
      // 统一的缩放比例
      return { scaleX: scaleValues[0], scaleY: scaleValues[0] };
    } else if (scaleValues.length === 2) {
      // 分别的scaleX和scaleY
      return { scaleX: scaleValues[0], scaleY: scaleValues[1] };
    }
  }

  // 如果没有找到scale变换，返回默认的缩放比例
  return { scaleX: 1, scaleY: 1 };
};

export const getRgba = (rgbaString) => {
  // 使用正则表达式匹配rgba的各个部分
  const match = rgbaString.match(/^rgba\(\s*(\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\s*\)$/);
  if (!match) {
    return rgbaString;
  }

  // 提取出红、绿、蓝和原始透明度
  const [r, g, b, opacity] = match.slice(1).map(Number);

  // 返回新的RGBA字符串，其中透明度被设置为1
  return {
    color: 'rgb(' + r + ',' + g + ',' + b + ')',
    opacity: opacity
  };
};

export const setHighText = (text, highArray) => {
  highArray.forEach((item) => {
    if (text.includes(item.text)) {
      // 转义正则表达式中的特殊字符
      const escapedSearchText = item.text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      const regex = new RegExp(escapedSearchText, 'g');
      text = text.replace(regex, '<span style="color: ' + item.color + '">' + item.text + '</span>');
    }
  });
  return text;
};

// 检查字符串是否为数字
export const isNumericString = (str) => {
  return /^\d+(\.\d+)?$/.test(str); // 这个正则表达式会匹配整数和小数
};

// 转换为带有两位小数的字符串
export const formatToTwoDecimalPlaces = (str) => {
  if (typeof str === 'number') {
    str = str.toString();
  }
  const [integerPart, decimalPart] = str.split('.');

  if (decimalPart === undefined || decimalPart.length === 0) {
    // 如果没有小数部分，则补齐 .00
    return `${integerPart}.00`;
  } else if (decimalPart.length === 1) {
    // 如果小数部分只有一位，则补齐到两位
    return `${integerPart}.${decimalPart}0`;
  } else {
    return str; // 直接返回原始字符串表示
  }
};

export const hexToRgba = (hex, alpha = 1) => {
  if (!hex) return '';
  // 确保输入是一个有效的十六进制颜色值，并以 # 开头
  hex = hex.replace(/^#/, '');
  // 如果十六进制颜色值是3位的简写形式（如 #f80），则扩展为6位
  if (hex.length === 3) {
    hex = hex
      .split('')
      .map((x) => x + x)
      .join('');
  }
  // 如果十六进制颜色值的长度不是6位，则抛出错误
  if (hex.length !== 6) {
    return hex;
  }
  // 解析红、绿、蓝分量
  const bigint = parseInt(hex, 16);
  const r = (bigint >> 16) & 255;
  const g = (bigint >> 8) & 255;
  const b = bigint & 255;
  // 返回 RGBA 字符串
  return `rgba(${r}, ${g}, ${b}, ${alpha || 1})`;
};

export const rgbToRgba = (rgbString, alpha) => {
  if (!rgbString) return '';
  // 去掉字符串两端的空格
  rgbString = rgbString.trim();

  // 使用正则表达式匹配 rgb 格式的数字部分
  const rgbMatch = rgbString.match(/\d+/g);

  // 如果没有匹配到 rgb 格式，返回 null
  if (!rgbMatch || rgbMatch.length !== 3) {
    return null;
  }

  // 将匹配到的数字部分转换为整数
  const r = parseInt(rgbMatch[0], 10);
  const g = parseInt(rgbMatch[1], 10);
  const b = parseInt(rgbMatch[2], 10);

  // 拼接 rgba 字符串
  const rgbaString = `rgba(${r}, ${g}, ${b}, ${alpha})`;

  return rgbaString;
};

export const initDrag = (el, scaleX = 1, scaleY = 1) => {
  if (!el) return;
  el.style.position = 'fixed';
  el.style.cursor = 'move';

  const dragDom = el;

  let disX = 0; // 鼠标按下时，鼠标与拖拽元素的左边距
  let disY = 0; // 鼠标按下时，鼠标与拖拽元素的上边距

  dragDom.onmousedown = (e) => {
    // 鼠标按下，计算当前元素距离可视区的距离
    disX = e.clientX / scaleX - dragDom.offsetLeft;
    disY = e.clientY / scaleY - dragDom.offsetTop;

    // 鼠标移动事件
    document.onmousemove = function (e) {
      // 通过事件委托，计算移动的距离
      const l = e.clientX / scaleX - disX;
      const t = e.clientY / scaleY - disY;
      // 移动当前元素
      dragDom.style.left = `${l + 'px'}`;
      dragDom.style.top = `${t + 'px'}`;
    };

    // 鼠标松开事件
    document.onmouseup = function () {
      document.onmousemove = null;
      document.onmouseup = null;
    };
  };
};
