<script>
import bus from "@/bus";
// import PrintDialog from "./printDialog.vue";
import { ipcRenderer } from "electron";
// import { grid } from "../data";
import pkg from "../../../../package.json";
import UpdateDialog from "@/views/design/updateDialog.vue";
import path from "path"; // 引入 path 模块
import store from "@/store/index.js";
import axios from "axios";
import { extractValue } from "@/utils/index.js";
const uuid = require("uuid");
const fs = require("fs");
import { mapState } from "vuex";
const { getVersion } = require("@/server/utils/store");

export default {
  components: { UpdateDialog },
  props: {
    user: {
      default: () => ({
        avatar: "",
        factory: {},
      }),
      type: Object,
    },
    factoryType: { type: String, default: "CN" },
  },
  data() {
    return {
      checkList: [],
      desktopDevice: 1,
      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: false,
      cacheVisible: false,
      showPrintDialog: false,
      productionNo: "",
      setting: {
        gridShow: 1,
        gridValue: 0,
        unit: "inch",
        language: "cn",
        autoPrint: false,
        gridSpacing: 1,
      },
      imgList: [],
      detail: null,

      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",
      ],
    };
  },
  computed: {
    actionList() {
      return this.$store.getters.getActionList;
    },

    ...mapState(["defaultProportion", "countryList", "orderType", "grid"]),
  },
  mounted() {
    // console.log(pkg, "pkg");
    this.$nextTick(() => {
      this.$refs.searchRef.focus();
      this.selectGridIndex = 0;
      this.setting.gridValue = 0;
    });
  },
  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,
    },
  },
  methods: {
    checkUpdate() {
      this.$refs.updateDialog.checkUpdate().then((data) => {
        if (data) {
          // 有新版本更新
          this.$refs.updateDialog.open(data);
        } 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;
      }
    },
    async setData(data) {
      if (!data) return this.$message.warning("请扫描生产单号");
      const params = {
        id: data.id,
        orderType: this.orderType,
      };
      if (this.orderType === "CN") {
        params.podJomallOrderCnId = data.podJomallOrderCnId;
      } else if (this.orderType === "US") {
        params.podJomallOrderUsId = data.podJomallOrderUsId;
      }

      await this.$api.post("/completeDelivery", params).then(() => {});
      this.$message.success("操作成功");
    },
    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);
      });
    },
    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) => {
              // console.log("item", item);

              var url = URL.createObjectURL(res.data);
              let img = new Image();
              img.crossorigin = "";
              img.src = url;
              img.style.width = item.img_width + "px";
              img.style.height = item.img_height + "px";
              img.onerror = function() {
                reject();
              };
              img.onload = function() {
                // console.log(img, "img");
                img.onload = null;
                const ctx = canvas.getContext("2d");
                ctx.drawImage(img, ...item.drawImage);
                URL.revokeObjectURL(url);
                resolve();
              };
            })
            .catch((e) => {
              console.log(e);
              reject(e);
            });
        } catch (e) {
          console.log(e, "error");
          reject(e);
        }
      });
    },
    async canvasToImage(canvasList) {
      return new Promise(async (resolve, reject) => {
        let imageList = [];
        try {
          for (let canvasItem of canvasList) {
            const canvas = document.createElement("canvas");
            canvas.className = "createCanvas";
            canvas.width = canvasItem.canvasWidth;
            canvas.height = canvasItem.canvasHeight;
            let list = [];
            for (let listItem of canvasItem.list) {
              list.push(this.drawImage(canvas, listItem));
            }
            await Promise.all(list);
            let base = canvas.toDataURL("image/png", 1);
            // console.log("base", base);

            canvas.remove();
            imageList.push(base);
          }
          resolve(imageList);
        } catch (e) {
          console.log(e);
          reject(e);
        }
      });
    },
    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 downloadImage() {
      if (!this.detail || Object.keys(this.detail).length === 0)
        return this.$message.warning("请扫描生产单号");
      let params = {
        productionNo: this.detail.factorySubOrderNumber,
        imgList: this.imgList,
      };

      let res = await this.$api.post("/downloadByDesignId", params);
      this.$message.success(res.msg);
    },
    async saveImgByUrl(url) {
      return new Promise(async (resolve, reject) => {
        try {
          let res = await this.$api.post("/saveImgByUrl", { url });

          resolve(res.data);
        } catch (e) {
          reject(e.message);
        }
      });
    },
    async hasDesignImagesCanvasJsonList(designImagesCanvasJsonList) {
      let imageResList = [];
      if (
        !this.checked &&
        this.detail.diyId &&
        this.detail.adjustable &&
        designImagesCanvasJsonList
      ) {
        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;
          });
          imageResList = Sres.data;
        } else {
          // designImagesCanvasJsonList.forEach((el) => {
          //   el.images.forEach((item) => {
          //     imageResList.push({
          //       productionFile: item,
          //       title: el.title,
          //     });
          //   });
          // });
          // for (let item of imageResList) {
          //   item.productionFile = await this.saveImgByUrl(item.productionFile);
          // }
        }
      }
      if (!imageResList.length) {
        console.log(347, this.orderType);

        // 根据生产单号查找 素材图片 下载到本地 然后返回本地地址去显示
        let res = await this.$api.post("/downloadBySubOrderNumber", {
          ids: [this.detail.id],
          device: this.$store.state.desktopDevice,
          orderType: this.orderType,
        });
        if (!res.data.length) return this.$message.warning("未找到素材图！");
        res.data.forEach((el) => {
          imageResList = imageResList.concat(el.list || []);
        });
      }
      if (this.checked) {
        imageResList = await this.cutImgFn(imageResList);
        imageResList.forEach((el) => {
          el.isCut = true;
        });
      }

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

        if (
          this.detail.mssWidth &&
          this.detail.adjustable &&
          this.detail.mssHeight
        ) {
          obj.size = {
            width: this.detail.mssWidth,
            height: this.detail.mssHeight,
          };
        }
        bus.$emit("busEmit", obj);
      }
    },

    async getDataInfo() {
      if (
        this.detail &&
        Object.keys(this.detail).length > 0 &&
        this.isAutoFinish
      ) {
        await this.setData(this.detail);
      }

      if (this.productionNo === "")
        return this.$message.warning("请录入生产单号");

      if (!this.isAutoFinish && !this.isFirst)
        this.$confirm("请注意自动完成上一单未勾选", "提示", {
          confirmButtonText: "确定",
          type: "warning",
        });

      try {
        await this.$api.post("/cleanDirectorySync");
      } catch (error) {
        console.error("清理目录时发生错误:", error.msg);
      }

      if (this.productionNo.includes("_")) {
        let code;
        let processed;
        const parts = this.productionNo.split("_");
        const prefix = parts[0];

        // 查找第一个包含"PSC"的片段
        const pscPart = parts.find((part) => part.includes("PSC"));

        if (pscPart) {
          processed = `${prefix}-${pscPart}`;
          if (pscPart.includes("JMPSC")) {
            this.productionNo = processed;
          }
          code = processed;
        }

        this.$store.commit("setOrderType", this.classifyField(code));
      } else {
        const str = this.productionNo.split("PSC")[0];

        this.$store.commit("setOrderType", str);
      }

      console.log(423, this.productionNo);

      try {
        //查找生产单号信息传给第二个显示器
        const findByPodProductionNo = await this.$api.post(
          "/findByPodProductionNo",
          {
            thirdSubOrderNumber: this.productionNo,
            orderType: this.orderType,
          }
        );
        this.detail = findByPodProductionNo.data;
        this.imgList = [];
        let designImagesCanvasJsonList = this.detail.drParam;
        await this.hasDesignImagesCanvasJsonList(designImagesCanvasJsonList);
        this.$store.commit("setProductDetail", findByPodProductionNo.data);
        ipcRenderer.send("win-subScreen", findByPodProductionNo.data);
        this.$dataStore.set("production_no", this.productionNo);
        this.productionNo = "";
        this.$refs.searchRef.focus();
      } catch (err) {
        console.log(err);
        if (!err.data) {
          this.$message.error(
            "未使用英文输入法输入/扫码，或该生产单号未拣胚或已完成"
          );
        }
        this.productionNo = "";
        this.$refs.searchRef.focus();
      } finally {
        this.isFirst = false;
      }
    },
    // // 聚焦资源管理器窗口（Windows）
    focusExplorerWindow(path) {
      const { exec } = require("child_process");
      const fs = require("fs");
      const command = `start explorer /select, "${path}"`;
      // 检查路径是否存在
      if (fs.existsSync(path)) {
        exec(`cmd /c "${command}"`, (err) => {
          if (err) console.error("激活窗口失败:", err);
        });
      } else {
        console.error("路径不存在:", path);
      }
    },
    classifyField(field) {
      // 第一类：以"AAAF-CNPSC"开头
      if (field.startsWith("AAAF-CNPSC")) {
        return "CN";
      }

      // 第二类：以"AAAF-USPSC"开头
      if (field.startsWith("AAAF-USPSC")) {
        return "US";
      }

      // 第三类：所有其他情况
      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.$store.commit("changeDesktopDevice", value);
      this.$store.commit("changeImgList", []);
      console.log(347, store.state.desktopDevice);
    },
    changeDesktoVersionFn(value) {
      console.log(553, value);
      this.selectGridIndex = 0;
      this.$store.commit("changeDesktoVersion", value);
      ipcRenderer.send("update-version", value);
      this.$store.commit("getNewGrid");
      this.command(0);
    },
    async cutImgFn(arr) {
      if (!arr.length) return arr;
      console.log(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,
              };
              const res = await this.$api.post("/processImage", params);
              fs.unlinkSync(el.productionFile);
              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]));
        console.log("newMap", newMap);

        processQueue.forEach((el) => {
          if (newMap.has(el.designId)) {
            el.fileName = newMap.get(el.designId).fileName;
            el.productionFile = newMap.get(el.designId).productionFile;
          }
        });
        console.log("processQueue", processQueue);
        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 "";
    },
    // async cleanDirectorySync() {
    //   let dirPath = path.join(process.cwd(), `./print/Input`);
    //   if (!fs.existsSync(dirPath)) {
    //     console.log(`目录不存在: ${dirPath}`);
    //     return;
    //   }
    //   try {
    //     const files = fs.readdirSync(dirPath, { withFileTypes: true });
    //     for (const file of files) {
    //       const fullPath = path.join(dirPath, file.name);
    //       if (
    //         file.isFile() &&
    //         path.extname(file.name).toLowerCase() === ".png"
    //       ) {
    //         await fs.promises.unlink(fullPath);
    //         console.log(`已删除文件: ${fullPath}`);
    //       }
    //     }
    //   } catch (error) {
    //     if (error.code === "ENOENT") {
    //       console.warn(`目录不存在: ${dirPath}`);
    //     } else {
    //       console.error(`清理错误: ${error.message}`);
    //     }
    //   }
    // },
  },
};
</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">
        <!--        <el-tooltip content="文件">-->
        <!--          <el-button style="margin-right: 8px" size="small">文件</el-button>-->
        <!--        </el-tooltip>-->
        <!-- <el-dropdown
          trigger="click"
          @command="handleCommand"
          :hide-on-click="false"
          split-button
          style="margin-right: 10px;width: 100%;"
        >
          设备类型:{{ selectedOption }}

          <el-dropdown-menu slot="dropdown" style="width: 100%;">
            <el-dropdown-item :command="'兄弟'">兄弟</el-dropdown-item>
            <el-dropdown-item :command="'其他'">其他</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown> -->
        <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-select>
        </div>
        <div class="selectInput">
          <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-select>
        </div>

        <el-dropdown trigger="click" @command="command" :hide-on-click="false">
          <el-button style="height: 100%;margin-right: 0" size="small"
            >{{ grid[selectGridIndex]?.label }}
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :command="i" v-for="(it, i) in grid" :key="i">
              {{ it.label }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <!--        <el-tooltip content="字体">-->
        <!--          <el-button size="small">-->
        <!--            <img style="width: 13px;height: 13px" src="@/static/icon/ziti.png" alt="">-->
        <!--          </el-button>-->
        <!--        </el-tooltip>-->
        <el-tooltip content="图片">
          <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="撤销">-->
        <!--          <el-button @click="changeActionIndex('+')"-->
        <!--                     :disabled="actionList.length===0 || actionIndex<-1 ||  actionIndex===actionList.length-1 " icon=""-->
        <!--                     size="small">-->
        <!--            <img style="width: 14px;height: 14px" src="@/static/icon/chehuizuo.png" alt="">-->
        <!--          </el-button>-->
        <!--        </el-tooltip>-->
        <!--        <el-tooltip content="恢复">-->
        <!--          <el-button @click="changeActionIndex('-')"-->
        <!--                     :disabled="actionList.length===0   || actionIndex<=-1" icon=""-->
        <!--                     size="small">-->
        <!--            <img style="width: 14px;height: 14px" src="@/static/icon/chehuiyou.png" alt="">-->
        <!--          </el-button>-->
        <!--        </el-tooltip>-->
        <el-tooltip content="背景色">
          <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="320"
          :offset="-120"
          trigger="click"
          placement="bottom"
        >
          <div class="setting-form">
            <el-form
              :model="setting"
              label-position="left"
              label-width="80px"
              size="small"
            >
              <el-form-item prop="setting" label="网格显示">
                <el-select
                  @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
                  @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
                  @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
                  @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-item label="自动打印模式">-->
              <!--                <el-switch @change="(e)=>settingChange('autoPrint',e)" v-model="setting.autoPrint"></el-switch>-->
              <!--              </el-form-item>-->
            </el-form>
            <!--            <div class="form-block">-->
            <!--              <div @click="setDefaultSetting" class="block-item">重置应用程序设置</div>-->
            <!--            </div>-->
            <!--            <div class="form-block">-->
            <!--              <div class="block-item">隐私政策</div>-->
            <!--              <div class="block-item">版本信息</div>-->
            <!--            </div>-->
          </div>
          <el-tooltip slot="reference" content="设置">
            <el-button style="margin-right: 8px" size="small">
              <img
                style="width: 18px;height: 18px"
                src="@/static/icon/shezhi.png"
                alt=""
              />
            </el-button>
          </el-tooltip>
        </el-popover>
        <!--        <el-tooltip content="打印">-->
        <!--          <el-button @click="showPrintDialog=true" size="small" type="primary">打印</el-button>-->
        <!--        </el-tooltip>-->
        <!--        <el-tooltip content="添加模板">-->
        <!--          <el-button size="small">添加模板</el-button>-->
        <!--        </el-tooltip>-->
      </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 class="check">
            <el-checkbox v-model="isAutoFinish">自动完成上一单</el-checkbox>
          </div>
        </div>
        <div style="margin-left: 10px;">
          <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>
  </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: 80px;
    }
  }
}
::v-deep {
  .el-tooltip {
    .el-upload--text {
      height: 100%;
    }
  }
}
</style>
