import store from "@/store";

//px转换mm
export function pxToUnit(px, unit) {
  const setting = this.$dataStore.get("setting");
  if (!unit) {
    if (setting) {
      unit = setting.unit;
    }
  }
  // console.log("mm", px);
  // console.log("inch", Number((Number(px) / 0.84183).toFixed(1)));
  if (unit === "mm") {
    px = Number((px * 0.84183).toFixed(1));
  } else if (unit === "inch") {
    px = Number((px * 0.84183) / 25.4).toFixed(1);
  }
  return px;
}
export function mmToPx(mm) {
  return Number((Number(mm) / 0.84183).toFixed(1));
}

export function unitToPx(px, unit) {
  const setting = this.$dataStore.get("setting");
  if (!unit) {
    unit = setting.unit;
  }
  if (unit === "mm") {
    px = Number((px / 0.84183).toFixed(1));
  } else if (unit === "inch") {
    px = Number((px / 0.84183) * 25.4).toFixed(1);
  }
  return px;
}

/**
 * @description: 计算出当前裁切区域的位置坐标
 * @param {* fabric.canvas 实例化} canvas
 * @param {* 是否是滚轮} mousewheel
 */
export const cutArea = (canvasEl, mousewheel) => {
  if (!canvasEl.cutCanvas) {
    canvasEl.cutCanvas = document.createElement("canvas");
    canvasEl.cutCanvas.id = `${canvasEl.id}_cut`;
  }

  canvasEl.cutCanvas.width = canvasEl.width;
  canvasEl.cutCanvas.height = canvasEl.height;
  canvasEl.cutCanvas.cssText = `position:absolute;top:0;left:0;width:${canvasEl.width}px;height:${canvasEl.height}px`;

  let cutCtx = canvasEl.cutCanvas.getContext("2d");

  cutCtx.fillStyle = "#f0f2f5";
  cutCtx.fillRect(0, 0, canvasEl.width, canvasEl.height);

  let {
    left,
    top,
    width,
    height,
    boundaryLeft,
    boundaryTop,
    boundaryWidth,
    boundaryHeight,
  } = getRealBoundary(canvasEl, mousewheel);

  //存储正方形边界
  canvasEl.set({
    boundaryLeft,
    boundaryTop,
    boundaryWidth,
    boundaryHeight,
  });

  cutCtx.clearRect(boundaryLeft, boundaryTop, boundaryWidth, boundaryHeight);
  //设置阴影
  cutCtx.save();
  cutCtx.strokeStyle = "#3d47bf";
  cutCtx.shadowColor = "rgba(0,0,0,1)";
  cutCtx.shadowOffsetX = 0;
  cutCtx.shadowOffsetY = 0;
  cutCtx.shadowBlur = 10;
  cutCtx.strokeRect(boundaryLeft, boundaryTop, boundaryWidth, boundaryHeight);

  cutCtx.restore();
  cutCtx.strokeStyle = "#f44";
  cutCtx.strokeRect(left, top, width, height);

  var diy = document.getElementById(canvasEl.id);
  insertAfter(canvasEl.cutCanvas, diy);

  canvasEl.set({
    cutWidth: width,
    cutHeight: height,
  });

  //设置蒙版图片
  if (canvasEl.mask_url) {
    if (!canvasEl.maskDiv) {
      canvasEl.maskDiv = document.createElement("div");
      canvasEl.maskDiv.className = "foxpsd_mask"; //网格图片位置
      // canvasEl.maskDiv.id = canvasEl.id +'_img' //网格图片位置

      canvasEl.maskDiv.style.pointerEvents = "none";
      canvasEl.maskDiv.style.position = "absolute";
      canvasEl.maskDiv.style.textAlign = "center";

      let mask_img = document.createElement("img");
      mask_img.id = canvasEl.id + "_img";
      mask_img.src = canvasEl.mask_url;
      mask_img.style.position = "absolute";
      mask_img.style.left = "50%";
      mask_img.style.top = "50%";
      mask_img.style.transform = "translate(-50%,-50%)";
      mask_img.style.maxWidth = "100%";
      mask_img.style.maxHeight = "100%";
      mask_img.style.display = "inline-block";
      canvasEl.maskDiv.appendChild(mask_img);
      insertAfter(
        canvasEl.maskDiv,
        document.getElementById(canvasEl.cutCanvas.id),
      );
    }

    canvasEl.maskDiv.style.width = `${boundaryWidth}px`;
    canvasEl.maskDiv.style.height = `${boundaryHeight}px`;
    canvasEl.maskDiv.style.top = `${boundaryTop}px`;
    canvasEl.maskDiv.style.left = `${boundaryLeft}px`;
  }
};

//
export function initCrop() {
  var canvas = document.createElement("canvas");
  const grid = store.state.grid[store.state.systemSetting.gridValue];
  canvas.width = grid.w;
  canvas.height = grid.h;
  canvas.style.width = grid.w + "px";
  canvas.style.height = grid.h + "px";
  canvas.style.background = "transparent";
  canvas.style.position = "absolute";
  canvas.style.left = "5%";
  canvas.style.top = "50%";
  canvas.style.transform = "translate(0, -50%)";

  console.log(115, canvas);
  cutArea(canvas);
}

// 获得裁切区域边界
const getRealBoundary = function(canvasEl, mousewheel) {
  //剪切区域的最大高度 和宽度
  let maxBili = 0.75;
  let maxWidth = canvasEl.width * maxBili;
  let maxHeight = canvasEl.height * maxBili;

  if (maxWidth > maxHeight) {
    maxWidth = maxHeight;
  } else {
    maxHeight = maxWidth;
  }

  let cutWidth, cutHeight;

  let plateRATIO = canvasEl.origWidth / canvasEl.origHeight;

  if (!mousewheel) {
    if (maxHeight * plateRATIO < maxWidth) {
      cutWidth = maxHeight * plateRATIO;
      cutHeight = maxHeight;
    } else {
      cutWidth = maxWidth;
      cutHeight = maxWidth / plateRATIO;
    }
    //oldCutWidth 第一次的剪切宽度
    if (!canvasEl.oldCutWidth) {
      canvasEl.set({
        oldCutWidth: cutWidth,
        oldCutHeight: cutHeight,
      });
    }
  }

  let zoom = canvasEl.getZoom();
  let x = canvasEl.viewportTransform[4];
  let y = canvasEl.viewportTransform[5];
  let left, top, width, height;

  if (mousewheel) {
    //根据原始的尺寸进行处理，zoom 是根据原始比例进行的缩放
    left = (canvasEl.width * zoom - canvasEl.oldCutWidth * zoom) / 2 + x;
    top = (canvasEl.height * zoom - canvasEl.oldCutHeight * zoom) / 2 + y;
    width = canvasEl.oldCutWidth * zoom;
    height = canvasEl.oldCutHeight * zoom;
  } else {
    //第一次
    left = (canvasEl.width - cutWidth) / 2;
    top = (canvasEl.height - cutHeight) / 2;
    width = cutWidth;
    height = cutHeight;
  }

  let boundaryLeft, boundaryTop, boundaryWidth, boundaryHeight;

  boundaryWidth = width > height ? width : height;
  boundaryHeight = boundaryWidth;

  boundaryLeft = left - (boundaryWidth - width) / 2;
  boundaryTop = top - (boundaryHeight - height) / 2;

  return {
    plateRATIO,
    left,
    top,
    width,
    height,
    boundaryLeft,
    boundaryTop,
    boundaryWidth,
    boundaryHeight,
  };
};

//插入元素
function insertAfter(newElement, targetElement) {
  // newElement是要追加的元素 targetElement 是指定元素的位置
  if (!targetElement) return;
  var parent = targetElement.parentNode; // 找到指定元素的父节点
  if (parent.lastChild == targetElement) {
    // 判断指定元素的是否是节点中的最后一个位置 如果是的话就直接使用appendChild方法
    parent.appendChild(newElement, targetElement);
  } else {
    parent.insertBefore(newElement, targetElement.nextSibling);
  }
}

export function extractValue(str) {
  // console.log(238, str);

  // 如果字符串不包含分隔符，返回空字符串
  if (!str.includes("_")) return "";
  if (str.includes("_A_")) return "A";
  if (str.includes("_B_")) return "B";
}

export function getImgTitle(imageResList) {
  return imageResList
    .map((el, index) => {
      el.designId = el.designId || index;
      el.title = extractValue(el.designId);
      return el;
    })
    .sort((a, b) => {
      const titleA = a.title;
      const titleB = b.title;

      // 检查是否为空值（null、undefined、空字符串）
      const isEmptyA = titleA === null || titleA === undefined || titleA === "";
      const isEmptyB = titleB === null || titleB === undefined || titleB === "";

      // 处理空值情况（空值排在最后）
      if (isEmptyA && isEmptyB) return 0; // 两个都为空，保持原顺序
      if (isEmptyA) return 1; // A为空，B不为空，A排在后面
      if (isEmptyB) return -1; // B为空，A不为空，B排在后面

      // 处理非空值比较（不区分大小写）
      const valueA = typeof titleA === "string" ? titleA.toUpperCase() : titleA;
      const valueB = typeof titleB === "string" ? titleB.toUpperCase() : titleB;

      // 升序比较（A-Z）
      if (valueA < valueB) return -1;
      if (valueA > valueB) return 1;
      return 0;
    });
}

/**
 * 毫米(mm) 转换为 像素(px) 工具函数
 * 换算标准：遵循打印/设计行业标准 1英寸 = 25.4mm，固定使用每一个网格42px的进行计算
 * @param {number|string} mm - 待转换的毫米数值
 * @returns {number} 转换后的像素值，保留1位小数
 */
export function newMmToPxFn(mm) {
  const px = (Number(mm) / 25.4) * 42;
  return Number(px.toFixed(1));
}
