const chapterReg = /^[0-9]+$/;
export function clearStorageChapter() {
  Object.keys(window.localStorage).forEach(value => {
    if (chapterReg.test(value)) {
      window.localStorage.removeItem(value);
    }
  });
}

const IFRAME_ID = "asyncIframe";

const OPEN_YCSD_TJ = window.options.yctj;
const TJ_URL = window.options.yctj_url;
// 异步创建iframe 加载页面
export function loadIframeAsync() {
  if (OPEN_YCSD_TJ) {
    var iframe = document.createElement("iframe");
    iframe.setAttribute("style", "position: fixed; bottom:0;");
    iframe.setAttribute("width", 0);
    iframe.setAttribute("height", 0);
    iframe.setAttribute("id", IFRAME_ID);
    iframe.setAttribute("src", TJ_URL);
    document.querySelector("body").appendChild(iframe);
  }
}

// 移除iframe
export function removeIframe() {
  var iframe = document.querySelector("#" + IFRAME_ID);
  if (iframe) document.querySelector("body").removeChild(iframe);
}

// 文案随机 banner随机
export function crmBannerRandom(crmType) {
  let crm_guide_pool = window.options.crm_guide_pool;
  let result = "";
  if (crm_guide_pool[crmType]) {
    let target = crm_guide_pool[crmType];
    let randomTitleIndex = Math.ceil(Math.random() * target.title.length) - 1;
    let randomBannerIndex = Math.ceil(Math.random() * target.banner.length) - 1;
    console.log("banner index: ", randomBannerIndex);
    console.log("text index: ", randomTitleIndex);
    result = {
      title: target.title[randomTitleIndex],
      banner: target.banner[randomBannerIndex]
    };
  }
  return result;
}

// 淘宝券商品链接复制
export function needToCopy() {
  let { twj_code } = window.options;
  let need_to_copy = true;
  // 没有code 直接false
  if (!twj_code.code) return false;
  let prev_copy_val = localStorage.getItem("copy_product");
  // 已经复制过
  if (prev_copy_val) {
    // 是否失效 - 判断是否还存在数组里
    let is_useful = twj_code.code.includes(prev_copy_val);
    if (is_useful) need_to_copy = false;
  }
  console.log("is_need_copy:", need_to_copy);
  return need_to_copy;
}

export function getRandomCode() {
  let { twj_code } = window.options;
  if (twj_code.code) {
    let index = Math.ceil(Math.random() * twj_code.code.length) - 1;
    return twj_code.code[index];
  }
  return "";
}

export function recordCode(code) {
  // let { uid, twj_code } = window.options;
  localStorage.setItem("copy_product", code);
  // let img = document.createElement("img");
  // let src = twj_code.link + `?uid=${uid}&code=${encodeURIComponent(code)}`;
  // img.setAttribute("src", src);
  // img.style = "position: absolute; bottom: 0; left: 0; width: 0; height: 0";
  // document.body.appendChild(img);
}

export function clipboard(text, event) {
  console.log("11");
  const cb = new Clipboard(".null", { text: () => text });
  cb.on("success", function(e) {
    console.log("success");
    cb.off("error");
    cb.off("success");
  });
  cb.on("error", function(e) {
    console.log("error");
    cb.off("error");
    cb.off("success");
  });
  cb.onClick(event);
}
