
export default function getCategoryName (a:any,id:number){
  let result = a.find((item:any) => item.id === id).name;
  return result
}
// 防抖函数
export function debounce(func: any, delay: any) {
  let timeout: any;
  return function (...args: any) {
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
};

// 复制
export async function copyToClipboardFun(code: string,event:any) {
  event.preventDefault();
  event.stopPropagation();
  try {
    await navigator.clipboard.writeText(code); // 将内容写入剪贴板
    ElMessage.success("复制成功");
  } catch (err: any) {
    ElMessage.error("复制失败");
  }
}

//百分比计算
export function returnPercent(n:any){
  let a = (Math.round(n * 100 * 100 / 100)).toFixed(2)
  let b = a.indexOf('.')
  let c = a.toString().substring(0,b)
  if(parseInt(a)==0){
    c = '1'
  }
  return c
}

// 价格转换
export function formatSellPrice(price:any) {
  // 将价格转换为字符串
  const priceStr = price.toString();

  // 按小数点分割整数和小数部分
  const [integerPart] = priceStr.split('.');

  // 获取整数部分的首位数字
  const firstDigit = integerPart[0];

  // 构造格式化后的结果
  const questionMarks = '?'.repeat(integerPart.length - 1); // 其余数字替换为问号
  return `${firstDigit}${questionMarks}.??`;
}

//存储时设置当天 24:00 过期
export function setLocalStorageWithExpiry(key:any, value:any) {
  let now = new Date();
  let midnight = new Date();
  midnight.setHours(24, 0, 0, 0); // 当天 24:00:00
  
  let data = {
    value: value,
    expiry: midnight.getTime() // 存储过期时间（毫秒）
  };
  localStorage.setItem(key, JSON.stringify(data));
}

//读取时检查是否过期
export function getLocalStorageWithExpiry(key:any) {
  let itemStr = localStorage.getItem(key);
  if (!itemStr) return null;

  let item = JSON.parse(itemStr);
  let now = new Date().getTime();

  if (now > item.expiry) {
    localStorage.removeItem(key); // 过期删除
    return null;
  }
  return item.value;
}

export function getBrowser() {
  let browser = 'Unknown';
  const detectBrowser = () => {
    const userAgent = navigator.userAgent.toLowerCase();
    if (userAgent.includes('firefox')) {
      browser = 'Firefox';
    } else if (userAgent.includes('safari') && !userAgent.includes('chrome')) {
      browser = 'Safari';
    } else if (userAgent.includes('chrome')) {
      browser = 'Chrome';
    } else if (userAgent.includes('edge')) {
      browser = 'Edge';
    } else if (userAgent.includes('opera') || userAgent.includes('opr')) {
      browser = 'Opera';
    } else if (userAgent.includes('msie') || userAgent.includes('trident')) {
      browser = 'Internet Explorer';
    }
  };

  detectBrowser()

  return { browser };
}


/**
* 埋点
* query => (page:页面,cate:类型名称,name:交互的行为,isLink:boolean,url:跳转url)
*/
export function Tracking(query:any) {
  const isMobile =
  /Android|iPhone|Windows Phone|UC|Kindle|MicroMessenger|iPad/i.test(
    navigator.userAgent
  );
  const { browser } = getBrowser();
  let trackdata = {
    page: query.page,
    browser: browser,
    deviceType: isMobile ? "mobile" : "desktop",
    url: location.href,
    host:location.host,
    userAgent: navigator.userAgent 
  };

  window._yfx_trackdata.push(["event", query.cate, query.name, trackdata]);
  // 延迟跳转
  console.log(window._yfx_trackdata)
  if(query.isLink){
    setTimeout(() => {
      navigateTo(query.url)
    }, 100);
  }
}