<script>
import VueDragResizeRotate from "@minogin/vue-drag-resize-rotate";
import PicScrollbarBox from "../../../components/PicScrollbarBox.vue";
const { ipcRenderer } = require("electron");
import { grid } from "../data";
import ImgSetting from "./imgSetting.vue";
import bus from "@/bus";
import PrintDialog from "@/views/design/head/printDialog.vue";
import { mmToPx } from "@/utils";
// import { raw } from "express";
const path = require("path");
const fs = require("fs");
const uuid = require("uuid");
import { startLoading, endLoading } from "@/utils/axios.js";

import { mapState } from "vuex";
const img = require("../../../assets/bg_tshirt_shadow.png");

export default {
  components: {
    PrintDialog,
    VueDragResizeRotate,
    ImgSetting,
    PicScrollbarBox,
  },
  destroyed() {
    document.removeEventListener("keyup", this.keyup);
    document.removeEventListener("dragover", this.dragover);
    document.removeEventListener("drop", this.drop);
  },
  created() {
    ipcRenderer.on("window-size", (event, size) => {
      const { width, height } = size;
      console.log(`接收到窗口尺寸：${width}x${height}`);
      let proportion;
      if (height > 1000) {
        proportion = 1.7;
      } else if (height > 900 && height <= 1000) {
        proportion = 1.5;
        this.PreViewGrid.h;
      } else {
        proportion = 1;
      }
      this.$store.commit("setWHproportion", proportion);
      this.grid[0].h = 540 * proportion;
      this.grid[0].w = 480 * proportion;
    });
  },
  computed: {
    gridWH() {
      if (
        !this.systemSetting ||
        !this.grid ||
        !this.grid[this.systemSetting.gridValue]
      )
        return { w: 0, h: 0, v: 1 };
      return {
        w: this.grid[this.systemSetting.gridValue].w,
        v: this.grid[this.systemSetting.gridValue].value,
        h: this.grid[this.systemSetting.gridValue].h,
      };
    },
    gridSpacing() {
      const { unit, gridSpacing } = this.systemSetting;
      if (!this.systemSetting || !Object.keys(this.systemSetting).length)
        return { w: 0, h: 0 };
      if (unit === "mm") {
        return {
          w: gridSpacing + "px",
          h: gridSpacing + "px",
        };
      } else if (unit === "inch") {
        let w = this.grid[this.systemSetting.gridValue].w;
        let row = this.grid[this.systemSetting.gridValue].row;
        let col = this.grid[this.systemSetting.gridValue].col;
        let h = this.grid[this.systemSetting.gridValue].h;
        return {
          // w: gridSpacing * ((w - row + 1) / row) + "px",
          w: gridSpacing * (w / row) + "px",
          h: gridSpacing * (h / col) + "px",
        };
      }
      return { w: "480px", h: "540px" };
    },
    viewGridSpacing() {
      const { unit, gridSpacing } = this.systemSetting;
      if (!this.systemSetting || !Object.keys(this.systemSetting).length)
        return { w: 0, h: 0 };
      if (unit === "mm") {
        return {
          w: gridSpacing + "px",
          h: gridSpacing + "px",
        };
      } else if (unit === "inch") {
        let w = 480;
        let row = 16;
        let col = 18;
        let h = 540;
        return {
          w: gridSpacing * (w / row) + "px",
          h: gridSpacing * (h / col) + "px",
        };
      }
      return { w: "480px", h: "540px" };
    },
    computedGridSize() {
      const getter = this.systemSetting;
      const num = getter.gridSpacing.slice(0, 2);
      return 10 + "px";
    },

    returnItem() {
      if (this.selectIndex < 0 && this.imgList.length) {
        // this.showImgSetting = false;
        this.selectIndex = 0;
      }
      let item = this.imgList[this.selectIndex];
      if (item) {
        item = JSON.parse(JSON.stringify(item));
        item.x = Number(item.x) - Number(item.w);
        item.y = Number(item.y) + Number(item.h) / 2;
        return JSON.parse(JSON.stringify(this.imgList[this.selectIndex]));
      }
      this.showImgSetting = false;
      return null;
    },

    ...mapState(["desktopDevice", "productDetail", "WHproportion"]),
  },
  data() {
    return {
      actionList: [],
      checkList: [],
      oldImgList: [],
      hasSize: false,
      parentWidth: 0,
      backColor: "#77797a",
      systemSetting: {},
      detail: {},
      imgHeight: 0,
      selectImgList: [],
      bus: 0,
      grid,
      PreViewGrid: {
        label: "16×18",
        value: 1,
        row: 16,
        col: 18,
        h: 540,
        w: 480,
      },
      showImgSetting: true,
      printDialogShow: true,
      parentHeight: 0,
      width: 0,
      selectIndex: -1,
      height: 0,
      x: 0,
      y: 0,
      imgList: [],
      viewImgList: [],
      selectImgIndexList: [],
      isView: false,
      imgHistoryList: [[]],
      imgHistoryIndex: 0,
      row: 8,
      img,
      col: 7,
    };
  },
  watch: {
    imgList: {
      handler(newValue) {
        // console.log(169, newValue);

        if (this.imgList.length > 0) {
          this.$nextTick(() => {
            let dom = document.getElementsByClassName("drr");
            // console.log("dom", dom);

            this.imgList.forEach((el, i) => {
              let dom_i = document.getElementsByClassName("drr")[i];
              dom_i.style.zIndex =
                dom_i.style.zIndex === "" || !dom_i.style.zIndex
                  ? 0
                  : dom_i.style.zIndex;
              dom[i].addEventListener("click", (e) => {
                this.selectIndex = i;
                this.selectItem(i);
              });
            });
          });
        }
        this.$store.commit("changeImgList", this.imgList);
      },
      deep: true,
      immediate: true,
    },
    selectIndex() {
      if (this.selectIndex >= 0) {
        if (!this.showImgSetting) {
          this.showImgSetting = true;
        }
      } else {
        this.showImgSetting = false;
      }
    },
    desktopDevice(newValue, oldValue) {
      if (newValue == 2) {
        this.imgList = [];
        this.selectImgList = [];
        this.selectIndex = -1;
        this.selectImgIndex = 0;
      }
    },
    productDetail(newValue) {
      this.detail = { ...newValue };
      if (typeof this.detail.imageAry == "string") {
        this.detail.imageAry = JSON.parse(this.detail.imageAry);
      }
    },
    changeCheckFn(value) {
      console.log("check", value);
    },
  },
  methods: {
    changePrintDialogShow() {
      this.printDialogShow = !this.printDialogShow;
    },
    async drop(e) {
      let that = this;
      e.stopPropagation();
      //阻止浏览器默认打开文件的操作
      e.preventDefault();
      console.log(e);
      const files = e.dataTransfer.files;
      if (files.length === 0) return;
      for (let i = 0; i < files.length; i++) {
        if (files[i].type !== "image/png") {
          return that.$message.warning("只能上传png格式文件");
        }
        let formData = new FormData();
        formData.append("file", files[i]);
        let { data } = await that.$api.post("/uploadImage", formData, {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        });
        that.selectImgIndex = 0;
        that.addFile(data, (file) => {
          that.imgHistoryList.push(JSON.parse(JSON.stringify(that.imgList)));
        });
      }
    },
    dragover(e) {
      e.stopPropagation();
      //阻止浏览器默认打开文件的操作
      e.preventDefault();
      e.dataTransfer.dropEffect = "copy";
    },
    keyup(e) {
      console.log(e);
      if (e.keyCode == 90 && e.ctrlKey) {
        let i = this.imgHistoryList.length - (2 + this.imgHistoryIndex);
        if (this.imgHistoryList[i]) {
          this.imgList = JSON.parse(JSON.stringify(this.imgHistoryList[i]));
          this.imgHistoryIndex = this.imgHistoryIndex + 1;
        }
      }
      if (this.selectIndex >= 0) {
        if (e.keyCode === 38) {
          //上
          this.$set(
            this.imgList[this.selectIndex],
            "y",
            Number(this.imgList[this.selectIndex].y) - 1
          );
          this.imgHistoryList.push(JSON.parse(JSON.stringify(this.imgList)));
        }
        if (e.keyCode === 40) {
          //下
          this.$set(
            this.imgList[this.selectIndex],
            "y",
            Number(this.imgList[this.selectIndex].y) + 1
          );
          this.imgHistoryList.push(JSON.parse(JSON.stringify(this.imgList)));
        }
        if (e.keyCode === 37) {
          //左
          this.$set(
            this.imgList[this.selectIndex],
            "x",
            Number(this.imgList[this.selectIndex].x) - 1
          );
          this.imgHistoryList.push(JSON.parse(JSON.stringify(this.imgList)));
        }
        if (e.keyCode === 39) {
          //右
          this.$set(
            this.imgList[this.selectIndex],
            "x",
            Number(this.imgList[this.selectIndex].x) + 1
          );
          this.imgHistoryList.push(JSON.parse(JSON.stringify(this.imgList)));
        }
      }
      if (e.keyCode === 8) {
        if (this.selectIndex >= 0) {
          this.imgList.splice(this.selectIndex, 1);
          if (this.imgList.length > 0) {
            this.selectIndex = 0;
          } else {
            this.selectIndex = -1;
          }
        }
      }
    },

    indexChange(v) {
      console.log(v);
      if (this.imgList.length === 0) return;
      let index = !this.imgList[this.selectIndex] ? 0 : this.selectIndex;

      let item = this.$store.state.actionList[v];
      if (!item) return;

      if (item.t === "drag") {
        this.$set(this.imgList[index], "x", item.x);
        this.$set(this.imgList[index], "y", item.y);
      } else if (item.t === "resize") {
        this.$set(this.imgList[index], "x", item.x);
        this.$set(this.imgList[index], "y", item.y);
        this.$set(this.imgList[index], "w", item.w);
        this.$set(this.imgList[index], "h", item.h);
      }
    },
    getOneMmsPx() {
      // 创建一个1mm宽的元素插入到页面，然后坐等出结果
      let div = document.createElement("div");
      div.id = "mm";
      div.style.width = "1mm";
      document.querySelector("body").appendChild(div);
      // 原生方法获取浏览器对元素的计算值
      let mm1 = document.getElementById("mm").getBoundingClientRect();

      return mm1.width;
    },
    setDesignImg(title) {
      let img = this.selectImgList.find((it) => it.title === title);
      if (img) {
        console.log(this.detail.designImageSize, "this.detail.size");
        this.getBackFile(
          { files: [img], size: this.detail.designImageSize },
          (file) => {
            this.imgHistoryList.push(JSON.parse(JSON.stringify(this.imgList)));
          }
        );
      }
    },
    selectImg(it, i) {
      if (this.isView) {
        return;
      }
      // this.selectImgIndexList.push(i)
      let item = this.imgList.find((img) => img.fileName === it.fileName);
      if (item) return;
      console.log(this.detail.designImageSize);
      let size = null;
      if (this.detail.mssWidth && this.detail.mssHeight) {
        size = {
          width: this.detail.mssWidth,
          height: this.detail.mssHeight,
        };
      }
      // this.selectImgIndexList = Array.from(new Set(this.selectImgIndexList))
      this.getBackFile({ files: [it], size }, (file) => {
        this.imgHistoryList.push(JSON.parse(JSON.stringify(this.imgList)));
      });
    },
    ev(type) {
      if (this.selectIndex < 0 && this.imgList.length) {
        this.selectIndex = 0;
      }
      // if (this.selectIndex === -1) this.selectIndex = 0
      if (!this.imgList[this.selectIndex]) return;

      let w = document.getElementById("line").clientWidth / 2;
      let h = document.getElementById("line").clientHeight / 2;
      let dom = document.getElementsByClassName("drr")[this.selectIndex];
      let z_index;
      if (dom) {
        z_index =
          dom.style.zIndex === "" || !dom.style.zIndex ? 0 : dom.style.zIndex;
      }

      switch (type) {
        case "center":
          this.$set(this.imgList[this.selectIndex], "x", Number(w));
          this.$set(this.imgList[this.selectIndex], "y", Number(h));
          this.imgHistoryList.push(JSON.parse(JSON.stringify(this.imgList)));
          break;
        case "x_center":
          this.$set(this.imgList[this.selectIndex], "x", Number(w));
          this.imgHistoryList.push(JSON.parse(JSON.stringify(this.imgList)));
          break;
        case "y_center":
          this.$set(this.imgList[this.selectIndex], "y", Number(h));
          this.imgHistoryList.push(JSON.parse(JSON.stringify(this.imgList)));
          break;
        case "add_index":
          dom.style.zIndex = Number(z_index) + 1;
          console.log(dom.style.zIndex);
          this.$set(
            this.imgList[this.selectIndex],
            "zIndex",
            this.imgList[this.selectIndex].zIndex + 1
          );
          this.imgHistoryList.push(JSON.parse(JSON.stringify(this.imgList)));
          break;
        case "reduce_index":
          dom.style.zIndex = Number(z_index) - 1;
          console.log(dom.style.zIndex);
          this.$set(
            this.imgList[this.selectIndex],
            "zIndex",
            this.imgList[this.selectIndex].zIndex - 1
          );
          this.imgHistoryList.push(JSON.parse(JSON.stringify(this.imgList)));
          break;
        default:
          break;
      }
    },
    formChange(form) {
      // if (this.selectIndex === -1) this.selectIndex = 0
      if (!this.imgList[this.selectIndex]) return;
      let f = JSON.parse(JSON.stringify(form));
      let x_mm = f.x;
      let w_mm = f.w;
      let h_mm = f.h;
      let y_mm = f.y;
      this.$set(this.imgList[this.selectIndex], "x", x_mm);
      this.$set(this.imgList[this.selectIndex], "y", y_mm);
      this.$set(this.imgList[this.selectIndex], "w", w_mm);
      this.$set(this.imgList[this.selectIndex], "h", h_mm);
      this.$set(this.imgList[this.selectIndex], "r", f.r);
      this.$set(this.imgList[this.selectIndex], "zIndex", f.zIndex);
      this.imgHistoryList.push(JSON.parse(JSON.stringify(this.imgList)));
    },
    close() {
      this.showImgSetting = false;
    },
    dragStop(data, item) {
      this.$set(item, "y", data.y);
      this.$set(item, "x", data.x);
      this.imgHistoryList.push(JSON.parse(JSON.stringify(this.imgList)));
    },
    resizeStop(data, item) {
      if (this.selectIndex < 0 && this.imgList.length) this.selectIndex = 0;
      this.$set(item, "y", data.y);
      this.$set(item, "w", data.w);
      this.$set(item, "h", data.h);
      this.$set(item, "x", data.x);
      this.imgHistoryList.push(JSON.parse(JSON.stringify(this.imgList)));
    },
    resizing(index) {},
    rotating(data, item) {
      console.log(data);
      this.$set(item, "r", data.angle.toFixed(2));
      this.imgHistoryList.push(JSON.parse(JSON.stringify(this.imgList)));
    },
    outsideClick(e) {
      if (
        !(
          e.target.className.includes("drr") ||
          e.target.className.includes("sucaitu-img")
        )
      ) {
        this.selectIndex = -1;
        this.close();
      }
    },
    selectItem(index) {
      let dom = document.getElementsByClassName("drr");
      console.log("dom", dom);

      for (let i = 0; i < dom.length; i++) {
        if (index !== i) {
          dom[i].classList.remove("active");
          dom[i].classList.add("inactive");
        }
      }
      this.selectIndex = index;
    },
    deSelect(index) {
      console.log(index, 222222222);
      this.close();
      this.selectIndex = -1;
    },
    delImg(index) {
      console.log(index, "index");
      this.imgList.splice(index, 1);
      if (this.imgList.length > 0) {
        this.selectIndex = 0;
        this.showImgSetting = true;
      } else {
        this.selectIndex = -1;
      }
      this.imgHistoryList.push(JSON.parse(JSON.stringify(this.imgList)));
    },
    fileToBase64(file) {
      return new Promise((resolve, reject) => {
        // 创建一个新的 FileReader 对象
        const reader = new FileReader();
        // 读取 File 对象
        reader.readAsDataURL(file);
        // 加载完成后
        reader.onload = function() {
          // 将读取的数据转换为 base64 编码的字符串
          const base64String = reader.result;
          // 解析为 Promise 对象，并返回 base64 编码的字符串
          resolve(base64String);
        };

        // 加载失败时
        reader.onerror = function() {
          reject(new Error("Failed to load file"));
        };
      });
    },
    getComputedName(title) {
      let img = this.selectImgList.find(
        (it) => it.title === title || it.title.includes(title)
      );
      return img?.designId;
    },
    getComputedTitle(title) {
      console.log(this.selectImgList, "this.selectImgList");
      let img = this.selectImgList.find(
        (it) => it.title === title || it.title.includes(title)
      );
      return img?.productionFile;
    },
    getBackFile({ files, size }, callback) {
      let that = this;
      let bw = document.getElementById("line");
      bw = bw.clientWidth;

      // bw = Number(bw.replace("px", ""));
      for (let i = 0; i < files.length; i++) {
        files[i].url = files[i].productionFile || files[i].url;
        that.$nextTick(async () => {
          let w = bw / 2;
          let width_px, height_px, rate, x, y;
          if (size) {
            width_px = that.WHproportion * mmToPx(size.width);
            height_px = that.WHproportion * mmToPx(size.height);
            x = w * that.WHproportion;
            y = (height_px / 2) * that.WHproportion;
            rate = height_px / width_px;
          } else {
            let data = await that.getImageSize(files[i].url);
            rate = data.height / data.width;
            width_px = bw * (2 / 3);
            x = w;
            y = height_px / 2;
            height_px = width_px * rate;
          }

          that.imgList = [];
          that.imgList.push({
            url: files[i].url,
            fileName: files[i].fileName,
            rate,
            w: width_px,
            zIndex: that.imgList.length,
            x,
            y,
            h: height_px,
            r: 0,
          });
          that.selectIndex = that.imgList.length - 1;
          that.showImgSetting = true;
          that.$nextTick(() => {
            that.ev("center");
          });
          if (i === files.length - 1) {
            callback && callback();
          }
        });
      }
    },
    addFile(file, callback) {
      let that = this;
      let bw = document.getElementById("line").clientWidth;
      let bh = document.getElementById("line").clientHeight;
      that.$nextTick(() => {
        that.getImageSize(file.url).then((data) => {
          let w = document.getElementById("line").clientWidth / 2;
          let rate = data.height / data.width;
          that.imgList = [];
          that.imgList.push({
            url: file.url,
            w: bw * (2 / 3),
            rate,
            fileName: file.fileName,
            zIndex: that.imgList.length,
            x: w,
            y: (bw * (2 / 3) * rate) / 2,
            h: bw * (2 / 3) * rate,
            r: 0,
          });
          console.log(570, that.imgList);
          that.selectIndex = that.imgList.length - 1;
          that.showImgSetting = true;
          callback && callback(file);
        });
      });
    },
    listenUpload() {
      // let that = this;
      // document.getElementById("img").onmousedown = function(e) {
      //   e.preventDefault();
      // };
      // that.parentWidth = document.getElementById("img").clientWidth;
      // that.parentHeight = document.getElementById("img").clientHeight;
      // let dp = document.getElementsByClassName("container")[0];
      // dp.addEventListener("dragover", this.dragover);
      // dp.addEventListener("drop", this.drop);
    },
    getImageSize(url) {
      return new Promise(function(resolve, reject) {
        let image = new Image();
        image.onload = function() {
          resolve({
            width: image.width,
            height: image.height,
          });
        };
        image.onerror = function() {
          reject(new Error("error"));
        };
        image.src = url;
      });
    },

    /**
     * 根据主题颜色修改图片颜色
     * @param  {[type]}   imgUrl    图片url
     * @param  {[type]}  color 主题颜色
     * @param  {Function} callback  返回值 返回base64
     */
    changeImageColor(color = "#00ff7f", callback) {
      let threshold = 114; //默认颜色阀值 为 114 －>和默认图相关
      let img = new Image();
      img.src = require("../../../assets/bg_tshirt_shadow.png");
      let newR = parseInt("0x" + color.substr(1, 2));
      let newG = parseInt("0x" + color.substr(3, 2));
      let newB = parseInt("0x" + color.substr(5, 2));
      //图片加载后进行处理
      img.onload = function() {
        let width = img.width,
          height = img.height,
          canvas = document.createElement("canvas"),
          ctx = canvas.getContext("2d");
        canvas.width = width;
        canvas.height = height;
        // 将源图片复制到画布上
        ctx.drawImage(img, 0, 0, width, height);
        // 获取画布的像素信息
        let imageData = ctx.getImageData(0, 0, width, height),
          data = imageData.data;
        // 对像素集合中的单个像素进行循环，每个像素是由4个通道组成，所以要注意
        let i = 0;
        while (i < data.length) {
          let r = data[i++],
            g = data[i++],
            b = data[i++],
            a = data[i++];
          //计算透明度
          let alp = (255 - r) / (255 - threshold);
          //判断是否透明
          let isTransparent = r == 255 && g == 255 && b == 255 && a == 255;
          if (isTransparent) {
            data[i - 1] = 0;
          } else {
            data[i - 4] = newR;
            data[i - 3] = newG;
            data[i - 2] = newB;
            data[i - 1] = a !== 255 ? 255 - a : alp * 255; //处理透明的图片和不透明的图片
          }
        }
        // 将修改后的代码复制回画布中
        ctx.putImageData(imageData, 0, 0);
        // 图片导出为 png 格式
        let imgType = "png";
        let imgData = canvas.toDataURL(imgType);

        callback && callback(imgData);
      };
      return img;
    },

    async cutImgFn() {
      if (!this.checkList?.length) return;

      if (this.detail.mssHeight && this.detail.mssWidth) {
        return this.$confirm(`该生产单为直接打印单不可进行裁切！`, "提示", {
          confirmButtonText: "确定",
          showCancelButton: false,
          type: "warning",
        });
      }
      try {
        const processQueue = await Promise.all(
          this.checkList.map(async (el) => {
            try {
              const outputDir = path.dirname(el.productionFile);
              const outputFileName = `${uuid.v4()}.png`;
              const outputPath = path.join(outputDir, outputFileName);
              const params = {
                inputPath: el.productionFile,
                outputPath: outputPath,
              };
              const res = await this.$api.post("/processImage", params);
              fs.unlinkSync(el.productionFile);
              return {
                fileName: outputFileName,
                productionFile: res.msg[0]?.outputPath,
                designId: el.designId,
              };
            } catch (error) {
              console.error(`处理失败: ${el.productionFile}`, error);
            }
          })
        );

        // 等待所有异步操作完成
        await new Promise((resolve) => setTimeout(resolve, 100));
        const newMap = new Map(processQueue.map((el) => [el.designId, el]));
        this.selectImgList.forEach((el) => {
          if (newMap.has(el.designId)) {
            el.fileName = newMap.get(el.designId).fileName;
            el.productionFile = newMap.get(el.designId).productionFile;
          }
        });
        console.log("selectImgList", this.selectImgList);

        if (this.imgList.length) {
          const fileNameExists = this.checkList.some(
            (el) => el.fileName === this.imgList[0].fileName
          );
          if (fileNameExists) {
            this.imgList = [];
            this.selectIndex = -1;
          }
        }

        this.checkList = [];

        this.selectImg(this.selectImgList[0]);
      } catch (error) {
        console.error("错误", error);
      }
    },
    startLoading,
    endLoading,

    handleClick(event) {
      // 获取点击的元素
      let currentElement = event.target;

      // 确保点击的元素在包含 container 类名的元素内
      if (currentElement.closest(".container")) {
        // 如果点击的元素不是 boxShaow，执行方法
        if (!currentElement.closest(".boxShaow") && !this.isView) {
          this.isView = true;
          console.log(723, this.isView);
        }
      }
      if (currentElement.closest(".scrollbarDrawer")) {
        this.isView = false;
      }
      this.$store.commit("setIsPreView", this.isView);
    },
  },
  mounted() {
    this.imgHeight = window.screen.height + "px";
    this.systemSetting = this.$dataStore.get("setting");

    bus.$on("busEmit", (v) => {
      let { type, value, size } = v;

      switch (type) {
        case "grid":
          this.row = value.row;
          this.col = value.col;
          break;
        case "index":
          this.indexChange(value);
          break;
        case "bg":
          this.changeImageColor(value, (res) => {
            this.img = res;
          });
          break;
        case "updateSystemSetting":
          this.systemSetting = this.$dataStore.get("setting");
          break;
        case "uploadImage":
          this.addFile(value, () => {
            this.imgHistoryList.push(JSON.parse(JSON.stringify(this.imgList)));
          });
          break;
        case "sendFile":
          console.log("sendFile");
          if (size) {
            this.hasSize = true;
          } else {
            this.hasSize = false;
          }
          this.detail.designImageSize = size;
          console.log(this.detail, "this.detail");
          this.imgList = [];
          this.selectIndex = -1;
          if (value.length > 0) {
            this.selectImgList = value;
            console.log(816, this.selectImgList);

            this.selectImgIndex = 0;
            this.getBackFile(
              { files: [value[0]], size: this.detail.designImageSize || null },
              (file) => {
                this.imgHistoryList.push(
                  JSON.parse(JSON.stringify(this.imgList))
                );
              }
            );
            // this.addFile([value[0].file])
          }
          break;
        default:
          break;
      }
    });

    document.addEventListener("keyup", this.keyup);
    this.$nextTick(() => {
      this.listenUpload();
    });
    document.addEventListener("click", this.handleClick);
  },
  beforeDestroy() {
    // 销毁组件时移除事件监听器
    document.removeEventListener("click", this.handleClick);
  },
};
</script>

<template>
  <div class="page-main">
    <img-setting
      @ev="ev"
      @change="formChange"
      :item="returnItem"
      @close="close"
    >
      <template #content>
        <div class="information-content">
          <!-- <div
            style="display: flex;justify-content: space-between;flex-wrap: nowrap;"
          >
            <div class="title" style="flex: 1;">
              效果图
            </div>
          </div> -->

          <!-- <el-row class="main">
            <el-col :span="6">
              <div class="text-center">打印区域</div>
            </el-col>

            <el-col :span="9" class="effectPic border-col">
              <div class="pic-title">效果图</div>
            </el-col>

            <el-col :span="9">
              <div class="pic-title">素材图</div>
            </el-col>

            <el-row
              class="border-row"
              v-for="(item, index) in detail.imageAry"
              :key="index"
            >
              <el-col :span="6" class="text-center"
                ><div>{{ item.title }}</div></el-col
              >
              <el-col :span="9" class="border-col text-center">
                <el-carousel
                  v-if="item.viewImgList?.length"
                  height="170px"
                  :autoplay="false"
                  indicator-position="none"
                  style="width: 100%;"
                >
                  <el-carousel-item
                    v-for="(img, i) in item.viewImgList"
                    :key="i"
                  >
                    <img class="full-width" :src="img.url" alt="" />
                  </el-carousel-item>
                </el-carousel>
                <div v-else>&nbsp;</div>
              </el-col>
              <el-col
                :span="9"
                style="overflow: hidden;align-items: stretch;flex-grow: 1"
              >
                <el-carousel
                  v-if="selectImgList?.length"
                  height="220px"
                  :autoplay="false"
                  indicator-position="none"
                  style="width: 100%;"
                >
                  <el-carousel-item v-for="(img, i) in selectImgList" :key="i">
                    <el-checkbox-group v-model="checkList">
                      <el-checkbox
                        :class="{
                          imgchecked: checkList.includes(img),
                        }"
                        :label="img"
                      >
                        <div
                          class="img-item"
                          @click.stop.prevent="selectImg(img, 0)"
                        >
                          <img style="width: 140px" :src="img.productionFile" />
                          <span>{{ img.designId }}</span>
                        </div>
                      </el-checkbox></el-checkbox-group
                    >
                  </el-carousel-item>
                </el-carousel>
              </el-col>
            </el-row>
          </el-row> -->
          <!-- <el-table
            style="margin: 5px;width: auto;"
            border
            :data="detail.imageAry"
            :header-cell-style="{ 'text-align': 'center' }">
            <el-table-column align="center" label="打印区域"
              prop="title"
              align="center"
              width="100px"
            ></el-table-column>
            <el-table-column align="center" label="效果图" prop="title">
              <template slot-scope="{row}">
                <img class="full-width" :src="row.url" alt="" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="素材图" prop="title">
              <template slot-scope="{ row }">
                <img
                  style="cursor: pointer"
                  @click="setDesignImg(row.title)"
                  v-if="getComputedTitle(row.title)"
                  class="full-width"
                  :src="getComputedTitle(row.title)"
                  alt=""
                />
                <span>{{ getComputedName(row.title) }}</span>
              </template>
            </el-table-column>
          </el-table> -->
          <PicScrollbarBox
            boxTitle="效果图"
            emptyTitle="效果图为空"
            style="border-bottom: 1px solid #ececec;"
          >
            <template #mainContent v-if="detail.imageAry?.length">
              <div style="display: flex;flex-wrap: nowrap;width: 100%;">
                <div
                  v-for="(img, index) in detail.imageAry"
                  :key="index"
                  class="img-item"
                  style="width: 50%;"
                >
                  <img width="150px" :src="img.url" />
                </div>
              </div>
            </template>
          </PicScrollbarBox>
          <PicScrollbarBox boxTitle="素材图" emptyTitle="素材图为空">
            <template #titleRight>
              <el-button
                type="primary"
                size="small"
                style="margin: 10px;"
                @click="cutImgFn"
                >裁切</el-button
              >
            </template>
            <template #mainContent>
              <el-checkbox-group
                v-if="selectImgList.length"
                v-model="checkList"
                style="display: flex;flex-wrap:nowrap;width: 100%;"
              >
                <el-checkbox
                  v-for="img in selectImgList"
                  :key="img.designId"
                  :class="{
                    imgchecked: checkList.includes(img),
                  }"
                  :label="img"
                >
                  <div class="img-item" @click.stop.prevent="selectImg(img)">
                    <img style="width:100%" :src="img.productionFile" />
                    <!-- <span>{{ img.designId }}</span> -->
                  </div>
                </el-checkbox></el-checkbox-group
              >
            </template>
          </PicScrollbarBox>
          <!-- <div>
            <div style="display: flex;justify-content: space-between;">
              <div class="title">
                素材图
              </div>
              <el-button
                type="primary"
                size="small"
                style="margin: 10px;"
                @click="cutImgFn"
                >裁切</el-button
              >
            </div>
            <el-scrollbar class="scrollbarBox">
              <el-checkbox-group
                v-if="selectImgList.length"
                v-model="checkList"
                style="display: flex;flex-wrap:nowrap"
              >
                <el-checkbox
                  v-for="img in selectImgList"
                  :key="img.designId"
                  :class="{
                    imgchecked: checkList.includes(img),
                  }"
                  :label="img"
                >
                  <div class="img-item" @click.stop.prevent="selectImg(img)">
                    <img style="width: 140px" :src="img.productionFile" />
                    <span>{{ img.designId }}</span>
                  </div>
                </el-checkbox></el-checkbox-group
              >
              <el-empty v-else description="没有素材"></el-empty>
            </el-scrollbar>
          </div> -->
        </div>
        <div class="product-information">
          <div class="title">
            生产单信息
          </div>
          <div class="div-content">
            <div :title="detail.podProductionNo" class="div-item">
              <div class="item-label">生产单号：</div>
              <div class="item-value">
                {{ detail.factorySubOrderNumber }}
                <div
                  style="margin-left: 5px"
                  v-if="detail.podProductionNo"
                  :style="{
                    color: detail.customizedQuantity > 1 ? 'red' : '#67C23A',
                  }"
                >
                  {{ detail.customizedQuantity > 1 ? "多" : "单" }}
                </div>
              </div>
            </div>
            <div :title="detail.factorySubOrderNumber" class="div-item">
              <div class="item-label">工厂单号：</div>
              <div class="item-value">{{ detail.factorySubOrderNumber }}</div>
            </div>
            <div :title="detail.processName" class="div-item">
              <div class="item-label">生产工艺：</div>
              <div class="item-value">{{ detail.processName }}</div>
            </div>
            <div :title="detail.baseSku" class="div-item">
              <div class="item-label">基版：</div>
              <div class="item-value">{{ detail.baseSku }}</div>
            </div>
            <div :title="detail.size" class="div-item">
              <div class="item-label">尺寸：</div>
              <div class="item-value">{{ detail.size }}</div>
            </div>
            <div :title="detail.variantSku" class="div-item">
              <div class="item-label">变体SKU：</div>
              <div class="item-value">{{ detail.variantSku }}</div>
            </div>
            <div :title="detail.num" class="div-item">
              <div class="item-label">数量：</div>
              <div class="item-value">{{ detail.num }}</div>
            </div>
            <div :title="detail.supplierItemNo" class="div-item">
              <div class="item-label">货号：</div>
              <div class="item-value">{{ detail.supplierItemNo }}</div>
            </div>
            <div :title="detail.color" class="div-item">
              <div class="item-label">颜色：</div>
              <div class="item-value">
                {{ detail.baseSku ? detail.baseSku.split("_")[1] : null }}
              </div>
            </div>

            <div :title="detail.factoryCode" class="div-item">
              <div class="item-label">工厂：</div>
              <div class="item-value">{{ detail.factoryCode }}</div>
            </div>
            <div
              :title="detail.shopNumber"
              class="div-item"
              style="flex: 100%;"
            >
              <div>
                店铺单号：
              </div>
              <div>
                {{ detail.shopNumber }}
              </div>
            </div>
            <div
              :title="detail.createTime"
              class="div-item"
              style="flex: 100%;"
            >
              <div>创建时间：</div>
              <div>{{ detail.createTime }}</div>
            </div>
            <div
              :title="detail.startStockingTime"
              class="div-item"
              style="flex: 100%;"
            >
              <div>
                生产确认时间：
              </div>
              <div>{{ detail.startStockingTime }}</div>
            </div>
          </div>
        </div>
      </template>
    </img-setting>
    <div
      @click="outsideClick"
      class="main-bg"
      :style="{ 'background-color': !isView ? '#77797a' : '#fff' }"
    >
      <div class="container">
        <div style="width: 100%;height: 100%; ">
          <div v-if="isView" id="img">
            <div
              id="line"
              style="left: 22%;top: 52%;background-color: transparent;overflow: hidden;cursor: none;"
            >
              <div
                class="sucaitu vieWsucaitu"
                :style="{ width: '100%', height: '100%' }"
              >
                <vue-drag-resize-rotate
                  :w="item.w / WHproportion"
                  class-name="my-drag-resize-rotate"
                  :prevent-deactivation="false"
                  :h="item.h / WHproportion"
                  :x="item.x / WHproportion"
                  :z="item.zIndex / WHproportion"
                  :aspectRatio="false"
                  :isActive="false"
                  :y="item.y / WHproportion"
                  v-for="(item, index) in imgList"
                  :key="index"
                  :draggable="false"
                  :resizable="false"
                  :rotatable="false"
                  :angle="item.r / WHproportion"
                  style="pointer-events: auto;cursor: default"
                >
                  <div
                    ref="sucaitu-img"
                    :style="{ zIndex: item.zIndex }"
                    class="sucaitu-img img element"
                    style="cursor: default"
                  >
                    <img
                      crossOrigin="anonymous"
                      :src="item.url"
                      :id="item.fileName + '_' + index"
                      alt=""
                      style="width: 100%;height: 100%"
                      class="sucaitu-img"
                    />
                  </div>
                </vue-drag-resize-rotate>
              </div>
              <div
                :class="{ 'no-border-grid': systemSetting.gridShow !== 1 }"
                :style="{
                  width: 480 + 'px',
                  height: 540 + 'px',
                }"
                class="grid"
                style="border-style:dashed"
              ></div>
            </div>
            <div style="width: 1040px;height: 100%;"></div>
            <!-- <img class="template-img" draggable="false" :src="img" alt="" /> -->
          </div>
          <div
            v-else
            style="width: 100%;height: 100%;background-color:#77797a "
          >
            <div id="line" class="boxShaow">
              <!-- <div
            class="sucaitu"
            :style="{ width: gridWH.w + 'px', height: gridWH.h + 'px' }"
          > -->
              <div class="sucaitu" :style="{ width: '100%', height: '100%' }">
                <vue-drag-resize-rotate
                  :w="item.w"
                  class-name="my-drag-resize-rotate"
                  :prevent-deactivation="false"
                  :h="item.h"
                  :x="item.x"
                  :z="item.zIndex"
                  :aspectRatio="true"
                  :isActive="index === selectIndex"
                  :y="item.y"
                  v-for="(item, index) in imgList"
                  :key="index"
                  :draggable="true"
                  :resizable="true"
                  :rotatable="true"
                  @dragstop="(a) => dragStop(a, item)"
                  @resizestop="(a) => resizeStop(a, item)"
                  @rotatestop="(a) => rotating(a, item)"
                  :angle="item.r"
                >
                  <div
                    ref="sucaitu-img"
                    :class="{ active: index === selectIndex }"
                    :style="{ zIndex: item.zIndex }"
                    class="sucaitu-img img element"
                  >
                    <img
                      crossOrigin="anonymous"
                      :src="item.url"
                      :id="item.fileName + '_' + index"
                      alt=""
                      style="width: 100%;height: 100%"
                      class="sucaitu-img"
                    />
                    <i
                      @click="delImg(index)"
                      v-if="index === selectIndex"
                      class=" close el-icon-close"
                    ></i>
                    <div
                      v-if="index === selectIndex"
                      class="control-point control-rotator"
                    ></div>
                  </div>
                </vue-drag-resize-rotate>
              </div>
              <div
                :class="{ 'no-border-grid': systemSetting.gridShow !== 1 }"
                :style="{
                  width: gridWH.w + 'px',
                  height: gridWH.h + 'px',
                }"
                class="grid"
              >
                <div
                  :style="{ height: gridSpacing.h, lineHeight: gridSpacing.h }"
                  class="grid-row"
                  v-for="it in 100"
                  :key="it"
                >
                  <div
                    :style="{ width: gridSpacing.w, height: gridSpacing.h }"
                    class="grid-col"
                    v-for="it in 100"
                    :key="it"
                  ></div>
                </div>
              </div>
            </div>
          </div>
          <div
            class="print-tip"
            v-if="
              detail &&
                detail.mssWidth &&
                detail.mssHeight &&
                selectImgList.length
            "
          >
            <b style="color: green" v-if="hasSize"
              >该生产单无需拖动设计，直接打印</b
            >
            <b style="color: red" v-else>该生产单需要拖动设计打印</b>
          </div>
        </div>

        <img
          class="template-img"
          draggable="false"
          :src="img"
          alt=""
          style="position: absolute;width: 1000px;left: 3%;height: 100%;"
          :style="{ 'z-index': isView ? '0' : '-1' }"
        />
      </div>
    </div>
    <print-dialog
      :visible="printDialogShow"
      :imgList="imgList"
      :byPlatenSize="gridWH.v"
    >
      <i
        @click="changePrintDialogShow"
        :class="!printDialogShow ? 'el-icon-arrow-left' : 'el-icon-arrow-right'"
      ></i>
    </print-dialog>
  </div>
</template>

<style lang="less" scoped>
.print-tip {
  position: absolute;
  bottom: 16px;
  font-size: 24px;
  left: 20%;
}
.page-main {
  display: flex;
  flex: 1;
  flex-shrink: 0;
  overflow: hidden;
  box-sizing: border-box;
}

.main-bg {
  flex: 1;
  // height: 100%;
  display: flex;

  // align-items: center;
  // justify-content: center;
}

#line {
  position: absolute;
  // z-index: 2;
  left: 5%;
  top: 50%;

  transform: translate(0, -50%);
  background-color: #f0f2f6;
}

.grid {
  border: 1px solid gray;
  overflow: hidden;

  .grid-row {
    .grid-col {
      box-sizing: border-box;

      display: inline-block;
      border: 1px solid gray;
      border-right: none;
      border-bottom: none;
    }
  }
}

.grid-row {
  width: 100%;
  overflow: hidden;
  height: 10px;
  line-height: 10px;
  white-space: nowrap;

  &:nth-of-type(1) {
    .grid-col {
      border-top: none !important;
    }
  }

  &:nth-last-of-type(1) {
    .grid-col {
      border-bottom: none !important;
    }
  }

  .grid-col {
    &:nth-of-type(1) {
      border-left: none !important;
    }
  }
}

#img {
  // position: absolute;
  // z-index: 1;
  // left: 130px;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  // width: auto;
  position: absolute;
  left: 5%;
  img {
    pointer-events: none;
    width: auto;
    height: 100%;
  }
}

.container {
  display: flex;
  width: 100%;
  height: 100%;
  // justify-content: center;
  // align-items: center;
  position: relative;
}

.sucaitu {
  // position: absolute;
  // z-index: 0;
  width: 100%;
  //display: flex;
  //justify-content: center;
  //align-items: center;
  height: 100%;

  img {
    width: 100%;
    height: 100%;
  }

  .close {
    position: absolute;
    top: -11px;
    right: -12px;
    color: white;
    z-index: 1000;
    width: 20px;
    cursor: pointer;
    height: 20px;
    background: red;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .img {
    height: fit-content;
    width: 100%;
    height: 100%;
    cursor: move;
    border: 1px dashed transparent;
  }
}

.select-img {
  border: 1px solid #ececec;
  width: 100%;
  overflow: auto;
  height: calc(100% - 251px);
  padding: 10px;
  box-sizing: border-box;
}

img {
  user-select: none;
  user-drag: none;
}

::v-deep .active,
.active {
  border-color: #66b1ff !important;
}

.select-img-index {
  box-sizing: border-box;
  border-color: #409eff !important;
}

.img-item {
  // height: 150px;
  width: 200px;
  padding: 5px;
  display: flex;
  cursor: pointer;
  // margin-bottom: 20px;
  border: 2px dashed transparent;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  span {
    font-size: 14px;
    // margin: 5px 0;
    width: 100%;
    color: black;
    display: inline-block; /* 使 span 成为块级元素，这样可以设置宽度 */
    // max-width: 270px; /* 限制宽度 */
    word-wrap: break-word; /* 或者使用 overflow-wrap: break-word; */
    white-space: normal; /* 确保正常换行 */
    text-align: center;
  }
}

.sucaitu-img {
  position: relative;
}

.no-border-grid {
  border-color: transparent !important;

  * {
    border-color: transparent !important;
  }
}

.el-checkbox-group {
  height: 100%;
  // border-top: 1px solid #ececec;
  margin-bottom: 25px;
  ::v-deep .el-checkbox {
    height: 100%;
    width: 100%;
    margin: 0;
    box-sizing: border-box;
    border: 1px solid #ffffff;
    margin: 5px;
    // margin-bottom: 5px;
    .el-checkbox__input {
      position: absolute;
      top: 5px;
      left: 5px;
    }
    .el-checkbox__label {
      width: 100%;
      padding: 0;
      height: 100%;
      background-color: #e3e3e3;
    }
  }
}

.imgchecked {
  border: 1px solid #409eff !important;
}
</style>
<style lang="less" scoped>
.el-upload {
  height: 100%;
}

.drr-stick {
  z-index: 9999;
}

.drr-stick-tr {
  z-index: -1 !important;
}

.my-drag-resize-rotate {
  border-color: transparent;
}

.handle-rot::before,
.handle-rot::after {
  display: none;
}
.information-content {
  border: 1px solid #ececec;
  border-top: none;

  .main {
    margin: 5px;
    border: 1px solid #ececec;
    height: 100%;
    .effectPic {
      .img {
        width: 100%;
      }
    }
  }
  .pic-title {
    text-align: center;
  }
}
.product-information {
  border: 1px solid #ececec;
  border-top: none;
  .div-content {
    padding: 0 10px;
    display: flex;
    flex-wrap: wrap;
    .div-item {
      display: flex;
      flex: 50%;
      font-size: 12px;
      margin-bottom: 10px;
      .item-label {
        flex: 1;
        text-align: right;
      }
      .item-value {
        flex: 36%;
      }
    }
  }
}
.title {
  padding: 10px;
  font-size: 20px;
  font-weight: 700;
}
.border-row {
  border-top: 1px solid #ececec;
  // border-bottom: 1px solid #ececec;
  display: flex;
  width: 100%;
  height: 100%;
  // align-items: center;
}
.full-width {
  width: 100%;
}
.text-center {
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}
.border-col {
  border-left: 1px solid #ececec;
  border-right: 1px solid #ececec;
}
.boxShaow {
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2), 0 0 15px rgba(0, 0, 0, 0.14),
    0 0 20px rgba(0, 0, 0, 0.12);
}
.vieWsucaitu {
  .active::before {
    display: none;
  }
  ::v-deep .drr:hover:before {
    outline: none;
  }
}
// ::v-deep.el-table thead {
//   color: black;
// }
</style>
