import { message } from '@/utils/message.js';
import dayjs from 'dayjs';

export function getNum(str) {
  if (typeof str !== 'string') return str;
  let numMatch = str.match(/[+-]?\d*\.?\d+(?:[Ee][+-]?\d+)?/);
  // 如果匹配到了，则转换为浮点数，否则返回null
  return numMatch ? parseFloat(numMatch[0]) : null;
}
export function exportExcel(res,  filename='') {
  const xlsx = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  const blob = new Blob([res.data], { type: xlsx }); // 转换数据类型
  const a = document.createElement('a'); // 转换完成，创建一个a标签用于下载
  let title = res.headers['content-disposition']?.slice(21) || filename;
  var decodedComponent = decodeURIComponent(title);
  a.download = decodedComponent;
  a.href = window.URL.createObjectURL(blob);
  a.click();
  a.remove();
  message('导出成功');
}
export function Download (res,  filename) {
  // let blob = new Blob([res]);
  let url = URL.createObjectURL(res);
  let link = document.createElement('a');
  link.href = url;
  link.download = `${filename}.xlsx`;
  link.click();
}
export function validInputVal(event) {
  let value = event.target.value;
  const validNumber = /^-?\d*\.?\d*$/;
  if (validNumber.test(value)) {
  } else {
    event.target.value = ''; // 直接更新输入框的显示值
  }
}

export function registerComponents(componentsArray, app) {
  componentsArray.forEach((component) => {
    app.use(component);
  });
}
//检测数据是否为空
export const isEmpty = (obj, keysToIgnore = []) => {
  for (let key in obj) {
    // 打印是否忽略当前 key
    if (obj.hasOwnProperty(key) && !keysToIgnore.includes(key)) {
      if (obj[key] === null || obj[key] === undefined || obj[key] === '') {
        return true;
      }
    }
  }
  return false;
};

export function displayDate(dateTimeStr) {
  return dateTimeStr.split(' ')[0];
}
//创建初始数据
export function createTableData() {
  let list = new Array(58).fill('');
  let first54Items = list.slice(0, 54);
  const resultObject = {};
  const step = 9;
  const keys = [15, 30, 45, 60, 75, 90];
  keys.forEach((key, index) => {
    resultObject[key] = first54Items.slice(index * step, (index + 1) * step);
  });
  return resultObject;
}
export const getFontSize = () => {
  const htmlElement = document.documentElement;
  return parseInt(htmlElement.style.fontSize);
};

export const getPx = (num) => {
  return (getFontSize() / 128) * num + 'px';
};
