import { isYunApp } from ".";

/**
  * 获取当前皮肤id
  * @returns
  */
export const GetCurrSkinId = () => {
  // eslint-disable-next-line no-useless-escape
  const matched = location.pathname.match(/\/([^\/]*).html/);
  const currSkinId = matched ? matched && matched[1] : ''
  console.log('当前皮肤id', currSkinId)
  return currSkinId
}

export const getCustomShareId = () => {
  const matched = location.href.match(/\/share\?id=(.*)/);
  const shareId = matched ? matched && matched[1] : '';
  console.log('自定义活动页id', shareId);
  return shareId;
};


import QRCode from 'qrcode'
import modalStore from "../store/modal";

export async function getQRCode(url) {
  const _myQRCode = await QRCode.toDataURL(url)
  return _myQRCode
}

/**
* @description: 函数节流，普通防连点
* @param {(Function, number?)}
* @return {Function}
*/
export const _throttle = (fun, delay = 2000) => {
 let last, deferTimer;
 return function () {
   const now = +new Date();
   if (last && now < last + delay) {
     clearTimeout(deferTimer);
     deferTimer = setTimeout(() => {
       last = now;
     }, delay);
   } else {
     last = now;
     fun.apply(this, arguments);
   }
 };
};


// 计算1970/1/1 距今的秒数
export const calcSecond = () => {
  const lastStamp = new Date(1970, 1, 1).getTime()

  const nowStamp = new Date().getTime()

  const seconds = Math.floor((nowStamp - lastStamp) / 1000)

  console.error("看看我的秒数", seconds)

  return seconds
}

export const randomStr = (length = 16) => {
  let str = '';
  let strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  const max = strPol.length;
  for(let i = 0; i < length; i++) {
    str += strPol[Math.floor(Math.random() * max)]
  }

  // console.error("看看我的随机串", str)

  return str
}


export function waitTime(time){
  return new Promise((resolve)=>{
    setTimeout(() => {
      resolve();
    }, time);
  });
}

export const convertImageToCanvas = (image) => {
  var canvas = document.createElement("canvas");
  canvas.width = image.width;
  canvas.height = image.height;
  canvas.getContext("2d").drawImage(image, 0, 0);
  return canvas;
};

export const url2Base64 = (src) => {
  return new Promise((resolve) => {
    // const imgDom = document.querySelector("#posterCom");
    const img = new Image();
    img.setAttribute("crossOrigin", "anonymous");
    img.src = src;
    img.onload = () => {
      const canvas = convertImageToCanvas(img);
      const url = canvas.toDataURL("image/png");
      // imgDom.append(img);
      img.style.className = "pic";
      // console.log(url.replace(/(data:image\/png;base64,)/g, ''))
      resolve(url);
    };
    img.onerror = () => {
      resolve("");
    };
  });
}

/**
 * @description: 支持异步函数的节流，防止接口时间太长击穿防连点
 * @return {Function}
 * @param fun
 * @param delay
 */
export const _asyncThrottle = (fun, delay = 2000) => {
  let last, deferTimer;
  let canClick = true;
  return function () {
    const now = Date.now();
    if (!canClick) return;

    if (last && now < last + delay) {
      // clearTimeout(deferTimer);
      // deferTimer = setTimeout(() => {
      //     last = now;
      // }, delay);
    } else {
      last = now;
      const ps = fun.apply(this, arguments);
      if (ps instanceof Promise) {
        canClick = false;
        ps.finally(() => {
          canClick = true;
        });
      }
    }
  };
};

/**
 * 日期格式化
 * @param date    接收可以被new Date()方法转换的内容
 * @param format  字符串，需要的格式例如：'yyyy/MM/dd hh:mm:ss'
 * @returns {String}
 */
export const dateFormatter = (date, format = "yyyy/MM/dd") => {
  if (!date) return "-";
  let _date = date
  let _format = format
  _date = new Date(
    typeof date === "string" && isNaN(date)
      ? date.replace(/-/g, "/")
      : Number(date)
  );
  const o = {
    "M+": _date.getMonth() + 1,
    "d+": _date.getDate(),
    "h+": _date.getHours(),
    "m+": _date.getMinutes(),
    "s+": _date.getSeconds(),
    "q+": Math.floor((_date.getMonth() + 3) / 3),
    S: _date.getMilliseconds(),
  };
  if (/(y+)/.test(_format)) {
    _format = format.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (const k in o) {
    if (new RegExp("(" + k + ")").test(_format)) {
      _format = _format.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return _format;
};


/**
 * 千分位
 */
export const formatThousand = (num) => {
  var reg = /\d{1,3}(?=(\d{3})+$)/g;
  return (num + '').replace(reg, '$&,');
}