import { getLocationParams } from "@/utils";

/**
 * 像素埋点函数
 */
export default function () {
  // 获取链接参数
  const p = getLocationParams();
  // 如果没有像素id不生成
  if (!p.fbPixelId) {
    return
  }
  // 创建fb像素埋点
  let script = document.createElement("script");
  script.id = "facebook-script";
  script.type = "text/javascript";
  script.async = true;
  script.innerHTML = `
      !function(f,b,e,v,n,t,s)
      {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
      n.callMethod.apply(n,arguments):n.queue.push(arguments)};
      if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
      n.queue=[];t=b.createElement(e);t.async=!0;
      t.src=v;s=b.getElementsByTagName(e)[0];
      s.parentNode.insertBefore(t,s)}(window, document,'script',
      'https://connect.facebook.net/en_US/fbevents.js');
      fbq('init', ${p.fbPixelId});
    `;
  document.getElementsByTagName("head")[0].appendChild(script);
  // 创建通知
  let noscript = document.createElement("noscript");
  let iframe = document.createElement("iframe");
  iframe.style.display = 'none'
  iframe.width = '0'
  iframe.height = '0'
  iframe.src = `https://www.facebook.com/tr?id=${p.fbPixelId}&ev=PageView&noscript=1`;
  noscript.appendChild(iframe);
  document.getElementsByTagName("body")[0].appendChild(noscript);


  // 动态配置meta
  let meta = document.createElement("meta");
  let meta2 = document.createElement("meta");
  meta.name = "og:url";
  meta.content = location.href;

  meta2.name = "twitter:url";
  meta2.content = location.href;
  document.getElementsByTagName("head")[0].appendChild(meta);
  document.getElementsByTagName("head")[0].appendChild(meta2);
}
