<script>
import BaseTable from "../../components/BaseTable.vue";
const { remote, ipcRenderer } = require("electron");
const { getDTFSetting, setDTFSetting } = 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: "",

      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.loadLocalConfig();
    this.fetchBatchList();
  },

  methods: {
    async loadLocalConfig() {
      try {
        if (!getDTFSetting().downloadDir) {
          const path = ipcRenderer.sendSync("get-install-path");
          setDTFSetting({ downloadDir: path });
        }
      } catch (error) {
        console.log(error);
      }
    },

    //定时任务
    async fetchBatchList(value) {
      try {
        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;
        }
      } catch (err) {
        console.error("批次列表拉取失败", err);
      }
    },

    handleSelect(rows) {
      console.log("选中行", rows);
      this.selectionList = rows;
    },
    handleSizeChange(size) {
      this.pageInfo.pageSize = size;
      this.pageInfo.currentPage = 1;
      this.settingRes();
    },
    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.radio = "";
        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 newUrls = data.flatMap(el => el.urls);
        // console.log(311, newUrls);
        // return;
        const res = await this.$api.post("/downloadMaterial", {
          urls: newUrls,
          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>
