
import httpRequest from "~/service/index";
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 copyToClipboard(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);
  }
}

/**
 *  二进制流转excel 
 */
export async function exportMethod2(data: any) {
  try {
    const res = await $fetch.raw(data.url, {
      method: data.method,
      body: data.params,   // POST 的参数
      responseType: 'blob' // 关键：返回 blob
    })

    // 创建 Blob
    const blob = new Blob([res._data], {
      type: 'application/vnd.ms-excel'
    })

    // 创建下载链接
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = URL.createObjectURL(blob)
    link.download = data.fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

  } catch (error) {
    console.error(error)
  }
}

export async function exportMethod(data: any) {
  try {
    const res = await $fetch.raw(`${data.url}${data.params ? '?' + data.params : ''}`, {
      method: data.method,
      responseType: 'blob'   // 一定要加
    });

    const blob:any = res._data;  // $fetch.raw 时文件流在 _data 里

    const link = document.createElement('a');
    link.style.display = 'none';
    link.href = URL.createObjectURL(blob);
    let fileName = data.fileName || 'download';
    // ⛳ 自动补全 .xls 后缀
    if (!fileName.toLowerCase().endsWith('.xls')) {
      fileName += '.xls';
    }

    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } catch (err) {
    console.error(err);
  }
}
