import { userStore } from "@/store/user-store";
import Taro from "@tarojs/taro";
// import UAParser from "ua-parser-js";
import axios from "axios";
import { load } from "@fingerprintjs/fingerprintjs";
import { getStorageSyncTime } from "@/utils";
import CryptoJS from "crypto-js";

export const base64Key: string = "MTIzNDU2Nzg5MDEyMzQ1Ng==";
export const iv: string = "1234567890123456";

type eventType = "event" | "behavior" | "exposure" | "stay";

/**
 * Who、When、How 由一般由埋点 SDK 自动生成，埋点设计人员在绝大多数情况下不必关心这三个要素，因此设计的核心是Where，What。
 * @param type
 * @param event
 */
export async function reporter<T>(type: eventType, event: T) {
  return;
  const systemInfo = await Taro.getSystemInfo();
  const networkTyp = await Taro.getNetworkType();
  // const uaParser = new UAParser(navigator.userAgent);

  console.log("getMurmur", getMurmur());

  const params = {
    network_type: networkTyp.networkType, // 网络类型
    app_version: process.env.XH_APP_VERSION, // 应用 版本号
    sdk_version: "1.0.0", // sdk 版本号
    platform: systemInfo.platform, // 客户端平台
    model: systemInfo.model, // 设备型号。新机型刚推出一段时间会显示unknown，微信会尽快进行适配。
    system: systemInfo.system, // 系统版本号
    version: systemInfo.version, // 微信版本号
    time: new Date().getTime(),
    event: event,
    type: type,
    user_id:
      userStore.getState().user?.userId ||
      getStorageSyncTime<AuthAPI.UserVO>("user")?.userId,
    merchant_id:
      process.env.TARO_ENV === "weapp"
        ? Taro.getExtConfigSync().merchantId
        : Taro.getStorageSync("merchantId"),
    merchant_app_id:
      process.env.TARO_ENV === "weapp"
        ? Taro.getExtConfigSync().merchantAppId
        : Taro.getStorageSync("merchantAppId"),
    page_path: Taro.getCurrentInstance().router?.path,
  };

  console.log("params", params);

  const ciphertext = encrypt(JSON.stringify(params), base64Key, iv);

  if (process.env.TARO_ENV === "h5") {
    new Image(0, 0).src =
      process.env.XH_MD_DOMAIN +
      `/log.gif?value=${encodeURIComponent(ciphertext)}`;
  }

  if (process.env.TARO_ENV === "weapp") {
    const reporter =
      process.env.XH_MD_DOMAIN + `/log?value=${encodeURIComponent(ciphertext)}`;

    let result: boolean = false;
    if (typeof navigator.sendBeacon === "function") {
      console.log("sendBeacon params", params);
      result = navigator.sendBeacon(reporter);
    }
    if (!result) {
      console.log("xhr params", params);
      axios.post(reporter).then();
    }
  }
}

/**
 * @description: 生成浏览器唯一标识
 */
export const getMurmur = () => {
  const agentPromise = load();
  agentPromise.then(async (agent) => {
    agent.get().then((result) => {
      console.log("rest", result.visitorId);
    });
  });
};

/**
 * AES加密
 * @param plainText 明文
 * @param keyInBase64Str base64编码后的key
 * @param iv 向量
 * @returns {string} base64编码后的密文
 */
export function encrypt(
  plainText: string,
  keyInBase64Str: string,
  iv: string,
): string {
  let key = CryptoJS.enc.Base64.parse(keyInBase64Str);
  const encrypted = CryptoJS.AES.encrypt(plainText, key, {
    iv: CryptoJS.enc.Utf8.parse(iv),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  } as any);
  // 这里的encrypted不是字符串，而是一个CipherParams对象
  return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
}
