<script>
import bus from "@/bus";
import { ipcRenderer } from "electron";
import { copySingleImage } from "@/server/utils/index.js";
const moment = require("moment");
const { pathMap } = require("@/config/index.js");

import pkg from "../../../../package.json";
import UpdateDialog from "@/views/design/updateDialog.vue";
import path from "path"; // 引入 path 模块
import axios from "axios";
import { getImgTitle } from "@/utils/index.js";
const uuid = require("uuid");

import { mapState } from "vuex";
const {
  getVersion,
  setVersion,
  getHostApi,
  setDesktopDevice,
  getDesktopDevice,
  getOrderInfoMap,
  getOrderInfoItem,
  addToOrderInfo,
  updateOrderInfoItem,
  removeFromOrderInfo,
  setOrderInfo,
  getLocation,
  setNowDate,
  getNowDate
} = require("@/server/utils/store");

export default {
  components: { UpdateDialog },
  props: {
    user: {
      default: () => ({
        avatar: "",
        factory: {}
      }),
      type: Object
    },
    factoryType: { type: String, default: "CN" }
  },
  data() {
    return {
      checkList: [],
      desktopDevice: getDesktopDevice(),
      desktoVersion: getVersion(),
      checked: false,
      isFirst: true,
      cacheList: [
        {
          label: "清除当前登录信息",
          value: "token"
        },
        {
          label: "登录记录",
          value: "userList"
        },
        {
          label: "打印预设",
          value: "print-setting"
        },
        {
          label: "系统设置",
          value: "setting"
        }
      ],
      selectGridIndex: 0,
      pkg,
      actionIndex: -1,
      isAutoFinish: true,
      isForcedProduction: false,
      cacheVisible: false,
      showPrintDialog: false,
      productionNo: "",
      templateProductionNo: "",
      setting: {
        gridShow: 1,
        gridValue: 0,
        unit: "inch",
        language: "cn",
        autoPrint: false,
        gridSpacing: 1
      },
      detail: null,
      config: getHostApi(),
      newApiApiHost: "",

      selectBgColor: "#ececec",
      predefineColors: [
        "#ff4500",
        "#ff8c00",
        "#ffd700",
        "#90ee90",
        "#00ced1",
        "#1e90ff",
        "#c71585",
        "rgba(255, 69, 0, 0.68)",
        "rgb(255, 120, 0)",
        "hsv(51, 100, 98)",
        "hsva(120, 40, 94, 0.5)",
        "hsl(181, 100%, 37%)",
        "hsla(209, 100%, 56%, 0.73)",
        "#c7158577"
      ],
      faceType: "A",
      dialogVisible: false,
      showforcedProduc: false
    };
  },
  computed: {
    actionList() {
      return this.$store.getters.getActionList;
    },

    ...mapState([
      "defaultProportion",
      "countryList",
      "orderType",
      "grid",
      "imgList"
    ])
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.searchRef?.focus();
      if (this.desktopDevice !== 3) {
        this.selectGridIndex = 0;
        this.setting.gridValue = 0;
      } else {
        this.selectGridIndex = 5;
        this.setting.gridValue = 5;
      }
    });
    this.$store.commit("changeDesktopDevice", getDesktopDevice());
  },
  created() {
    localStorage.setItem("desktoVersion", "print");
    if (this.$dataStore.get("setting")) {
      this.setting = this.$dataStore.get("setting");
    } else {
      this.$dataStore.set("setting", this.setting);
    }
  },
  watch: {
    setting: {
      handler(val) {
        this.$dataStore.set("setting", val);
        bus.$emit("busEmit", { type: "updateSystemSetting" });
      },

      deep: true
    },
    config: {
      handler(val) {
        this.newApiApiHost = this.getDomainFromUrl(val.apiApiHost);
      },
      immediate: true,
      deep: true
    },
    desktopDevice() {
      this.checked = false;
    },
    imgList: {
      //监听当前网格内数据，并把power设置为true
      handler(value) {
        if (this.detail && value?.length && this.desktopDevice === 3) {
          const item = this.detail?.saveImgList?.find(
            el => el.fileName == value[0].fileName
          );
          if (item && !item.power) {
            item.power = true;
            try {
              //复制图片到当前文件夹下
              copySingleImage(
                item.productionFile,
                getLocation("downloadLocation1")
              );
              copySingleImage(
                item.productionFile,
                getLocation("downloadLocation2")
              );
            } catch (error) {
              this.$message.error("发送失败");

              console.log(error);
            }
            //更新数据到本地数据
            updateOrderInfoItem(this.detail.newId, this.detail, this.faceType);
          }
          if (
            this.orderType == "OP" &&
            this.canCompleteProduction(this.detail)
          ) {
            this.setData(this.detail);
          }
          console.log("updateOrderInfoItemitem", item);
          console.log("本地数据updateOrderInfoItem：", getOrderInfoMap());
        }
      }
      // deep: true,
    }
  },
  methods: {
    checkUpdate() {
      this.$refs.updateDialog.checkUpdate().then(data => {
        if (data) {
          // 有新版本更新
          this.$refs.updateDialog.open(data, 2);
        } else {
          this.$message.warning("已是最新版本");
        }
      });
    },
    dropdownCommand(v) {
      switch (v) {
        case "logout":
          this.$confirm("是否退出登录?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              this.$dataStore.delete("user");
              this.$router.push("/");
            })
            .catch(() => {});
          break;

        case "cache":
          this.checkList = [];
          this.cacheVisible = true;
          break;
      }
    },
    // 判断是否可完成生产
    canCompleteProduction(data) {
      if (!data?.saveImgList?.length) return false;
      return data.saveImgList?.every(el => el.power) ?? false;
    },

    async setData(data, type) {
      if (!data) return this.$message.warning("请扫描生产单号/操作单号");

      if (this.desktopDevice == 3 && !this.canCompleteProduction(data)) {
        if (type == "btn") {
          const item = data.saveImgList?.find(el => !el.power);
          this.$message.warning(
            `该订单${item?.title || ""}面未打印，无法生产完成`
          );
        }
        return;
      }

      let params = {
        id: data.id,
        orderType: this.orderType
      };

      if (this.orderType === "CN") {
        params.podJomallOrderCnId = data.podJomallOrderCnId;
      } else if (this.orderType === "US") {
        params.podJomallOrderUsId = data.podJomallOrderUsId;
      } else if (this.orderType === "OP") {
        params.data = { ...data };
      }

      try {
        const isOP = this.orderType === "OP";
        const newId = data.newId;
        console.log("生产完成------", this.orderType, type);
        // 统一走完成交付的场景：非OP / OP且type=btn
        if (!isOP || type === "btn") {
          await this.$api.post(
            pathMap.completeDelivery[this.orderType],
            params
          );
          if (this.desktopDevice === 3) {
            await removeFromOrderInfo(newId);
            bus.$emit("busEmit", { value: newId, type: "completeMessage" });
          }
        } else {
          // OP 非btn：扫码入库校验库存
          const { code, data: resData } = await this.$api.post(
            pathMap.scanProduce[this.orderType],
            { id: params.id, status: params.data.status, type: "app" }
          );
          if (code === 301) {
            this.$confirm(
              `${
                resData.thirdSkuCode
              }库存不足，无法进入生产!请联系仓库管理人员核对库存。</br>
      库存数量：${resData.availableInventory || 0}，
      生产中数量：${resData.inventory || 0}，
      <span style="color: red;">可调配库存：${resData.inventory || 0}</span>`,
              "提示",
              {
                confirmButtonText: "确定",
                type: "error",
                dangerouslyUseHTMLString: true,
                customClass: "custom-inventory-msgbox"
              }
            );
            this.detail = "";
            this.productionNo = "";
            this.$refs.searchRef?.focus();
            return;
          }
          this.desktopDevice === 3 &&
            bus.$emit("busEmit", { value: newId, type: "productingMessage" });
        }

        this.$message.success("操作成功");
      } catch (error) {
        this.$message.error(error);
        console.error("setData 执行失败", error);
      }
    },
    async sureData() {
      if (!this.detail || Object.keys(this.detail).length <= 1) {
        return this.$message.warning("请扫描生产单号/操作单号");
      }
      this.$confirm(`确定生产完成？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        await this.setData(this.detail, "btn");
      });
    },
    clearCache() {
      if (this.checkList.length === 0) {
        return this.$message.warning("请选择要清除的数据");
      }
      this.$confirm("是否确定清除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          for (let k of this.checkList) {
            if (k === "print-setting" || k === "deviceId") {
              let list = Object.keys(this.$dataStore.store).filter(el =>
                el.includes(k)
              );
              list.forEach(el => {
                this.$dataStore.delete(el);
              });
            } else if (k === "token") {
              this.$dataStore.delete("token");
              this.$dataStore.delete("user");
            } else {
              if (this.$dataStore.get(k)) {
                this.$dataStore.delete(k);
              }
            }
          }
          window.location.reload();
        })
        .catch(() => {});
    },
    drawImage(canvas, item) {
      return new Promise((resolve, reject) => {
        try {
          axios
            .get(item?.src, {
              responseType: "blob"
            })
            .then(res => {
              var url = URL.createObjectURL(res.data);
              let img = new Image();
              img.crossorigin = "";
              img.src = url;

              img.onerror = function() {
                reject();
              };
              img.onload = function() {
                // console.log(img, "img");
                img.onload = null;
                const ctx = canvas.getContext("2d");
                ctx.imageSmoothingEnabled = true;
                ctx.imageSmoothingQuality = "high";
                ctx.drawImage(img, ...item.drawImage);
                URL.revokeObjectURL(url);

                resolve();
              };
            })
            .catch(e => {
              console.log(e);
              reject(e);
            });
        } catch (e) {
          console.log(e, "error");
          reject(e);
        }
      });
    },
    /**
     * 批量将canvas绘制配置转成base64图片
     * @param {Array} canvasList - canvas绘制配置列表，每项需包含canvasWidth/canvasHeight/list(绘制项)
     * @returns {Promise<Array>} 图片base64列表
     */
    async canvasToImage(canvasList) {
      // 基础参数校验，避免空值/非数组导致后续循环报错
      if (!Array.isArray(canvasList)) {
        throw new Error("canvasList必须是数组类型");
      }
      const imageList = [];

      // 遍历每个canvas配置项，串行处理（保持原逻辑，若想并行可改成Promise.all(canvasList.map(...))）
      for (const canvasConfig of canvasList) {
        // 解构赋值，简化后续取值，同时校验核心属性
        const { canvasWidth, canvasHeight, list: drawItems } = canvasConfig;
        if (!canvasWidth || !canvasHeight || !Array.isArray(drawItems)) {
          throw new Error(
            "canvas配置项必须包含canvasWidth/canvasHeight/list(数组)属性"
          );
        }

        // 创建临时canvas
        const canvas = document.createElement("canvas");
        canvas.className = "createCanvas";
        canvas.width = canvasWidth;
        canvas.height = canvasHeight;

        // 批量执行绘制方法，收集异步绘制Promise（语义化变量名，替代原模糊的list）
        const drawPromises = drawItems.map(drawItem =>
          this.drawImage(canvas, drawItem)
        );
        // 等待当前canvas的所有绘制操作完成
        await Promise.all(drawPromises);

        // 转base64/png（质量1保持原逻辑）
        const base64 = canvas.toDataURL("image/png", 1);
        // 移除临时canvas，释放内存
        canvas.remove();
        // 推入结果列表
        imageList.push(base64);
      }

      // async函数本身返回Promise，直接return即可，无需手动resolve
      return imageList;
    },

    base64ToFile(base64, fileName) {
      let arr = base64.split(",");
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);

      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], fileName, { type: "image/png" });
    },

    async saveImgByUrl(url) {
      try {
        let res = await this.$api.post("/saveImgByUrl", { url });
        return res.data;
      } catch (e) {
        throw new Error(e.message); // 或者直接 throw e;
      }
    },

    async hasDesignImagesCanvasJsonList(
      designImagesCanvasJsonList,
      bool,
      isForcedProduction
    ) {
      let imageResList = [];

      this.showforcedProduc = false;
      // 当adjustable有值时  直接赋值宽高
      if (
        !this.checked &&
        this.detail.diyId &&
        this.detail.adjustable &&
        designImagesCanvasJsonList &&
        this.desktopDevice !== 3
      ) {
        designImagesCanvasJsonList = JSON.parse(designImagesCanvasJsonList);
        if (!designImagesCanvasJsonList[0].images) {
          let imageList = await this.canvasToImage(designImagesCanvasJsonList);
          let fm = new FormData();
          for (let img of imageList) {
            let filename = uuid.v4().replace("-", "") + ".png";
            fm.append("files", this.base64ToFile(img, filename));
          }
          // console.log("fm", fm);
          let Sres = await this.$api.post("/saveToPng", fm);
          Sres.data.forEach((item, i) => {
            item.title = designImagesCanvasJsonList[i].options.title;
            item.productionFile = item.url;
            item.designId = item.designId || i.toString();
          });
          imageResList = Sres.data;
          console.log("imageResList", imageResList);
        }
      }
      if (this.desktopDevice == 3) {
        if (designImagesCanvasJsonList) {
          designImagesCanvasJsonList = JSON.parse(designImagesCanvasJsonList);
          // 惠立彩 带黄点摸的订单直接展示错误弹窗
          if (
            this.detail.productMark == "custom_part" &&
            this.detail.adjustable &&
            !designImagesCanvasJsonList[0].images
          ) {
            this.showforcedProduc = true;
            this.dialogVisible = true;
            return;
          }
          if (
            (this.detail.productMark == "custom_part" &&
              !this.detail.adjustable) ||
            this.detail.productMark !== "custom_part"
          ) {
            this.showforcedProduc = true;
            this.dialogVisible = true;
            return;
          }
        }
        if (
          (this.detail.productMark == "custom_part" &&
            !this.detail.adjustable) ||
          this.detail.productMark !== "custom_part"
        ) {
          this.showforcedProduc = true;
          this.dialogVisible = true;
          return;
        }
      }

      // 根据生产单号查找 素材图片 下载到本地 然后返回本地地址去显示
      if (!imageResList.length && !bool) {
        try {
          let newType = this.orderType;
          if (this.orderType == "CN" && this.desktopDevice == 3) {
            newType = this.orderType == "CN" ? "CNHLC" : "USHLC";
          }
          let res = await this.$api.post(
            pathMap["downloadBySubOrderNumber"][newType],
            {
              ids:
                this.orderType == "OP"
                  ? [this.detail.podOrderProductId]
                  : [this.detail.id],
              device: this.desktopDevice,
              orderType: this.orderType,
              forceProduction:
                this.isForcedProduction || isForcedProduction || false
            }
          );
          console.log("downloadBySubOrderNumber", res);

          if (!res.data.length) return this.$message.warning("未找到素材图！");
          res.data.forEach(el => {
            imageResList = imageResList.concat(el.list || []);
          });
        } catch (error) {
          if (this.desktopDevice == 3) this.dialogVisible = true;
        }
      } else if (bool) {
        //如果有本地数据 则直接获取本地数据同图片
        imageResList = this.detail?.saveImgList || [];
      }

      if (this.checked) {
        imageResList = await this.cutImgFn(imageResList);
        imageResList.forEach(el => {
          el.isCut = true;
        });
      }

      // 延迟后强制激活窗口
      if (this.desktopDevice == 2) {
        if (imageResList.length) {
          let pathUrl = imageResList[0].productionFile;
          setTimeout(async () => {
            const pathParts = pathUrl.split("\\");
            pathParts.pop();
            // 使用 join() 将剩余部分重新拼接成路径
            const folderPath = pathParts.join("\\");
            ipcRenderer.send("select-files", folderPath);
            // 删除最后一个部分，即文件名
          }, 500);
        }
      } else {
        const newImgList = getImgTitle(imageResList);
        let obj = {
          type: "sendFile",
          value: [...newImgList],
          productMark: this.detail.productMark
        };

        if (this.detail.adjustable && this.detail.specList?.length) {
          obj.sizeObj = this.detail.specList.reduce((acc, el) => {
            if (!el?.faceTitle) return acc;
            acc[el.faceTitle] = {
              width: el.mssWidth || 0, // 默认值防undefined
              height: el.mssHeight || 0
            };
            return acc;
          }, {});
        }
        //设置储存图片的字段，并添加power标识
        if (!this.detail["saveImgList"]?.length) {
          this.detail["saveImgList"] = [...newImgList].map(el => {
            el.power = false;
            return { ...el };
          });
        }
        //如果该数据的图片第一次出现且素材图大于1张则把该数据储存到本地
        if (newImgList.length > 1 && !bool && this.desktopDevice == 3) {
          console.log("addToOrderInfo：", this.detail);

          addToOrderInfo(this.detail);
          console.log("本地数据addToOrderInfo：", getOrderInfoMap());
        }
        if (this.detail["saveImgList"].length == 1) {
          this.faceType = this.detail["saveImgList"][0].title;
        }

        if (this.desktopDevice == 3) obj.faceType = this.faceType;
        bus.$emit("busEmit", obj);
      }
    },

    async getDataInfo(e, isForcedProduction) {
      //查询后先检查当前是否有数据，有则先走生产完成

      if (
        this.detail &&
        Object.keys(this.detail).length > 0 &&
        this.isAutoFinish
      ) {
        try {
          await this.setData(
            this.detail,
            this.orderType === "OP" ? "btn" : undefined
          );
        } catch (err) {
          console.error("setData 执行失败", err);
        }
      }
      if (
        this.detail &&
        Object.keys(this.detail).length > 0 &&
        this.orderType === "GC"
      ) {
        try {
          await this.setData(this.detail);
        } catch (err) {
          console.error("setData 执行失败", err);
        }
      }

      //判断生产单号是否为空
      if (this.productionNo === "")
        return this.$message.warning("请录入生产单号/操作单号");

      const today = moment(new Date()).format("YYYY-MM-DD");

      //判断上一单未勾选添加当天日期是否跳过（us)
      if (
        this.factoryType === "US" &&
        !this.isAutoFinish &&
        today != getNowDate()
      ) {
        this.$confirm("请注意自动完成上一单未勾选", "提示", {
          confirmButtonText: "跳过提示",
          type: "warning"
        }).then(res => {
          if (res == "confirm") {
            setNowDate(today);
          }
        });
      }

      //判断生产单号是US CN GC(老pod),并设置 setOrderType
      if (this.productionNo.includes("_")) {
        this.$store.commit(
          "setOrderType",
          this.classifyField(this.productionNo)
        );
      } else {
        let str;
        if (this.productionNo.includes("PSC")) {
          str = this.productionNo.split("PSC")[0];
        } else if (this.productionNo.includes("OP")) {
          str = "OP";
        } else {
          str = "GC";
        }
        this.$store.commit("setOrderType", str);
      }

      this.templateProductionNo = this.productionNo;
      try {
        //查询当前生产单号是否在本地数据
        let localItem = null;

        let findByPodProductionNo;
        const apiRequestParams = {
          thirdSubOrderNumber: this.productionNo,
          orderType: this.orderType,
          resizable: this.desktopDevice == 3 ? true : false
        };

        //判断是否为惠立彩
        if (this.desktopDevice === 3) {
          const item = getOrderInfoItem(this.productionNo, this.faceType);
          console.log("本地数据getOrderInfoItem：", getOrderInfoMap());
          localItem = item ? { data: item } : null;

          findByPodProductionNo =
            localItem ||
            (await this.$api.post(
              pathMap["findByPodProductionNo"][this.orderType],
              apiRequestParams
            ));
        } else {
          findByPodProductionNo = await this.$api.post(
            pathMap["findByPodProductionNo"][this.orderType],
            apiRequestParams
          );
        }

        this.detail = findByPodProductionNo.data;

        if (this.detail.pause || this.detail.status == "CANCEL") {
          this.detail = "";
          const err = new Error();
          err.data = `订单：${this.productionNo}已挂起或者已取消，无法生产`;
          throw err;
        }

        //赋值当前扫码为生产单号的标识
        if (!this.detail["newId"]) {
          this.detail["newId"] = this.productionNo;
        }

        if (
          this.orderType == "OP" &&
          (this.detail.productMark == "custom_normal" ||
            this.detail.productMark == "normal")
        ) {
          this.detail = "";
          const err = new Error();
          err.data = "G和CB类的操作单无效操作!!!";
          throw err;
        }

        if (
          this.orderType == "OP" &&
          (this.detail.status == "PENDING_PICK" ||
            this.detail.status == "PENDING_REPLENISH")
        ) {
          const {
            data: checkInventoryData,
            code: checkInventoryCode
          } = await this.$api.post(pathMap["checkInventory"][this.orderType], {
            id: this.detail.id,
            status: this.detail.status
          });
          if (checkInventoryCode == 301) {
            this.$confirm(
              `${
                checkInventoryData?.thirdSkuCode
              }库存不足，无法进入生产!请联系仓库管理人员核对库存。</br>
              库存数量：${checkInventoryData.availableInventory || 0}，
              生产中数量：${checkInventoryData.inventory || 0}，
              <span style="color: red;">可调配库存：
                ${checkInventoryData.inventory || 0}</span>`,
              "提示",
              {
                confirmButtonText: "确定",
                type: "error",
                dangerouslyUseHTMLString: true,
                // 🔥 关键：添加自定义类名
                customClass: "custom-inventory-msgbox"
              }
            );
            this.detail = "";
            this.productionNo = "";
            this.$refs.searchRef?.focus();
            return;
          }
        }

        if (this.orderType == "OP" && this.desktopDevice !== 3) {
          await this.setData(this.detail);
        }

        let designImagesCanvasJsonList = this.detail.drParam;
        //获取下载素材
        await this.hasDesignImagesCanvasJsonList(
          designImagesCanvasJsonList,
          this.desktopDevice === 3 ? (localItem ? true : false) : false,
          isForcedProduction
        );
        this.$store.commit("setProductDetail", this.detail);

        ipcRenderer.send("win-subScreen", findByPodProductionNo.data);
        this.$dataStore.set("production_no", this.productionNo);
        this.productionNo = "";
        this.$refs.searchRef?.focus();
      } catch (err) {
        console.log(723, err);
        if (!err.data) {
          this.$message.error(
            "未使用英文输入法输入/扫码，或该生产单号未拣胚或已完成"
          );
        } else {
          this.$message.error(err.data);
        }
        this.productionNo = "";
        this.$refs.searchRef?.focus();
      } finally {
        this.isFirst = false;
      }
    },

    classifyField(field) {
      if (field.includes("CN")) return "CN";
      if (field.includes("US")) return "US";
      if (field.includes("OP")) return "OP";
      return "GC";
    },
    changeActionIndex(t) {
      let index = this.actionIndex;
      if (t === "+") {
        if (index === this.$store.state.actionList.length - 1) return;
        this.actionIndex = this.actionIndex + 1;
      } else {
        if (index === 0) return;
        this.actionIndex = this.actionIndex - 1;
      }
      // console.log(this.actionIndex, 88);
      bus.$emit("busEmit", { type: "index", value: this.actionIndex });
      this.$store.commit("changeActionIndex", this.actionIndex);
    },
    setDefaultSetting() {
      this.$store.commit("setDefaultSetting");
      this.setting = {
        gridShow: 1,
        gridValue: 0,
        unit: "mm",
        language: "cn",
        autoPrint: false,
        gridSpacing: 10
      };
      this.$message.success("重置应用程序设置成功");
    },
    settingChange(field, value) {
      if (value === "inch") {
        this.setting.gridSpacing = 1;
      } else if (value === "mm") {
        this.setting.gridSpacing = 20;
      }
      this.$store.commit("updateSystemSetting", { field, value });
    },

    setBg() {
      bus.$emit("busEmit", { type: "bg", value: this.selectBgColor });
    },
    async uploadImage(f) {
      let formData = new FormData();
      formData.append("file", f);
      let { data } = await this.$api.post("/uploadImage", formData, {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        }
      });
      bus.$emit("busEmit", { type: "uploadImage", value: data });
      return false;
    },
    command(i) {
      if (this.setting.gridValue == i) return;

      if (i === 1) {
        // this.$store.commit("setWHproportion", this.defaultProportion - 0.3);
      } else {
        this.$store.commit("setWHproportion", this.defaultProportion);
      }
      this.$store.commit("setGrid");

      this.selectGridIndex = i;
      this.setting.gridValue = i;

      this.$store.commit("updateSystemSetting", {
        field: "gridValue",
        value: this.grid[i]
      });
      bus.$emit("busEmit", { type: "grid", value: this.grid[i] });
    },
    handleCommand(command) {
      this.selectedOption = command; // 根据选中的项来更新 selectedOption
    },
    changeDesktopDeviceFn(value) {
      this.faceType = "A";
      if (value === 3) {
        this.setting.gridValue == 5;
        this.selectGridIndex = 5;
      } else {
        this.selectGridIndex = 0;
        this.setting.gridValue = 0;
      }
      setDesktopDevice(value);
      this.$store.commit("changeDesktopDevice", value);
      this.$store.commit("changeImgList", []);

      // window.location.reload();
    },
    changeDesktoVersionFn(value) {
      setVersion(value);
      this.selectGridIndex = 0;
      this.$store.commit("changeDesktoVersion", value);
      ipcRenderer.send("update-version", value);
      this.$store.commit("getNewGrid");
      this.$store.commit("setGrid");
      this.command(0);
    },
    async cutImgFn(arr) {
      if (!arr.length) return arr;

      try {
        const processQueue = await Promise.all(
          arr.map(async (el, index) => {
            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
              };
              let res;
              res = await this.$api.post("/processImage", params);

              return {
                fileName: outputFileName,
                productionFile: res.msg[0]?.outputPath,
                designId: el.designId || index
              };
            } catch (error) {
              console.error(`处理失败: ${el.productionFile}`, error);
            }
          })
        );

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

        return processQueue;
      } catch (error) {
        console.error("错误", error);
        return [];
      }
    },
    getCountryName(code) {
      if (code) {
        const item = this.countryList?.find(el => el.countryCode == code);
        if (item) {
          return `(${item.nameCn})`;
        }
      }

      return "";
    },

    getDomainFromUrl(url) {
      try {
        return new URL(url).host;
      } catch (e) {
        console.error("Invalid URL:", url);
        return null;
      }
    },
    clearArray() {
      setOrderInfo([]);
    },
    forcedProductionFN(_, bool) {
      this.detail = null;
      if (bool) this.isForcedProduction = true;
      this.productionNo = this.templateProductionNo;
      this.templateProductionNo = "";
      this.getDataInfo(null, true);
      this.dialogVisible = false;
    },
    closeDialog() {
      this.templateProductionNo = "";
      this.detail = null;
      this.$store.commit("setProductDetail", {});
      this.dialogVisible = false;
    }
  }
};
</script>
<style scoped>
.page-header {
  background-color: #ececec;
  display: flex;
  justify-content: space-between;
  height: 40px;
  padding: 5px;
}

.left-btn {
  display: flex;
}
</style>
<template>
  <div>
    <div class="page-header">
      <div class="left-btn">
        <div class="selectInput">
          <div>设备类型：</div>

          <el-select
            v-model="desktopDevice"
            @change="changeDesktopDeviceFn"
            placeholder="请选择设备类型"
          >
            <el-option label="兄弟" :value="1"></el-option>
            <el-option label="其他" :value="2"></el-option>
            <el-option label="惠立彩" :value="3"></el-option>
          </el-select>
        </div>
        <div style="display: flex;">
          <div class="selectInput" v-if="desktopDevice != 3">
            <div>驱动版本：</div>

            <el-select
              v-model="desktoVersion"
              @change="changeDesktoVersionFn"
              placeholder="请选择版本"
            >
              <el-option label="2.0" value="print"></el-option>
              <el-option label="4.0" value="print4.0"></el-option>
              <el-option label="600" value="print600"></el-option>
              <el-option label="600SC" value="print600SC"></el-option>
            </el-select>
          </div>

          <el-dropdown
            trigger="click"
            @command="command"
            :hide-on-click="false"
            :disabled="desktopDevice == 3"
          >
            <el-button style="height: 100%;margin-right: 0" size="small"
              >{{ grid[selectGridIndex]?.label }}
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                :class="{ disabledClass: it.disabled }"
                :command="i"
                v-for="(it, i) in grid"
                :key="i"
                :disabled="it.disabled"
              >
                {{ it.label }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <el-tooltip content="图片" v-if="desktopDevice != 3">
            <el-upload
              accept=".png"
              action=""
              :show-file-list="false"
              multiple
              :before-upload="uploadImage"
              style="height: 100%;"
            >
              <el-button style="height: 100%;margin:0 8px" size="small">
                <i class="el-icon-picture" style="font-size: 15px;"></i>
              </el-button>
            </el-upload>
          </el-tooltip>

          <el-tooltip content="背景色" v-if="desktopDevice != 3">
            <el-color-picker
              style="margin-right: 3px"
              v-model="selectBgColor"
              @change="setBg"
              color-format="hex"
              :predefine="predefineColors"
            >
            </el-color-picker>
          </el-tooltip>

          <el-popover
            width="350"
            :offset="-120"
            trigger="click"
            placement="bottom"
          >
            <div class="setting-form">
              <el-form
                :model="setting"
                label-position="left"
                label-width="70px"
                size="small"
              >
                <el-form-item prop="setting" label="网格显示">
                  <el-select
                    style="width:100%"
                    @change="e => settingChange('gridShow', e)"
                    clearable
                    v-model="setting.gridShow"
                  >
                    <el-option :value="1" label="未缩放的网格"></el-option>
                    <el-option :value="0" label="无"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="gridSpacing" label="单位">
                  <el-select
                    style="width:100%"
                    @change="e => settingChange('unit', e)"
                    clearable
                    v-model="setting.unit"
                  >
                    <el-option value="mm" label="mm"></el-option>
                    <el-option value="inch" label="inch"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="gridSpacing" label="网格间隔">
                  <el-select
                    style="width:100%"
                    @change="e => settingChange('gridSpacing', e)"
                    clearable
                    v-model="setting.gridSpacing"
                  >
                    <el-option
                      v-if="setting.unit === 'mm'"
                      :value="20"
                      :label="`20 ${setting.unit}`"
                    ></el-option>
                    <el-option
                      v-if="setting.unit === 'mm'"
                      :value="10"
                      :label="`10 ${setting.unit}`"
                    ></el-option>
                    <el-option
                      v-if="setting.unit === 'inch'"
                      :value="1"
                      :label="`1 ${setting.unit}`"
                    ></el-option>
                    <el-option
                      v-if="setting.unit === 'inch'"
                      :value="0.5"
                      :label="`0.5 ${setting.unit}`"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="language" label="语言设置">
                  <el-select
                    style="width:100%"
                    @change="e => settingChange('language', e)"
                    clearable
                    v-model="setting.language"
                  >
                    <el-option value="cn" label="中文"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="language" label="版本号">
                  <b>{{ pkg.version || "" }}</b>
                  <el-button
                    @click="checkUpdate"
                    style="margin-left: 15px"
                    type="text"
                    >检查更新
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
            <el-tooltip slot="reference" content="设置">
              <el-button style="margin:0 8px" size="small">
                <img
                  style="width: 18px;height: 18px"
                  src="@/static/icon/shezhi.png"
                  alt=""
                />
              </el-button>
            </el-tooltip>
          </el-popover>
        </div>
        <div v-if="desktopDevice == 3">
          <div class="selectInput">
            <div>当前打印：</div>

            <el-select v-model="faceType" placeholder="请选择" class="FaceType">
              <el-option label="A面 / 正面" value="A"></el-option>
              <el-option label="B面 / 反面" value="B"></el-option>
            </el-select>
          </div>
        </div>
      </div>
      <div class="center-input">
        <el-input
          @keyup.enter.native="getDataInfo"
          style="width: 40%;"
          size="medium"
          placeholder="请扫描生产单号/操作单号"
          ref="searchRef"
          v-model="productionNo"
        ></el-input>
        <el-button
          @click="getDataInfo"
          size="medium"
          style="margin-left: 10px"
          type="primary"
          >查询
        </el-button>
        <div class="sure-btn">
          <el-button
            @click="sureData"
            size="medium"
            style="margin-left: 10px;width: 100%;"
            type="success"
            >生产完成
          </el-button>
        </div>
        <div style="margin-left: 10px;">
          <el-checkbox v-model="isAutoFinish">自动完成上一单</el-checkbox>
        </div>
        <div style="margin-left: 10px;" v-if="desktopDevice == 3">
          <el-checkbox v-model="isForcedProduction" style="color: red;"
            >自动强制生产</el-checkbox
          >
        </div>
        <div style="margin-left: 10px;" v-show="desktopDevice != 3">
          <el-checkbox v-model="checked">自动裁切</el-checkbox>
        </div>
        <!-- <el-button
          @click="downloadImage"
          size="medium"
          style="margin-left: 15px"
          type="primary"
          >下载素材
        </el-button> -->
      </div>
      <div class="right-user">
        <div
          v-if="user && user.factory"
          style="font-weight: 700;margin-left: 8px;"
        >
          {{
            user.factory.countryCode
              ? `${user.factory.countryCode}${getCountryName(
                  user.factory.countryCode
                )}`
              : "CN(中国)"
          }}
        </div>
        <p v-if="user && user.factory">{{ user.factory.title }}</p>
        <el-dropdown @command="dropdownCommand">
          <div style="margin-right: 20px">
            <b style="cursor:pointer;">{{ user.account }}</b>
            <i class="el-icon-arrow-down"></i>
          </div>

          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            <!-- <el-dropdown-item command="cache">清除缓存</el-dropdown-item> -->
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <update-dialog ref="updateDialog" />
    <el-dialog :visible.sync="cacheVisible" title="清除缓存" width="700px">
      <el-checkbox-group
        style="display: flex;flex-direction: column"
        v-model="checkList"
      >
        <el-checkbox
          style="margin-bottom: 10px"
          :label="item.value"
          v-for="(item, i) in cacheList"
          :key="i"
          >{{ item.label }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="cacheVisible = false">取消</el-button>
        <el-button @click="clearCache" type="primary">清除</el-button>
      </template>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogVisible"
      width="30%"
      @close="closeDialog"
      :close-on-click-modal="false"
    >
      <template slot="title">
        <div style="display:flex;align-items:center;gap:8px;">
          <!-- 红色圆形X图标 -->
          <i
            class="el-icon-error"
            style="font-size:20px;color:#f56c6c;margin-right: 8px;"
          ></i>
          <span style="font-weight: bold;">无法直接生产</span>
        </div>
      </template>
      <div
        style="font-size: 16px;  line-height: 1.6; padding: 10px 0;font-weight: bold;color: #333;"
      >
        <div v-if="showforcedProduc">
          此单素材属于历史不规范素材，无法直接打印。请更换打印设备
        </div>
        <div v-else>
          <div>
            素材效果已经超出台版范围，无法直接打印。
            请更换打印设备，或者进行强制生产
          </div>
          <div>
            注:“自动强制生产”会让每次生产都强制生产
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button v-if="!showforcedProduc" @click="forcedProductionFN"
          >强制生产</el-button
        >
        <el-button
          v-if="!showforcedProduc"
          @click="e => forcedProductionFN(e, true)"
          style="color: red;"
          >自动强制生产</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<style lang="less" scoped>
.right-user {
  display: flex;
  align-items: center;

  b {
    margin: 0 3px;
    display: inline-block;
    color: black;
    font-size: 15px;
    font-weight: bold;
  }

  p {
    margin: 0 10px;
    font-weight: bold;
    display: inline-block;
    font-size: 15px;
    color: #e6a23c;
  }
}

.setting-form {
  .el-form {
    padding: 10px;
    box-sizing: border-box;
  }
}

.form-block {
  padding: 15px 0;
  border-top: 1px solid #ececec;

  &:nth-last-of-type(1) {
    border-bottom: 1px solid #ececec;
  }
}

.block-item {
  width: 100%;
  text-align: left;
  cursor: pointer;
  font-size: 14px;
  padding: 10px 10px;

  &:hover {
    background-color: #ececec;
  }
}

.center-input {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
  flex-shrink: 0;
  overflow: hidden;
  padding-left: 100px;
}

.sure-btn {
  // width: 300px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;

  // ::v-deep {
  //   .el-button {
  //     span {
  //       position: relative;
  //       // left: -40px;
  //     }
  //   }
  // }
}

.check {
  position: absolute;
  right: 10px;
  width: fit-content;
  line-height: 36px;
  height: 100%;
  z-index: 2;
  color: white;
}

::v-deep .el-color-picker__trigger {
  background: white;
  width: 41px;
}

::v-deep .el-color-picker__color {
  border: none !important;
}

.selectInput {
  display: flex;
  align-items: center;
  margin: 0 10px;

  ::v-deep {
    .el-select .el-input {
      max-width: 90px;
    }
    .FaceType .el-input {
      max-width: 120px;
    }
  }
}
::v-deep {
  .el-tooltip {
    .el-upload--text {
      height: 100%;
    }
  }
}
.disabledClass {
  display: none;
}
::v-deep {
  .el-dialog {
    .el-dialog__body {
      padding: 20px 50px;
    }
  }
}
</style>

<style>
.custom-inventory-msgbox {
  width: 500px !important; /* 必须加 !important 覆盖默认样式 */
  min-width: 500px !important; /* 防止被最小宽度限制 */
}
</style>
