import useClipboard from "vue-clipboard3";
import { VITE_CDN_STATIC_PATH } from "@/common/config";
import router from "@/router";
import dayjs from "dayjs";
import Decimal from "decimal.js";
import { toast } from "./toast";
import storage, { actions } from "@/utils/storage";

const { toClipboard } = useClipboard();

/**
 * 获取静态资源url地址
 * @param assetsPath 静态资源路径，相对于assets目录
 */
export function getAssets(assetsPath: string) {
  return new URL(`../assets/img/${assetsPath}`, import.meta.url).href;
}

/**
 * cdn静态资源
 */
export const getStaticImage = (path: string) => {
  return `${VITE_CDN_STATIC_PATH}static/${path}`;
};

/**
 * 获取网络图片地址
 */

export const getImage = (path: string) => {
  return import.meta.env.VITE_APP_BASE_IMG +'/' + path;
};

/**
 * 千位分割
 * @param num
 * @returns
 */
export function formatDigit(num: number | string) {
  let reg = /\d{1,3}(?=(\d{3})+$)/g;
  if (!num) {
    return "0";
  }
  let n = num.toString();
  let arr: any = [];
  if (n.includes(".")) {
    arr = n.split(".");
    return (arr[0] + "").replace(reg, "$&.") + "," + arr[1];
  } else {
    return (num + "").replace(reg, "$&.");
  }
}
/**
 * 取小数点 四舍五入
 * @param num
 * @returns
 */
export function formatDecimal(num: number | string, position: number) {
  return Number(num).toFixed(position);
}
// 复制
export function clipboard(copy: string) {
  try {
    toClipboard(copy);
    toast("Copy Success");
  } catch (error) {
    new Error("copy error");
  }
}
/**
 * 写入搜索框历史记录
 * 截取最后三个 写入
 * @param value
 */
export function writeHistoricalData(value: any) {
  let searchHistoryList = [];
  if (value instanceof Array) {
    searchHistoryList = [...value];
  } else {
    const valueList = localStorage.getItem("searchHistoryList")
      ? localStorage.getItem("searchHistoryList").split(",")
      : [];
    valueList.push(value);
    searchHistoryList =
      valueList.length > 3
        ? [...new Set(valueList)].slice(1, 4)
        : [...new Set(valueList)];
  }
  localStorage.setItem("searchHistoryList", searchHistoryList.join(","));
}

// 格式化名称
export const fomartName = (name: string) => {
  return name.replace(name.slice(3, 5), "***");
};

// 设备环境
export function userBrowser() {
  let user = navigator.userAgent;
  let isAndroid = user.indexOf("Android") > -1 || user.indexOf("Adr") > -1;
  let isIos = !!user.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  return {
    isAndroid,
    isIos,
  };
}

// 格式化 游戏数据源 [[],[],[]]
export const formatGameList = (listData: Array<any>, num: number) => {
  let data: Array<any> = [];
  let length = Math.ceil(listData.length / num);
  for (let i = 0; i < length; i++) {
    if (listData.length == 0) return (data = [[]]);
    data.push([]);
  }
  for (let j = 0; j < data.length; j++) {
    data[j] = listData.slice(j * num, (j + 1) * num);
  }
  return data;
};

/**
 * 格式化 日期
 */
export const fomartDate = (
  time: string | Date,
  tem: string = "YYYY-MM-DD HH:mm:ss"
) => {
  return dayjs(time).format(tem);
};
/**
 * 时间戳转换
 * @param time  时间
 * @param step 时间戳长度 true 10位 false 13位
 * @returns
 */
export const toTimeStamp = (time: string, step: boolean = true) => {
  return step ? dayjs(time).unix() : dayjs(time).valueOf();
};

/**
 * 获取当前时间戳
 * @param step
 * @returns
 */
export function getCurrentTime(step: number = 1000) {
  let time = Math.round(new Date().getTime() / step);
  return time;
}

/**
 * @param type add | sub | mul | div
 * 精度计算
 */
export function decimalNumber(n1: number, n2: number, type: string) {
  let result: any = 0;
  switch (type) {
    case "add":
      result = new Decimal(n1).add(new Decimal(n2));
      break;
    case "sub":
      result = new Decimal(n1).sub(new Decimal(n2));
      break;
    case "mul":
      result = new Decimal(n1).mul(new Decimal(n2));
      break;
    case "div":
      result = new Decimal(n1).div(new Decimal(n2));
      break;
  }
  return result.toNumber();
}

/**
 * 跳转外部链接
 */

export function jumpOhterLink(link: string) {
  console.log(link, "?link");
  try {
    window.Android.openAndroid(<string>link);
  } catch (error) {
    window.open(<string>link);
  }
}

/**
 * 格式化地址参数
 * @param url
 * @returns
 */
export function getLocationParams(url?: string) {
  url = url || location.href.trim();
  let p: CustomObject = {};
  let arr = url.split("#");

  arr.forEach((item) => {
    // console.log(item)
    if (!item.includes("?")) return;
    let t = item.split("?");
    // console.log(t)
    t[1].split("&").forEach((item2) => {
      let t2 = item2.split("=");
      p[t2[0]] = decodeURIComponent(t2[1]);
    });
  });
  return p;
}

// facebook 像素埋点
export function buryingPointToFaceBook(fn: string, params?: any) {
  console.log(fn, params, "进入facebook埋点");
  try {
    window.fbq("track", fn, params);
  } catch (error) {
    console.log(error);
  }
}

// 谷歌埋点
export function buryingPointToGoogle(fn: string, params?: any) {
  console.log(fn, params, "进入google埋点");
  let p = {
    send_to: "AW-11457761648/TgPJCPabmpcZEPCivtcq",
    ...params,
  };
  try {
    window.gtag("event", fn, p);
  } catch (error) {
    console.log(error);
  }
}

// 快手埋点
export function buryingPointToKwaiq(fn: string, params?: CustomObject) {
  console.log(fn, params, "进入kwaiq埋点");
  const p = getLocationParams();
  if (!p.kwai_pixel_id) {
    return;
  }
  try {
    window.kwaiq.instance(p.kwai_pixel_id).track(fn, params);
  } catch (error) {
    console.log(error);
  }
}

// 验证手机号
export function resultMobile(num: string) {
  // let result = RegExp(/^[1-9]{2}\s?9\d{7,8}$/);
  let result = RegExp(/^\d{10,11}$/);
  if (!result.test(num)) {
    return false;
  }
  return true;
}

// 匹配Img标签 a标签
export function otherImg(str: any) {
  const imgTags = str.replace(/<img[^>]*>/g, (item: any) => {
    if (item && item.includes("http")) {
      return item;
    } else {
      return item.replace(/src="/g, `src="${import.meta.env.VITE_APP_BASE_IMG+'/'}`);
    }
  });
  const tempElement = document.createElement("div");
  tempElement.innerHTML = imgTags;
  const aTags = tempElement.querySelectorAll("a");
  aTags.forEach((aTag) => {
    aTag.style.display = "flex";
  });
  const updatedHtmlString = tempElement.innerHTML;
  return updatedHtmlString;
}

export function handleDomClick(event: any) {
  event.preventDefault();
  const A_arr = (event.composedPath() || []).filter(
    (item: any) => item.tagName === "A"
  );
  if (A_arr.length > 0) {
    const href = A_arr[0].getAttribute("href");
    const target = A_arr[0].getAttribute("target");
    if (target === "_blank") {
      jumpOhterLink(href);
    } else {
      router.push(href);
    }
  }
}
