<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";
import {
  submitDownload,
  getDownloadStatus,
  onDownloadStatusChange
} from "@/utils/download-api";
export default {
  props: {
    selection: { type: Array, default: () => [] },
    podOrderProductIds: { type: Array, default: () => [] }
  },
  data() {
    return {
      dialogVisible: false,
      dtfSetting: getDTFSetting(),
      radio: "",
      curBatchArrangeNum: "",
      searchForm: {},
      statusMap: statusMap,
      userData: getUser(),
      isDownloading: false,
      removeStatusListener: null
    };
  },

  async 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);
      }
    });
    this.removeStatusListener = onDownloadStatusChange(status => {
      this.handleDownloadStatus(status);
    });
    await this.syncDownloadStatus();
  },
  beforeDestroy() {
    if (this.removeStatusListener) this.removeStatusListener();
  },
  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("请选择操作单");
      }
      if (this.isDownloading) {
        return this.$message.warning("正在下载中，请等待完成后再操作");
      }
      try {
        this.isDownloading = true;
        const res = await this.$api.post(
          pathMap["downloadBySubOrderNumber"]["DTF"],
          this.podOrderProductIds
        );
        if (res.code !== 200 || !res.data || res.data.length === 0) {
          this.$message.warning(res.msg || "暂无素材可下载");
          this.isDownloading = false;
          return;
        }
        const urls = res.data.map(item => ({
          url: item.fileUrl,
          fileName: item.fileName
        }));
        const downloadRes = await submitDownload({
          urls,
          targetPath: path.join(
            getDTFSetting().downloadDir,
            `批次号：${this.curBatchArrangeNum}`,
            "原素材"
          ),
          batchArrangeNum: this.curBatchArrangeNum
        });
        if (downloadRes.code !== 200) {
          this.isDownloading = false;
          this.$message.error(downloadRes.msg);
        }
      } catch (error) {
        console.error(error.message || "下载失败");
        this.$message.error("下载提交失败，请重试");
        this.isDownloading = false;
      }
    },
    handleDownloadStatus(status) {
      this.isDownloading = status.isRunning;
      if (!status.isRunning && status.result) {
        const { success, failed } = status.result;
        const { currentBatchNo } = status;
        this.$message.success(
          `批次号：${currentBatchNo}，下载完成：成功 ${success.length} 个，失败 ${failed.length} 个`
        );
        if (failed.length > 0) {
          console.warn("下载失败明细：", failed);
        }
      }
    },
    async syncDownloadStatus() {
      try {
        const res = await getDownloadStatus();
        this.isDownloading = res.data.isRunning;
      } catch (err) {
        console.error("同步下载状态失败", err);
      }
    },
    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>
