<script>
import BaseTable from "../../components/BaseTable.vue";
const { remote, ipcRenderer } = require("electron");
const { getDTFSetting } = require("@/server/utils/store");
const { Menu } = remote;

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: [],
      radio: "",
      dtfSetting: getDTFSetting(),
      pageInfo: {
        pageNum: 1,
        pageSize: 10,
        total: 2
      },
      tableList: Array.from({ length: 50 }, (_, index) => {
        const isDtg = index % 2 === 0;
        return {
          id: index + 1,
          batchArrangeNum: index + 1,
          status: index % 3 === 0 ? 0 : 1,
          img: isDtg ? "/static/dtg.jpg" : "/static/dtf.jpg",
          subOrderNumber: index % 4 !== 0,
          num: isDtg ? 120 + index * 2 : 86 + index,
          failedReason: ""
        };
      }),
      tableConfig: [
        {
          prop: "batchArrangeNum",
          label: "批次号",
          width: 100,
          slotName: "batchNo"
        },
        {
          prop: "operationNum",
          label: "操作单数量",
          width: 100
        },
        {
          prop: "materialNum",
          label: "素材数量",
          width: 100
        },
        {
          prop: "craftType",
          label: "工艺类型",
          width: 100,
          slotName: "craftType"
        },
        {
          prop: "standardDesignImage",
          label: "规范素材",
          width: 100,
          slotName: "standardDesignImage"
        },
        {
          label: "创建时间",
          prop: "createTime"
        },
        {
          label: "排版状态",
          width: 140,
          prop: "status"
        },
        {
          prop: "failReason",
          label: "失败原因",
          width: 300,
          slotName: "failReason"
        },
        {
          label: "排版参数",
          prop: "layoutParameters",
          width: 300
        },
        {
          label: "操作",
          width: 260,
          slotName: "operation"
        }
      ]
    };
  },
  mounted() {
    this.fetchBatchList();
    // 开启5分钟轮询
    this.pollTimer = setInterval(() => {
      this.fetchBatchList();
    }, 5 * 60 * 1000);

    // 监听下载结果
    ipcRenderer.on("download:success", (_, batchNum) => {
      this.$message.success(`批次 ${batchNum} 素材下载完成`);
    });
    ipcRenderer.on("download:error", (_, { batchArrangeNum, msg }) => {
      this.$message.error(`批次 ${batchArrangeNum} 下载失败：${msg}`);
    });
  },
  beforeDestroy() {
    clearInterval(this.pollTimer);
    ipcRenderer.removeAllListeners("download:success");
    ipcRenderer.removeAllListeners("download:error");
  },
  methods: {
    async fetchBatchList() {
      // 先判断：有下载任务在跑，本轮直接跳过
      const status = ipcRenderer.sendSync("download:getStatus");
      if (status.isRunning) return;

      try {
        // const res = await getBatchListApi();
        let res;
        if (res.code === 200) {
          this.tableData = res.data || [];
          this.autoHandleDownload();
        }
      } catch (err) {
        console.error("批次列表拉取失败", err);
      }
    },

    autoHandleDownload() {
      // 1. 过滤出 status 为“是”的批次
      const finishList = this.tableData.filter(item => item.status === "是");
      if (finishList.length === 0) return;

      // 2. 直接发给主进程，主进程会自动校验本地文件、过滤已存在的批次
      ipcRenderer.sendSync("download:addTasks", finishList);
    },
    handleSelect(rows) {
      console.log("选中行", rows);
      this.selectionList = rows;
    },
    handleSizeChange(size) {
      this.pageInfo.pageSize = size;
      this.pageInfo.pageNum = 1;
      this.loadData();
    },
    handleCurrentChange(page) {
      this.pageInfo.pageNum = 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.batchNo,
        isArray: false
      });
      console.log("goFliePage", data);
      if (type == "check") {
        ipcRenderer.send("open-folder-only", data);
      }
    },
    changeTypesetting() {
      if (this.dtfSetting.autoLayoutType == "none") {
        this.dialogVisible = true;
      } else {
        this.$message(
          "排版进行中，请查看处理状态，排版完成的素材至文件夹排版素材查看"
        );
      }
    },
    submit() {
      console.log(this.radio);
      if (!this.radio) {
        return this.$message.error("请选择排版宽度");
      }

      if (this.dtfSetting.overWidthMode === "biggerSize" && this.radio == 60) {
        this.$confirm(
          "由于排版设置中选择“按更大规格排版”仅适用于40+2，选60时，默认超60的规格不排版",
          "提示",
          {
            confirmButtonText: "确定",
            type: "warning"
          }
        ).then(() => {
          this.$message(
            "排版进行中，请查看处理状态，排版完成的素材至文件夹排版素材查看"
          );
        });
      } else {
        this.$message(
          "排版进行中，请查看处理状态，排版完成的素材至文件夹排版素材查看"
        );
      }
    },
    toDetail(value) {
      this.$router.push({
        name: "dtf-batch-detail",
        params: {
          batchNo: value
        }
      });
    },
    downloadFile() {
      this.$message("下载进行中，下载完成的素材将在文件夹原素材中显示");
    }
  }
};
</script>

<template>
  <div class="page" @contextmenu.prevent="openMenu">
    <DTFhead :user="user" :factoryType="factoryType"></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 #batchNo="scope">
        <a href="javascript:;" @click="toDetail(scope.row.batchNo)">{{
          scope.row.batchNo
        }}</a>
      </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)"
          >
            <img src="../../assets/download.png" width="30" height="30" />
            <div>下载素材</div></el-button
          >
          <el-button
            type="text"
            disabled
            class="btn flex btnBox"
            @click="changeTypesetting(scope.row)"
            ><img
              src="../../assets/typesetting.png"
              width="30"
              height="30"
              :class="{ disabled: false }"
            />
            <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>
