<script>
const { getDTFSetting } = require("@/server/utils/store");
const { ipcRenderer } = require("electron");
const { statusMap } = require("@/config/index.js");
const { pathMap } = require("@/config/index.js");
const { getUser } = require("@/server/utils/store");
var path = require("path");
import bus from "@/bus";
export default {
  props: {
    selection: { type: Array, default: () => [] },
    podOrderProductIds: { type: Array, default: () => [] }
  },
  data() {
    return {
      dialogVisible: false,
      dtfSetting: getDTFSetting(),
      radio: "",
      curBatchArrangeNum: "",
      searchForm: {},
      statusMap: statusMap,
      userData: getUser()
    };
  },

  mounted() {
    const params = this.$route.params;
    this.curBatchArrangeNum = params.batchArrangeNum;
    bus.$on("downLoadFile", async v => {
      let { podOrderProductId, batchArrangeNumber } = v;
      console.log(31, v);

      try {
        let res = await this.$api.post(
          pathMap["downloadBySubOrderNumber"]["OP"],
          {
            ids: [podOrderProductId],
            device: 4,
            orderType: "OP",
            targetDir: path.join(
              getDTFSetting().downloadDir,
              `批次号：${batchArrangeNumber}`,
              "原素材"
            )
          }
        );
        console.log(77, res);
      } catch (error) {
        this.$message.error(error);
      }
    });
  },
  created() {},

  methods: {
    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;
      }
    },
    getCountryName(code) {
      if (code) {
        const item = this.countryList?.find(el => el.countryCode == code);
        if (item) {
          return `(${item.nameCn})`;
        }
      }

      return "";
    },
    goBack() {
      this.$router.push({
        name: "design-dtf",
        query: { page: this.$route.query.fromPage }
      });
    },
    async downLoadFn() {
      if (!this.podOrderProductIds.length) {
        return this.$message.warning("请选择操作单");
      }
      console.log(1111)
      try {
        let res = await this.$api.post(
          pathMap["downloadBySubOrderNumber"]["OP"],
          {
            ids: this.podOrderProductIds,
            device: 4,
            orderType: "OP",
            targetDir: path.join(
              getDTFSetting().downloadDir,
              `批次号：${this.curBatchArrangeNum}`,
              "原素材"
            )
          }
        );
        console.log(77, res);
      } catch (error) {
        this.$message.error(error);
      }
    },
    getDataInfo() {
      this.$emit("search", this.searchForm);
    },
    productionCompleted() {
      if (!this.selection.length) {
        return this.$message.warning("请选择操作单");
      }
      this.$confirm(`确定生产完成？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        await this.$api.post(pathMap.completeDelivery["DTF"], {
          orderType: "DTF",
          ids: this.selection
        });
      });
    },
    changeTypesetting() {
      if (!this.selection.length) {
        return this.$message.warning("请选择操作单");
      }
      this.dialogVisible = true;
      this.radio = "";
    },
    async submit() {
      try {
        if (!this.radio) {
          return this.$message.error("请选择排版宽度");
        }
        const payload = {
          ids: this.selection,
          type: "png",
          templateWidth: this.radio,
          targetDir: path.join(
            getDTFSetting().downloadDir,
            `批次号：${this.curBatchArrangeNum}`,
            "手动排版素材"
          )
        };
        if (this.dtfSetting.widthStrategy == 3 && this.radio == 60) {
          this.$confirm(
            "由于排版设置中选择“按更大规格排版”仅适用于40+2，选60时，默认超60的规格不排版",
            "提示",
            {
              confirmButtonText: "确定",
              type: "warning"
            }
          );
          const { data } = await this.$api.post(
            pathMap["replenishmentComposingDesignImages"],
            payload
          );
          console.log("submit", data);

          this.$message.success("DTF排版成功，请到手动排版素材中查看");
        } else {
          const { data } = await this.$api.post(
            pathMap["replenishmentComposingDesignImages"],
            payload
          );
          console.log("submit", data);

          this.$message.success("DTF排版成功，请到手动排版素材中查看");
        }
        this.dialogVisible = false;
        this.getDataInfo();
      } catch (error) {
        console.log("submit", error);
      }
    },
    async goFliePage() {
      let { data } = await this.$api.post("/createBatchFolder", {
        basePath: this.dtfSetting.downloadDir,
        downloadDir: this.curBatchArrangeNum,
        isArray: false
      });
      if (!data) {
        return this.$message.error("下载文件目录未配置或者目录错误");
      }

      ipcRenderer.send("open-folder-only", data);
    }
  }
};
</script>

<template>
  <div>
    <div class="page-header">
      <el-form style="display: flex;flex-wrap: nowrap;" inline>
        <el-form-item>
          <el-button icon="el-icon-arrow-left" @click="goBack"
            >返回</el-button
          ></el-form-item
        >
        <el-form-item>
          <el-input
            placeholder="请扫描操作单"
            v-model="searchForm.operationNo"
            clearable
          ></el-input
        ></el-form-item>
        <el-form-item label="操作单状态">
          <el-select
            style="width: 120px;"
            v-model="searchForm.status"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="(value, label) in statusMap"
              :key="value"
              :label="label"
              :value="value"
            ></el-option> </el-select
        ></el-form-item>
        <el-form-item label="操作单排版状态">
          <el-select
            v-model="searchForm.layout"
            placeholder="请选择"
            clearable
            style="width: 120px;"
          >
            <el-option label="排版成功" :value="true"></el-option>
            <el-option label="排版失败" :value="false"> </el-option> </el-select
        ></el-form-item>

        <el-form-item>
          <el-button @click="getDataInfo" type="primary"
            >查询
          </el-button></el-form-item
        >
        <el-form-item>
          <el-button @click="productionCompleted" type="success"
            >生产完成
          </el-button></el-form-item
        >
        <el-form-item>
          <el-button @click="downLoadFn" type="success"
            >下载素材
          </el-button></el-form-item
        >
        <el-form-item>
          <el-button @click="changeTypesetting" type="success"
            >排版
          </el-button></el-form-item
        >
        <el-form-item>
          <el-button @click="goFliePage" type="success"
            >查看排版文件
          </el-button></el-form-item
        >
      </el-form>

      <div class="right-user">
        <div
          v-if="userData && userData.factory"
          style="font-weight: 700;margin-left: 8px;"
        >
          {{
            userData.user.countryCode
              ? `${userData.user.countryCode}${getCountryName(
                  userData.user.countryCode
                )}`
              : "CN(中国)"
          }}
        </div>
        <p v-if="userData.user && userData.user.factory">
          {{ userData.user.factory.title }}
        </p>
        <el-dropdown @command="dropdownCommand">
          <div style="margin-right: 20px">
            <b style="cursor:pointer;">{{ userData.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-menu>
        </el-dropdown>
      </div>
    </div>
    <el-dialog title="排版宽度" :visible.sync="dialogVisible" width="25%">
      <el-radio-group v-model="radio">
        <el-radio :label="42">40+2cm</el-radio>
        <el-radio :label="60">60cm</el-radio>
      </el-radio-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</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;
  }
}

.page-header {
  display: flex;
  justify-content: space-between;
  background-color: #ececec;
  padding: 5px;
  .el-form-item {
    margin-bottom: 0;
  }
}
</style>
