import moment from "moment";
import { post, get } from "@/utils/request";
import Cookies from "js-cookie";
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";
import * as toEnglish from "./ACapital.js";

//根据value值回显字典label值
export function dictDataEcho(value, arr) {
  if (value && arr) {
    value = value + "";
    const current = arr.find((x) => x.dictKey === value);
    if (current != undefined && current.dictValue) {
      return current.dictValue;
    }
    return "";
  }
  return "";
}

//根据value值回显字典label值
export function dictValueLabel(value, arr) {
  if ((value || value === 0) && arr) {
    const current = arr.filter((x) => x.value == value);
    if (current && current.length > 0) {
      return current[0].label;
    }
    return "";
  }
  return "";
}

export function getDict(key) {
  return new Promise((resolve, reject) => {
    let dictObj = {};
    let arr = {};
    let num = 0;
    // if (!sessionStorage.getItem("dict")) {
    //   sessionStorage.setItem("dict", JSON.stringify(dictObj));
    // } else {
    //   dictObj = JSON.parse(sessionStorage.getItem("dict"));
    // }
    for (let i = 0; i < key.length; i++) {
      const element = key[i];
      if (dictObj[element]) {
        arr[element] = dictObj[element];
        num++;
        if (num === key.length) {
          resolve(arr);
        }
      } else {
        post("/dictTenantData/page", {
          pageNum: 1,
          pageSize: 999,
          tenantId: Cookies.get("tenantId"),
          dictCode: element,
        }).then((res) => {
          dictObj[element] = res.rows;
          arr[element] = res.rows;
          sessionStorage.setItem("dict", JSON.stringify(dictObj));
          num++;
          console.log(num);
          if (num === key.length) {
            resolve(arr);
          }
        });
      }
    }
  });
}

export function getDictOne(key) {
  return new Promise((resolve, reject) => {
    let dictObj = {};
    let arr = {};
    let num = 0;
    for (let i = 0; i < key.length; i++) {
      const element = key[i];
      if (dictObj[element]) {
        arr[element] = dictObj[element];
        num++;
        if (num === key.length) {
          resolve(arr);
        }
      } else {
        post("/tenantDict/getDict", {
          dictCode: element,
        }).then((res) => {
          dictObj[element] = res;
          arr[element] = res;
          num++;
          if (num === key.length) {
            resolve(arr);
          }
        });
      }
    }
  });
}

// 金额千分符
export function moneyFormat(s, n) {
  if (s) {
    s = s + "";
    let str = s.slice(0, 1);
    if (str === "-") {
      s = s.slice(1, s.length);
    }
    n = n > 0 && n <= 20 ? n : 2;
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = s.split(".")[0].split("").reverse(),
      r = s.split(".")[1];
    var t = "";
    for (let i = 0; i < l.length; i++) {
      t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? "," : "");
    }
    let result = t.split("").reverse().join("") + "." + r;
    if (str === "-") {
      return "-" + result;
    } else {
      return result;
    }
  } else {
    return "0.00";
  }
}

// 计算该日期是星期几
export function calculationWeek(val, format) {
  let weekArrayList = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
  let index = new Date(moment(val, format).format("yyyy-MM-DD")).getDay();
  let week = weekArrayList[index];
  return week;
}

export function getPdf(title) {
  // pdfDom 这个就是你vue页面中定义的ID  比如<div id="pdfDom">  这个也要避下雷
  const element = document.getElementById("pdfDom");
  window.pageYoffset = 0;
  document.documentElement.scrollTop = 0;
  document.body.scrollTop = 0;
  setTimeout(() => {
    // const nowDate = new Date();
    // const date = {
    //   year: nowDate.getFullYear(),
    //   month: nowDate.getMonth() + 1,
    //   date: nowDate.getDate(),
    //   hours: nowDate.getHours(),
    //   minutes: nowDate.getMinutes(),
    //   seconds: nowDate.getSeconds(),
    // };
    // const newMonth = date.month > 10 ? date.month : "0" + date.month;
    // const newDay = date.date > 10 ? date.date : "0" + date.date;
    // const newMinutes = date.minutes < 10 ? "0" + date.minutes : date.minutes;
    // const newSeconds = date.seconds < 10 ? "0" + date.seconds : date.seconds;
    // const value = date.year + newMonth + newDay + date.hours + newMinutes + newSeconds;
    let id = "";
    //创建一个画布    ---  增加导出的pdf水印 ！！
    let can = document.createElement("canvas");
    //设置画布的长宽
    can.width = 400;
    can.height = 500;
    let cans = can.getContext("2d");
    //旋转角度
    cans.rotate((-15 * Math.PI) / 180);
    cans.font = "18px Vedana";
    //设置填充绘画的颜色、渐变或者模式
    cans.fillStyle = "rgba(200, 200, 200, 0.40)";
    //设置文本内容的当前对齐方式
    cans.textAlign = "left";
    //设置在绘制文本时使用的当前文本基线
    cans.textBaseline = "Middle";
    //在画布上绘制填色的文本（输出的文本，开始绘制文本的X坐标位置，开始绘制文本的Y坐标位置）
    //cans.fillText(value, can.width / 8, can.height / 2)
    let div = document.createElement("div");
    div.id = id;
    div.style.pointerEvents = "none";
    div.style.top = "2000px";
    div.style.left = "-2000px";
    div.style.position = "fixed";
    div.style.zIndex = "100000";
    div.style.width = document.getElementById("pdfDom").scrollHeight + "px";
    div.style.height = document.getElementById("pdfDom").scrollHeight + "px";
    div.style.background = "url(" + can.toDataURL("image/png") + ") left top repeat";
    document.getElementById("pdfDom").appendChild(div); // 到页面中
    html2Canvas(element, {
      allowTaint: true,
      useCORS: true, // 需要注意，element的 高度 宽度一定要在这里定义一下，不然会存在只下载了当前你能看到的页面   避雷避雷！！！
      scale: 2, // 提升画面质量，但是会增加文件大小
      height: document.getElementById("pdfDom").scrollHeight,
      windowHeight: document.getElementById("pdfDom").scrollHeight,
    }).then(function (canvas) {
      var contentWidth = canvas.width;
      var contentHeight = canvas.height;
      // 一页pdf显示html页面生成的canvas高度;
      var pageHeight = (contentWidth * 841.89) / 592.28;
      // 未生成pdf的html页面高度
      var leftHeight = contentHeight;
      // 页面偏移
      var position = 0;
      // a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
      var imgWidth = 595.28;
      var imgHeight = (592.28 / contentWidth) * contentHeight;
      var pageData = canvas.toDataURL("image/jpeg", 1.0);
      var pdf = new JsPDF("", "pt", "a4");
      // 有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
      // 当内容未超过pdf一页显示的范围，无需分页
      if (leftHeight < pageHeight) {
        pdf.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
      } else {
        while (leftHeight > 0) {
          pdf.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
          leftHeight -= pageHeight;
          position -= 841.89;
          // 避免添加空白页
          if (leftHeight > 0) {
            pdf.addPage();
          }
        }
      }
      pdf.save(title + ".pdf");
    });
  }, 1000);
}
export function getPdfTransverseA4(title) {
  html2Canvas(document.getElementById("pdfDom"), {
    // allowTaint: true,
    // taintTest: false,
    // logging: false,
    // useCORS: true,
    // dpi: window.devicePixelRatio * 2, // 将分辨率提高到特定的DPI 提高四倍
    // scale: 2, // 按比例增加分辨率
    allowTaint: true,
    useCORS: true, // 需要注意，element的 高度 宽度一定要在这里定义一下，不然会存在只下载了当前你能看到的页面   避雷避雷！！！
    scale: 4, // 提升画面质量，但是会增加文件大小
    height: document.getElementById("pdfDom").scrollHeight,
    windowHeight: document.getElementById("pdfDom").scrollHeight,
  }).then((canvas) => {
    // eslint-disable-next-line new-cap
    var pdf = new JsPDF("l", "mm", "a4"); // A3纸，横向
    // var pdf = new JsPDF('p', 'mm', 'a4') // A4纸，纵向
    var ctx = canvas.getContext("2d");
    // A4大小，210mm x 297mm，四边各保留10mm的边距，显示区域190x277
    // var a4w = 190;
    // var a4h = 277
    // A3大小，279mm x 420mm，四边各保留10mm的边距，显示区域259x400
    // var a4w = 259;
    // var a4h = 400;
    var a4w = 210;
    var a4h = 297;
    // var imgHeight = Math.floor(a4h * canvas.width / a4w) // 按A4显示比例换算一页图像的像素高度[这个计算方式应该是纵向]
    var imgHeight = Math.floor((a4w * canvas.width) / a4h); // 按A4显示比例换算一页图像的像素高度[这个是横向打印的计算方法]
    var renderedHeight = 0;
    while (renderedHeight < canvas.height) {
      var page = document.createElement("canvas");
      page.width = canvas.width;
      page.height = Math.min(imgHeight, canvas.height - renderedHeight); // 可能内容不足一页
      // 用getImageData剪裁指定区域，并画到前面创建的canvas对象中
      page.getContext("2d").putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0);
      // 添加图像到页面，保留10mm边距 [a4使用]
      // pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width))
      // 添加图像到页面，保留10mm边距[a3使用1.414换算比例]
      // pdf.addImage(page.toDataURL("image/jpeg", 1.0), "JPEG", 10, 10, a4w * 1.414, Math.min(a4h, (a4w * page.height) / page.width) * 1.414);
      pdf.addImage(page.toDataURL("image/jpeg", 1.0), "JPEG", 0, 0, a4w * 1.414, Math.min(a4h, (a4w * page.height) / page.width) * 1.414);
      renderedHeight += imgHeight;
      if (renderedHeight < canvas.height) {
        pdf.addPage(); // 如果后面还有内容，添加一个空页
      }
    }
    // 保存文件
    pdf.save(title + ".pdf");
  });
}

export function currencyPrefix(key) {
  if (["¥", "￥", "1"].includes(key)) {
    return "SAY RMB ";
  } else if (["$", "2"].includes(key)) {
    return "SAY US DOLLARS ";
  } else if (["€", "3"].includes(key)) {
    return "SAY EURO ";
  } else {
    return "SAY RMB ";
  }
}

// 金额英文写法
export function translateIntoEnglish(money, currencyType) {
  let text = "";
  if (money) {
    text = currencyPrefix(currencyType);
    if (!/^\d+$/.test(Number(money))) {
      text = text + parseFloat(money).toFixed(2).toEnglish().toUpperCase();
    } else {
      text = text + parseFloat(money).toFixed(2).toEnglish().toUpperCase() + " ONLY";
    }
  }
  text = text.split(" POINT ZERO ZERO ").join("");
  return text;
}

// 随机数
export function random() {
  let $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
  let maxPos = $chars.length;
  let random = "";
  for (let i = 0; i < 32; i++) {
    random += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return random;
}

// 深拷贝
export function checkType(target) {
  return Object.prototype.toString.call(target).slice(8, -1);
}
export function deepClone(data) {
  const obj = checkType(data) === "Array" ? [] : {};
  let arr = ["Object", "Array"];
  if (arr.includes(checkType(data))) {
    for (let key in data) {
      let value = data[key];
      //value为简单类型，直接赋值
      if (!arr.includes(checkType(value))) {
        obj[key] = value;
      } else {
        // 定义一个映射，初始化时，将data本身加入映射中
        const map = new WeakMap();
        // 如果拷贝的是复杂数据类型第一次拷贝后存入map
        // 第二次再遇到该值时，直接赋值为null,结束递归
        map.set(data, true);
        if (map.has(value)) {
          obj[key] = null;
        } else {
          map.set(value, true);
          obj[key] = deepClone(value);
        }
      }
    }
  } else {
    return data;
  }
  return obj;
}

// 计算时间间隔
export function timeInterval(smallTime, largeTime) {
  //一般前端使用的时间分隔符是"-"，需要替换成"/"
  let large = new Date(largeTime.replace("-", "/").replace("-", "/"));
  let small = new Date(smallTime.replace("-", "/").replace("-", "/"));
  if (large > small) {
    let date3 = large.getTime() - new Date(small).getTime(); //时间差的毫秒数
    //计算出相差天数
    let days = Math.floor(date3 / (24 * 3600 * 1000));
    //计算出小时数
    let leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
    let hours = Math.floor(leave1 / (3600 * 1000));
    //计算相差分钟数
    let leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
    let minutes = Math.floor(leave2 / (60 * 1000));
    //计算相差秒数
    let leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
    let seconds = Math.round(leave3 / 1000);
    return { days: days, hours: hours, minutes: minutes, seconds: seconds };
  }
  return { days: 0, hours: 0, minutes: 0, seconds: 0 };
}

// 比较时间大小
export function compareTime(date1, date2) {
  var oDate1 = new Date(date1);
  var oDate2 = new Date(date2);
  if (oDate1.getTime() > oDate2.getTime()) {
    return true; //第一个大
  } else {
    return false; //第二个大
  }
}
