<script>
import BaseTable from "../../components/BaseTable.vue";
const { remote, ipcRenderer } = require("electron");
const { getDTFSetting } = require("@/server/utils/store");
const { Menu } = remote;
const path = require("path");
const { pathMap } = require("@/config/index.js");
import DTFhead from "./components/head.vue";
export default {
  name: "design-dtf",
  components: { BaseTable, DTFhead },
  props: {
    user: {
      default: () => ({
        avatar: "",
        factory: {}
      }),
      type: Object
    },
    factoryType: { type: String, default: "CN" }
  },
  data() {
    return {
      dialogVisible: false,
      selectionList: [],
      searchForm: {},
      radio: "",
      templateBatchArrangeNum: "",
      pollTimer: null,
      dtfSetting: getDTFSetting(),
      isFetching: false,
      pageInfo: {
        currentPage: 1,
        pageSize: 10,
        total: 2
      },
      tableList: [],
      tableConfig: [
        {
          prop: "batchArrangeNum",
          label: "批次号",
          width: 140,
          slotName: "batchArrangeNum"
        },
        {
          prop: "operationNum",
          label: "操作单数量",
          width: 100
        },
        {
          prop: "materialNum",
          label: "素材数量",
          width: 100
        },
        {
          prop: "craftType",
          label: "工艺类型",
          width: 100
        },
        {
          prop: "standardDesignImage",
          label: "规范素材",
          width: 100,
          render(row) {
            return row.standardDesignImage == 0
              ? "否"
              : row.standardDesignImage == 1
              ? "是"
              : "混合";
          }
        },
        {
          label: "创建时间",
          prop: "createTime"
        },
        {
          label: "排版状态",
          width: 140,
          prop: "layoutStatus",
          slotName: "layoutStatus"
        },
        {
          prop: "failReason",
          label: "失败原因",
          width: 300,
          slotName: "failReason"
        },
        {
          label: "排版参数",
          prop: "composingParam",
          width: 300
        },
        {
          label: "操作",
          width: 260,
          slotName: "operation",
          prop: "operation"
        }
      ],
      layoutStatus: {
        1: { label: "待排版", type: "warning" },
        2: { label: "排版中", type: "info" },
        3: { label: "排版成功", type: "success" },
        4: { label: "排版失败", type: "danger" },
        5: { label: "部分成功", type: "success" }
      }
    };
  },
  mounted() {
    this.fetchBatchList();
    this.pollTimer = setInterval(() => this.fetchBatchList(), 300000);

    // 单文件下载成功
    ipcRenderer.on("download:file-success", (_, data) => {
      console.log(`批次 ${data.batchArrangeNum}：${data.fileName} 下载完成`);
    });

    // 单文件下载失败
    ipcRenderer.on("download:file-error", (_, data) => {
      this.$message.error(
        `批次 ${data.batchArrangeNum}：${data.fileName} 下载失败，${data.msg}`
      );
    });

    // 新增：批次校验失败，批量提示
    ipcRenderer.on("download:batch-invalid", (_, invalidList) => {
      const msg = invalidList
        .map(item => `【${item.batchArrangeNum}】${item.reason}`)
        .join("；");
      this.$message.warning(`存在异常批次：${msg}`);
    });
  },
  beforeDestroy() {
    if (this.pollTimer) {
      clearInterval(this.pollTimer);
      this.pollTimer = null;
    }
    ipcRenderer.removeAllListeners("download:status-reply");
    ipcRenderer.removeAllListeners("download:file-success");
    ipcRenderer.removeAllListeners("download:file-error");
    ipcRenderer.removeAllListeners("download:batch-invalid");
    ipcRenderer.removeAllListeners("download:all-finish");
  },
  methods: {
    getDownloadStatus() {
      return new Promise(resolve => {
        // 只监听一次回复，避免重复绑定
        ipcRenderer.once("download:status-reply", (_, status) => {
          resolve(status);
        });
        // 发送请求
        ipcRenderer.send("download:get-status");
      });
    },
    //定时任务
    async fetchBatchList(value) {
      // 先判断：有下载任务在跑，本轮直接跳过
      // console.log("this.isFetching", this.isFetching);

      if (this.isFetching) return;
      this.isFetching = true;
      try {
        const status = await this.getDownloadStatus();
        // console.log("status", status);

        if (status.isRunning) return;
        let params = {
          currentPage: this.pageInfo.currentPage,
          pageSize: this.pageInfo.pageSize
        };

        if (value) {
          params = { ...params, ...value };
        }

        const res = await this.$api.post(pathMap["productionSoftware"], params);

        if (res.code === 200) {
          this.tableList = res.data.records || [];

          this.pageInfo.total = res.data.total;
          ipcRenderer.sendSync("download:submit-batch-list", this.tableList);
        }
      } catch (err) {
        console.error("批次列表拉取失败", err);
      } finally {
        this.isFetching = false;
      }
    },

    handleSelect(rows) {
      console.log("选中行", rows);
      this.selectionList = rows;
    },
    handleSizeChange(size) {
      this.pageInfo.pageSize = size;
      this.pageInfo.currentPage = 1;
      this.loadData();
    },
    handleCurrentChange(page) {
      this.pageInfo.currentPage = page;
      this.loadData();
    },

    //右键选择器
    openMenu(e) {
      e.preventDefault();
      const template = [
        {
          label: "全部选择",
          click: () => {
            this.$refs.tableRefs?.toggleAllSelection(true);
          }
        },
        {
          label: "取消选择",
          click: () => this.$refs.tableRefs?.toggleAllSelection(false)
        }
      ];
      const menu = Menu.buildFromTemplate(template);
      menu.popup({ x: e.clientX, y: e.clientY });
    },

    //查看排版文件
    async goFliePage(value, type) {
      console.log(value);

      let { data } = await this.$api.post("/createBatchFolder", {
        basePath: this.dtfSetting.downloadDir,
        downloadDir: value.batchArrangeNum,
        isArray: false
      });
      if (!data) {
        return this.$message.error("下载文件目录未配置或者目录错误");
      }
      if (type == "check") {
        ipcRenderer.send("open-folder-only", data);
      }
    },

    //打开手动排版弹窗
    changeTypesetting(value) {
      if (
        this.dtfSetting.autoLayoutStrategy == 3 ||
        [3, 5].includes(value.layoutStatus)
      ) {
        this.dialogVisible = true;
        this.templateBatchArrangeNum = value.batchArrangeNum;
      } else {
        this.$message(
          "排版进行中，请查看处理状态，排版完成的素材至文件夹排版素材查看"
        );
      }
    },

    //提交手动排版
    async submit() {
      if (!this.radio) {
        return this.$message.error("请选择排版宽度");
      }

      if (this.dtfSetting.widthStrategy == 3 && this.radio == 60) {
        this.$confirm(
          "由于排版设置中选择“按更大规格排版”仅适用于40+2，选60时，默认超60的规格不排版",
          "提示",
          {
            confirmButtonText: "确定",
            type: "warning"
          }
        );
        await this.$api.post(pathMap["psReComposingDesignImages"], {
          batchArrangeNum: this.templateBatchArrangeNum,
          templateWidth: this.radio
        });
        this.$message(
          "排版进行中，请查看处理状态，排版完成的素材至文件夹排版素材查看"
        );
      } else {
        await this.$api.post(pathMap["psReComposingDesignImages"], {
          batchArrangeNum: this.templateBatchArrangeNum,
          templateWidth: this.radio
        });
        this.$message(
          "排版进行中，请查看处理状态，排版完成的素材至文件夹排版素材查看"
        );
      }

      this.dialogVisible = false;
      this.fetchBatchList(this.searchForm);
    },

    //跳转批次详情页
    toDetail(value) {
      this.$router.push({
        name: "dtf-batch-detail",
        params: {
          ...value
        }
      });
    },

    //下载批次原素材
    async downloadFile(value) {
      try {
        const { data } = await this.$api.post(pathMap["listMaterialsByBatch"], {
          batchArrangeNum: value
        });
        const res = await this.$api.post("/downloadMaterial", {
          urls: data.urls,
          targetPath: path.join(
            getDTFSetting().downloadDir,
            `批次号：${value}`,
            "原素材"
          )
        });
        console.log("listMaterialsByBatch-", data);
        console.log("downloadMaterial", res);

        this.$message("下载进行中，下载完成的素材将在文件夹原素材中显示");
      } catch (error) {
        console.log(error);
      }
    }
  }
};
</script>

<template>
  <div class="page" @contextmenu.prevent="openMenu">
    <DTFhead
      :user="user"
      :factoryType="factoryType"
      @search="
        value => {
          searchForm = value;
          this.fetchBatchList(searchForm);
        }
      "
    ></DTFhead>
    <BaseTable
      v-if="tableList.length"
      ref="tableRefs"
      :table-data="tableList"
      :table-config="tableConfig"
      :has-selection="true"
      :has-index="true"
      :page-info="pageInfo"
      @page-size-change="handleSizeChange"
      @page-current-change="handleCurrentChange"
      @selection="handleSelect"
      border
      stripe
      height="100%"
      size="mini"
    >
      <!-- 自定义插槽示例 -->
      <template #batchArrangeNum="scope">
        <a href="javascript:;" @click="toDetail(scope.row)">{{
          scope.row.batchArrangeNum
        }}</a>
      </template>
      <template #layoutStatus="scope">
        <el-tag :type="layoutStatus[scope.row?.layoutStatus].type">{{
          layoutStatus[scope.row?.layoutStatus].label
        }}</el-tag>
      </template>
      <template #failReason="scope">
        <div style="white-space: pre-line">
          <span v-html="scope.row?.failReason"></span>
        </div>
      </template>

      <template #operation="scope">
        <div class="flex" style="justify-content: space-between;">
          <el-button
            type="text"
            class="btn flex btnBox"
            @click="downloadFile(scope.row.batchArrangeNum)"
          >
            <img src="../../assets/download.png" width="30" height="30" />
            <div>下载素材</div></el-button
          >
          <el-button
            type="text"
            :disabled="scope.row.layoutStatus == 2"
            class="btn flex btnBox"
            @click="changeTypesetting(scope.row)"
            ><img
              src="../../assets/typesetting.png"
              width="30"
              height="30"
              :class="{ disabled: scope.row.layoutStatus == 2 }"
            />
            <div>排版</div>
          </el-button>
          <el-button
            type="text"
            class="btn flex btnBox"
            @click="goFliePage(scope.row, 'check')"
          >
            <img src="../../assets/file.png" width="30" height="30" />
            <div>查看排版文件</div>
          </el-button>
        </div>
      </template>
    </BaseTable>
    <el-empty
      style="height: 100%; "
      v-else
      :image-size="500"
      :image="require('@/assets/JOMALL.png')"
      description="好像什么都没有"
    ></el-empty>
    <el-dialog title="排版宽度" :visible.sync="dialogVisible" width="25%">
      <el-radio-group v-model="radio">
        <el-radio :label="40">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 scoped lang="less">
.page {
  height: "100%";
}
.flex {
  display: flex;
}
.btnBox {
  flex-direction: column;
  align-items: center;
}
.btn {
  padding: 0;
}
::v-deep .el-empty__image img {
  filter: grayscale(100%);
  opacity: 0.3;
}
::v-deep.el-empty__description p {
  font-size: 50px;
}
.el-button {
  div {
    margin-top: 5px;
    font-size: 12px;
  }
}
::v-deep.disabled {
  filter: grayscale(100%);
  opacity: 0.3;
}
</style>
