<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      label-width="68px"
    >
      <el-row :gutter="10">
        <el-col :span="4">
          <el-form-item label="分切单号" prop="eBillNo">
            <el-input
              v-model="queryParams.eBillNo"
              placeholder="请输入分切单号"
              clearable
              disabled
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="物料" prop="materialNo">
            <el-input
              v-model="queryParams.materialNo"
              placeholder="请输入物料编码"
              clearable
              disabled
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="分切状态" prop="slitStatus">
            <DictSelect
              v-model="queryParams.slitStatus"
              disabled
              placeholder="请选择分切状态"
              dict-type="WMS_SLITTING_STATUS"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="损耗" prop="lossQty">
            <el-input
              v-model="queryParams.lossQty"
              placeholder="请输入损耗"
              clearable
              oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,8})?).*$/g, '$1')"
              @keyup.enter.native="handleQuery"
              @input="lossChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="分切类型" prop="splitType">
            <DictSelect
              v-model="queryParams.splitType"
              placeholder="请选择分切类型"
              dict-type="WMS_SPLITTING_TYPE"
              :disabled="queryParams.slitStatus !== '0'"
              @change="splitTypeChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="打印方式" prop="reportType">
            <el-select
              v-model="form.reportType"
              @change="handleChangePrinterType"
            >
              <el-option label="积木打印" value="0">积木打印</el-option>
              <el-option label="bartender打印" value="1"
                >bartender打印</el-option
              >
              <el-option label="智高打印" value="2">智高打印</el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item
            v-if="form.reportType === '1'"
            label="BT模板"
            prop="BtReportId"
          >
            <el-select
              v-model="form.BtReportId"
              placeholder="请选择模板"
              @change="reportChange"
            >
              <el-option
                v-for="item in btTemplateList"
                :key="item.id"
                :label="item.originName"
                :value="item.id"
              >
                <el-row :gutter="10">
                  <el-col :span="12">{{ item.originName }}</el-col>
                  <el-col :span="12" class="text-right">{{
                    item.version
                  }}</el-col>
                </el-row>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item
            v-if="form.reportType !== '0'"
            label="打印机"
            prop="printer"
          >
            <el-select v-model="form.printer" placeholder="请选择打印机">
              <el-option
                v-for="(item, index) in printers"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1.5" class="text-right">
          <el-button
            type="primary"
            plain
            icon="el-icon-printer"
            size="mini"
            @click="handlePrint"
            >打印标签</el-button
          >
          <el-button
            type="primary"
            plain
            icon="el-icon-printer"
            size="mini"
            @click="handlePreviewLabel"
            >打印预览</el-button
          >
          <!-- <el-button
            v-hasPermi="['wms:label-master-slit-plan:create']"
            type="primary"
            plain
            icon="el-icon-edit-outline"
            size="mini"
            :disabled="slitDisabled"
            @click="handleGenerate"
          >生成分切计划</el-button> -->
        </el-col>
      </el-row>
    </el-form>

    <!-- <div class="slideOpen"> -->
    <!-- <i
        class="operateBtn"
        :class="isOpen ? 'el-icon-arrow-right' : 'el-icon-arrow-left'"
        :style="{ right: operatePosition }"
        @click="handleOpenTask"
      /> -->
    <!-- <div v-show="isOpen" class="side"> -->
    <!-- 分切任务支援表 -->
    <!-- <TaskSupport ref="taskSupport" />
      </div> -->

    <!-- <div :class="{ 'sidebar-open': isOpen }" class="leftMain" :style="{ width: mainContentWidth }"> -->
    <!-- 材料汇总 -->
    <TaskSupport
      ref="taskSupport"
      @materialList="handleSelectedMaterial"
      @getSupportList="getSupportList"
    />
    <!-- 分切批次来源 -->
    <BatchSource
      ref="batchSource"
      :active-name="activeName"
      :query-paramspro="queryParams"
      class="batch"
      @batchSourceList="handleSelectedBatch"
    />
    <!-- 分切后规格 -->
    <SlittingSize
      ref="slittingSize"
      :active-name="activeName"
      class="slit"
      @deleteRow="deleteSlitingSize"
    />

    <!-- </div> -->
    <!-- </div> -->

    <!-- 分切物料选择 -->
    <MultipleSelect ref="multipleSelect" />
    <!-- 打印标签 -->
    <SlittingIssue ref="slittingIssue" />
    <HicoreLabelPreview ref="hicoreLabelPreview" :list="previewUrlList" />
  </div>
</template>

<script>
import axios from "axios";
import {
  createSlitPlan,
  deleteSlitPlan,
  updateSlittingType,
} from "@/api/wms/inLibrary/slittingOrder";
import MultipleSelect from "./components/MultipleSelect.vue";
import SlittingSize from "./components/SlittingSize.vue";
import BatchSource from "./components/BatchSource.vue";
import TaskSupport from "./components/TaskSupport.vue";
import SlittingIssue from "./components/SlittingIssue.vue";
import HicoreLabelPreview from "@/components/HicoreLabelPreview/index.vue";
import { isArray } from "min-dash";
import { getAppendixTableData } from "@/api/system/appendix.js";
import { getCuttingPrintBatch } from "@/api/wms/inLibrary/slittingOrder";
import { GetPrinters, Print } from "@/utils/hicorePrinterFunction";

const AccessTokenKey = "ACCESS_TOKEN";

export default {
  name: "SlittingInstruction",
  components: {
    MultipleSelect,
    SlittingSize,
    BatchSource,
    TaskSupport,
    SlittingIssue,
    HicoreLabelPreview,
  },
  provide() {
    return {
      paramsQuery: this.queryParams,
    };
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 展开收起
      isOpen: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      activeName: "slittingSize",
      printers: [],
      preview: false,
      previewUrlList: [],
      // 分切任务单列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 单据打印参数
      tokens: "",
      baseUrl: "",
      reportId: "",
      // 分切完成，单据置灰
      slitDisabled: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        eBillNo: null,
        materialNo: null,
        remark: null,
        loss: null,
        slitStatus: null,
        alitStatus: null,
        createTime: [],
        splitType: "",
      },
      // 更新分切的id
      updateId: null,
      // 表单参数
      form: {
        reportType: "1",
        printer: "Fabulous F-BP43i",
        BtReportId: "",
        BtReportUrl: "",
        BtReportName: "",
        HicoreReportName: "",
      },
      nextIndex: 0,
      nextPrintState: false,
      // bartender模板列表
      btTemplateList: [],
      // 表单校验
      rules: {},
    };
  },
  // computed: {
  //   mainContentWidth() {
  //     return this.isOpen ? 'calc(100% - 850px)' : '100%'
  //   },
  //   queryWidth() {
  //     return this.isOpen ? 'calc(100% - 850px)' : '100%'
  //   },
  //   operatePosition() {
  //     return this.isOpen ? '850px' : '0'
  //   }
  // },
  created() {
    const { slitStatus, ebillNo, materialNo, materialName } = this.$route.query;
    this.queryParams.eBillNo = ebillNo;
    this.queryParams.materialNo = materialNo;
    this.queryParams.materialName = materialName;
    this.queryParams.slitStatus = slitStatus;
    this.queryParams.materialNo =
      "(" + this.queryParams.materialNo + ")" + this.queryParams.materialName;
    this.tokens = localStorage.getItem(AccessTokenKey);
    this.reportId = this.$route.meta.reportId;
    this.baseUrl = process.env.VUE_APP_REPORT_API;
    if (this.queryParams.slitStatus === "2") {
      this.slitDisabled = true;
      this.$nextTick(() => {
        this.$refs.taskSupport.updateDisable = this.slitDisabled;
      });
    } else {
      this.slitDisabled = false;
    }
    this.getTemplateList();
  },
  methods: {
    // 打印预览
    handlePreviewLabel() {
      this.preview = true;
      this.previewUrlList = [];
      this.$refs.hicoreLabelPreview.visable = true;
      this.handleHicorePrint();
    },
    reportChange(e) {
      const fdIndex = this.btTemplateList.findIndex((ret) => ret.id === e);
      this.form.HicoreReportName = this.btTemplateList[fdIndex].originName;
      this.form.BtReportName = this.btTemplateList[fdIndex].originName;
      this.form.BtReportUrl = this.btTemplateList[fdIndex].url;
    },
    // 获取BT打印模板
    getTemplateList() {
      getAppendixTableData({
        pageNum: 1,
        pageSize: 999,
        printFlag: "1",
        filesMenuId: "1000000000000000001",
      }).then(({ data }) => {
        this.btTemplateList = data?.list ?? [];
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        eBillNo: undefined,
        alitStatus: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.$refs.batchSource.getList();
      this.$refs.slittingSize.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.$refs.batchSource.handleQuery();
      this.$refs.slittingSize.handleQuery();
    },
    /** 生成分切任务单 */
    // handleGenerate() {
    //   // createSlitPlan()
    //   const selectedTaskRows = this.$refs.taskSupport.currentRows
    //   const selectedBatchRows = this.$refs.batchSource.currentRows
    //   if (this.queryParams.lossQty === undefined || this.queryParams.lossQty === '' || selectedBatchRows.length === 0 || selectedTaskRows.length === 0) {
    //     this.$modal.msgWarning('损耗数量/批次来源/分切任务不能为空!')
    //     return
    //   }
    //   const taskIds = selectedTaskRows.map(item => {
    //     const { id } = item
    //     return id
    //   })
    //   const params = {
    //     lossQty: this.queryParams.lossQty,
    //     id: selectedBatchRows[0].id,
    //     slitIds: taskIds
    //   }
    //   createSlitPlan(params).then(res => {
    //     this.$modal.msgSuccess('创建成功!')
    //     this.$refs.batchSource.getList()
    //     this.$refs.taskSupport.getList()
    //     this.$refs.slittingSize.getList()
    //   })
    // },
    handleOpenTask() {
      this.isOpen = !this.isOpen;
    },
    reLoading(timeout) {
      const loading = this.$loading({
        lock: true,
        text: "标签打印中，请勿重复操作",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      setTimeout(() => {
        loading.close();
      }, timeout * 1000);
    },
    repeatSendPrint(bodyData) {
      this.nextPrintState = false;
      axios({
        method: "post",
        // url: 'https://content-yeti-immortal.ngrok-free.app/bartenderPrint',
        // url: 'http://qgz855xj.dongtaiyuming.net/bartenderPrint',
        // url: 'http://218.2.10.30:9001/bartenderPrint',
        // 麦禾田内网
        url: "http://192.168.2.253:9001/bartenderPrint",
        data: bodyData,
      })
        .then((e) => {
          this.nextPrintState = true;
          if (e.data.code !== 200) {
            this.$message.error(e.data.msg);
          } else {
            this.nextIndex += 1;
          }
        })
        .catch((e) => {
          // 出现问题，重新发送
          setTimeout(() => {
            this.repeatSendPrint(bodyData);
          }, 500);
        });
    },
    // 补打方式选择事件
    handleChangePrinterType(e) {
      this.form.printer = "";
      this.printers = [];
      switch (e) {
        case "0":
          break;
        case "1":
          this.printers = [
            {
              label: "麦禾田（热压）",
              value: "Fabulous F-BP43i",
            },
            {
              label: "麦禾田（仓库）",
              value: "Fabulous F-BP43i (cangku)",
            },
            {
              label: "麦禾田（生产打包）",
              value: "Zebra ZT230 (300 dpi)",
            },
          ];
          break;
        case "2":
          GetPrinters()
            .then(({ printer, printers }) => {
              // 设置上次使用的打印机
              this.form.printer = printer;
              this.printers = printers;
            })
            .catch((e) => {
              this.$message.error(e);
            });
          break;
      }
    },
    // 智高标签打印
    async handleHicorePrint() {
      if (
        !this.form.printer ||
        Object.prototype.toString.call(this.form.printer) !== "[object String]"
      ) {
        this.$message.warning("请选择打印机");
        return;
      }
      const { data } = await getCuttingPrintBatch({
        id: this.queryParams.eBillNo,
      });
      const reportDataList = data.data ?? [];
      const totalSize = reportDataList.length;
      // loading
      this.reLoading(reportDataList.length);
      if (totalSize === 0) return;

      const printParams = {
        printer: this.form.printer,
        Preview: this.preview ? "3" : "0",
        TemplateURL: "http://113.105.183.190:9167/bucket159",
        TemplateName: this.form.HicoreReportName,
        PrintData: reportDataList,
      };
      const _this = this;
      if (printParams.Preview === "3") {
        for (let x = 0; x < reportDataList.length; x++) {
          (function (x) {
            printParams.PrintData = [reportDataList[x]];
            Print(printParams)
              .then((data) => {
                _this.previewUrlList.push(data[1]);
              })
              .catch((e) => {
                _this.$message.error(e);
              });
          })(x);
        }
      } else {
        Print(printParams)
          .then((data) => {})
          .catch((e) => {
            this.$message.error(e);
          });
      }
      this.preview = false;
      this.$message.success("标签打印成功");
    },
    // 打印分切后标签
    handlePrint() {
      // 智高标签打印
      if (this.form.reportType === "2") {
        this.handleHicorePrint();
        return;
      }
      if (this.form.reportType === "0") {
        const { eBillNo } = this.queryParams;
        const src = `${this.baseUrl}/jmreport/view/${this.reportId}?token=${this.tokens}&id=${eBillNo}`;
        this.$refs.slittingIssue.dialogVisible = true;
        this.$refs.slittingIssue.src = src;
      } else {
        // 解决第二次打印只打印单条数据问题
        this.nextIndex = 0;
        if (!this.form.BtReportUrl || !this.form.BtReportName) {
          this.$message.warning("请选择bartender打印模板");
          return;
        }
        if (!this.form.printer) {
          this.$message.warning("请选择打印机");
          return;
        }
        getCuttingPrintBatch({ id: this.queryParams.eBillNo }).then((ret) => {
          const reportDataList = ret.data.data ?? [];
          const totalSize = reportDataList.length;
          const bodyDataList = [];
          // loading
          this.reLoading(reportDataList.length);
          if (totalSize === 0) return;

          this.repeatSendPrint({
            filePath: this.form.BtReportUrl,
            fileName: this.form.BtReportName,
            printer: this.form.printer,
            dataSource: reportDataList[0],
          });
          reportDataList.forEach((item, index) => {
            bodyDataList.push({
              filePath: this.form.BtReportUrl,
              fileName: this.form.BtReportName,
              printer: this.form.printer,
              dataSource: item,
            });
            if (bodyDataList.length === totalSize) {
              const timer = setInterval(async () => {
                if (this.nextPrintState && this.nextIndex < totalSize) {
                  this.repeatSendPrint(bodyDataList[this.nextIndex]);
                }
                // 打印完毕，清除定时器
                if (this.nextIndex === totalSize) {
                  clearInterval(timer);
                }
              }, 750);
            }
          });
        });
      }
    },
    // 获取选中的物料
    handleSelectedMaterial(data) {
      this.selectedMaterialList = data || [];
      const { width } = this.selectedMaterialList[0] || 0;
      const minWidth = this.selectedMaterialList.reduce(
        (acc, cur) => (cur.width < acc ? cur.width : acc),
        width
      );
      this.$refs.batchSource.queryParams.width = minWidth;
      this.$refs.batchSource.getList();
      this.$refs.batchSource.isSelectedMaterial =
        this.queryParams.slitStatus === "2" ? false : data.length > 0;
    },
    lossChange(v) {
      if (v && isArray(this.selectedMaterialList)) {
        this.$refs.batchSource.isSelectedMaterial =
          !v || this.queryParams.slitStatus === "2"
            ? false
            : this.selectedMaterialList.length > 0;
      }
    },
    handleSelectedBatch(data) {
      const { lossQty } = this.queryParams;
      const { selectedMaterialList, $modal, $refs } = this;
      const taskIds = selectedMaterialList.map(({ id }) => id);
      const params = {
        lossQty,
        id: data[0].id,
        slitIds: taskIds,
      };
      createSlitPlan(params)
        .then(() => {
          $modal.msgSuccess("创建成功!");
        })
        .finally(() => {
          this.$refs.batchSource.handleCancelSelect();
          $refs.batchSource.getList();
          $refs.taskSupport.getList();
          $refs.slittingSize.getList();
        });
    },
    // 删除分切后规格
    deleteSlitingSize(row) {
      const { id, materialNo } = row;
      this.$modal
        .confirm('是否确认删除物料编码为"' + materialNo + '"的数据项?')
        .then(function () {
          return deleteSlitPlan(id);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
        })
        .finally(() => {
          this.$refs.slittingSize.getList();
          this.$refs.batchSource.getList();
          this.$refs.taskSupport.getList();
        })
        .catch(() => {});
    },
    getSupportList(data) {
      this.queryParams.slitStatus = data.slitStatus + "";
      this.queryParams.splitType = data.slitType;
      this.updateId = data.masterId;
    },
    // 更新分切类型
    splitTypeChange(v) {
      const params = {
        id: this.updateId,
        slitType: v,
      };
      updateSlittingType(params).then((res) => {
        this.$modal.msgSuccess("分切类型更新成功!");
      });
    },
  },
};
</script>

<style scoped>
/* .searchCase {
  width: 100%;
}
.selects {
  position: relative;
}
.icon {
  position: absolute;
  top: 14px;
  right: 12px;
  width: 40px;
  height: 30px;
  border: none;
  padding: 10px;
}
.app-container {
  position: relative;
}
.slideOpen .side {
  position: absolute;
  top: 12%;
  right: 0;
  width: 850px;
  height: 100%;
  overflow-y: auto;
  box-shadow: 0 0 10px rgba(0, 0, 0, .2);
  transition: all .3s;
}
.slideOpen .operateBtn {
  position: absolute;
  right: 850px;
  top: 300px;
}
.slideOpen .operateBtn:hover {
  cursor: pointer;
}
.slideOpen .main-content {
  margin-right: 850px;
  transition: all .3s;
}
::deep.leftMain {
  height: 100%!important;
}
::deep.batch {
  height: 50%!important;
}
::deep.slit {
  height: 50%!important;
} */
</style>
