<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";

export default {
  components: { PrintDialog, UpdateDialog },
  props: {
    user: {
      default: {
        avatar: "",
        factory: {},
      },
      type: Object,
    },
  },
  data() {
    return {
      checkList: [],
      desktopDevice: 1,
      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: "mm",
        language: "cn",
        autoPrint: false,
        gridSpacing: 10,
      },
      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",
      ],
      grid,
    };
  },
  computed: {
    actionList() {
      return this.$store.getters.getActionList;
    },
  },
  mounted() {
    // console.log(pkg, "pkg");
    this.$nextTick(() => {
      this.$refs.searchRef.focus();
    });
  },
  created() {
    if (this.$dataStore.get("setting")) {
      this.setting = this.$dataStore.get("setting");
    } else {
      this.$dataStore.set("setting", this.setting);
    }
  },
  watch: {
    setting: {
      handler() {
        this.$dataStore.set("setting", this.setting);
        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("请扫描生产单号");
      await this.$api.post("/completeDelivery", { id: data.id }).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(() => {});
    },
    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 getDataInfo() {
      if (
        this.detail &&
        Object.keys(this.detail).length > 0 &&
        this.isAutoFinish
      ) {
        await this.setData(this.detail);
      }

      if (this.productionNo === "")
        return this.$message.warning("请录入生产单号");
      try {
        //查找生产单号信息传给第二个显示器
        const findByPodProductionNo = await this.$api.post(
          "/findByPodProductionNo",
          {
            thirdSubOrderNumber: this.productionNo,
          }
        );
        this.detail = findByPodProductionNo.data;

        ipcRenderer.send("win-subScreen", findByPodProductionNo.data);
        // 根据生产单号查找 素材图片 下载到本地 然后返回本地地址去显示
        let res = await this.$api.post("/downloadBySubOrderNumber", [
          this.detail.id,
          this.$store.state.desktopDevice,
        ]);
        console.log("res111", res);
        this.imgList = [];
        res.data.forEach((el) => {
          this.imgList = this.imgList.concat(el.list || []);
        });

        this.$dataStore.set("production_no", this.productionNo);
        if (res.data.length === 0)
          return this.$message.warning("未找到素材图！");
        let arr = [];
        res.data.forEach((el) => {
          if (el.list) {
            el.list.forEach((it) => {
              arr.push(it);
            });
          }
        });
        console.log(arr, "arr");
        res.data = arr.filter((el) => el.type !== 1);

        // 延迟后强制激活窗口
        if (this.desktopDevice !== 1) {
          if (this.imgList.length) {
            let pathUrl = this.imgList[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 {
          console.log(260, res.data);

          bus.$emit("busEmit", {
            type: "sendFile",
            value: res.data,
            // size: { width: this.detail.mssWidth || 500, height: this.detail.mssHeight || 500 },
          });
        }

        this.productionNo = "";

        this.$refs.searchRef.focus();
      } catch (err) {
        this.productionNo = "";
        this.$refs.searchRef.focus();
      }
    },
    // // 聚焦资源管理器窗口（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);
      }
    },
    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) {
      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);
    },
  },
};
</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>

        <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"
          >
            <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>
        <el-button
          @click="downloadImage"
          size="medium"
          style="margin-left: 15px"
          type="primary"
          >下载素材
        </el-button>
      </div>
      <div class="right-user">
        <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: 150px;
    }
  }
}
</style>
