<template>
  <el-dialog
    :visible.sync="visible"
    title="物料合批"
    append-to-body
    width="400px"
    @open="dialogOpen"
    @close="dialogClose"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      size="mini"
      label-width="110px"
    >
      <el-form-item label="物料条码" prop="qrCode">
        <el-input v-model="queryParams.qrCode" disabled />
      </el-form-item>
      <el-form-item label="当前数量" prop="inQty">
        <el-input v-model="queryParams.inQty" disabled />
      </el-form-item>
      <el-form-item label="物料编码" prop="materialNo">
        <el-input v-model="form.materialNo" disabled />
      </el-form-item>
      <el-form-item label="合批条码" prop="mergeQrCode">
        <el-input
          ref="mergeLot"
          v-model="form.mergeQrCode"
          placeholder="请输入或扫入合批条码"
          @change="mergeLotsChange"
        />
      </el-form-item>
      <el-form-item label="合批数量" prop="receiptQty">
        <el-input v-model="form.receiptQty" disabled />
      </el-form-item>
      <el-form-item label="合批后数量" prop="afterMergeQty">
        <el-input
          v-model="form.afterMergeQty"
          placeholder="请输入拆分数量"
          disabled
        />
      </el-form-item>
      <el-form-item label="选择仓库" prop="erpStockName">
        <template slot-scope="scope">
          <StockSelect
            :ref="`stock-${scope.$index}`"
            v-model="queryParams.erpStockId"
            filterable
            @change="
              ($event) => {
                stockChange($event, scope.$index);
              }
            "
          />
        </template>
      </el-form-item>
      <el-form-item label="选择区域" prop="wmsStoreAreaName">
        <template slot-scope="scope">
          <AreaSelect
            :ref="`area-${scope.$index}`"
            v-model="queryParams.wmsStoreAreaId"
            filterable
            @change="
              ($event) => {
                areaChange($event, scope.$index);
              }
            "
          />
        </template>
      </el-form-item>
      <el-form-item label="选择货位" prop="wmsStoreName">
        <template slot-scope="scope">
          <LocationSelect
            :ref="`location-${scope.$index}`"
            v-model="queryParams.wmsStoreId"
            filterable
          />
        </template>
      </el-form-item>
      <el-form-item label="打印模板" 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-form>
    <div slot="footer">
      <el-button type="primary" :loading="batchLoading" @click="ensureBatch"
        >确认合批/打印标签</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { createMerge } from "@/api/wms/inLibrary/materialDemolitionBatch";
import { getInfoByQrCode } from "@/api/wms/base/material";
import { printLabel } from "@/api/common";
import StockSelect from "../../incoming/wareHousing/components/StockSelect.vue";
import AreaSelect from "../../incoming/wareHousing/components/AreaSelect.vue";
import LocationSelect from "../../incoming/wareHousing/components/LocationSelect.vue";
import { getLabelPrintData } from "@/api/wms/incoming/register";
import { getAppendixTableData } from "@/api/system/appendix.js";

export default {
  components: {
    StockSelect,
    AreaSelect,
    LocationSelect,
  },
  data() {
    return {
      printData: [],
      form: {
        materialLots: undefined,
        materialNo: undefined,
        mergeLots: undefined,
        receiptQty: undefined,
        splitQty: undefined,
        wmsStoreAreaId: undefined,
        wmsStoreId: undefined,
        erpStockId: undefined,
        afterMergeQty: undefined,
        printer: "Fabulous F-BP43i",
        BtReportId: "",
        BtReportUrl: "",
        BtReportName: "",
        reportType: "0",
      },
      // bartender模板列表
      btTemplateList: [],
      queryParams: {
        inQty: undefined,
        id: undefined,
        qrCode: undefined,
        erpStockName: "",
        wmsStoreAreaName: "",
        wmsStoreName: "",
        erpStockId: "",
        wmsStoreId: "",
        wmsStoreAreaId: "",
      },
      rules: {
        mergeQrCode: [
          {
            required: true,
            message: "请输入/扫入标签码",
            trigger: "blur",
          },
        ],
        receiptQty: [
          {
            required: true,
            message: "请输入合批数量",
            trigger: "blur",
          },
        ],
        afterMergeQty: [
          {
            required: true,
            message: "请输入合批后的数量",
            trigger: "blur",
          },
        ],
        erpStockId: [
          {
            required: true,
            message: "请选择仓库",
            trigger: "change",
          },
        ],
        wmsStoreAreaId: [
          {
            required: true,
            message: "请选择区域",
            trigger: "change",
          },
        ],
        wmsStoreId: [
          {
            required: true,
            message: "请选择货位",
            trigger: "change",
          },
        ],
      },
      visible: false,
      batchLoading: false,
    };
  },
  created() {
    this.getTemplateList();
  },
  methods: {
    reportChange(e) {
      const fdIndex = this.btTemplateList.findIndex((ret) => ret.id === e);
      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 ?? [];
      });
    },
    // 重置
    reset() {
      this.form = {
        materialLots: undefined,
        materialNo: undefined,
        mergeLots: undefined,
        mergeQty: undefined,
        splitQty: undefined,
        wmsStoreAreaId: undefined,
        wmsStoreId: undefined,
        erpStockId: undefined,
        afterMergeQty: undefined,
        printer: "Fabulous F-BP43i",
        BtReportId: "",
        BtReportUrl: "",
        BtReportName: "",
        reportType: "0",
      };
      this.queryParams = {
        inQty: undefined,
      };
    },
    dialogOpen() {
      this.autoFocus();
    },
    autoFocus() {
      this.$nextTick(() => {
        this.$refs.mergeLot.focus();
      });
    },
    mergeLotsChange(v) {
      if (!this.form.mergeQrCode) {
        this.$modal.msgWarning("请先输入或扫入标签码，标签码不能为空");
        return;
      }
      const params = {
        qrCode: this.form.mergeQrCode,
      };
      getInfoByQrCode(params).then((res) => {
        const { data } = res;
        if (!data) {
          this.$modal.msgWarning("该标签码不存在");
        } else {
          this.form = {
            ...res.data[0],
            printer: "Fabulous F-BP43i",
            BtReportId: "",
            BtReportUrl: "",
            BtReportName: "",
            reportType: "0",
          };
          this.form.afterMergeQty =
            this.form.receiptQty + this.queryParams.inQty;
          this.form.mergeQrCode = v;
        }
      });
    },
    // 合批/打印
    async ensureBatch() {
      if (!this.form.BtReportUrl || !this.form.BtReportName) {
        this.$message.warning("请选择bartender打印模板");
        return;
      }
      this.form.mergeQty = this.form.receiptQty;
      const params = {
        ...this.form,
        ...this.queryParams,
        printer: undefined,
        BtReportId: undefined,
        BtReportUrl: undefined,
        BtReportName: undefined,
        reportType: undefined,
      };
      // Reflect.deleteProperty(params, "printer");
      // Reflect.deleteProperty(params, "BtReportId");
      // Reflect.deleteProperty(params, "BtReportUrl");
      // Reflect.deleteProperty(params, "BtReportName");
      // Reflect.deleteProperty(params, "reportType");
      if (this.queryParams.qrCode === this.form.mergeQrCode) {
        this.$modal.msgWarning("相同批次不能合并");
        return;
      }
      this.batchLoading = true;
      try {
        const result = await createMerge(params);
        this.$modal.msgSuccess("物料合批成功,正在打印...");
        const { data: qrCode } = result;
        const fetchPrintParams = {
          qrCode,
        };
        const printDetailData = await getLabelPrintData(fetchPrintParams);
        const { data: productsDetails } = printDetailData;
        this.printData.push(...productsDetails);
        // 打印参数
        const printParams = {
          printJson: JSON.stringify(this.printData),
          fileUrl: this.form.BtReportUrl,
        };
        await printLabel(printParams); // 打印

        this.$emit("complete");
        this.printData = [];
        this.visible = false;
        this.reset();
      } catch (error) {
        console.log(error);
      } finally {
        this.batchLoading = false;
      }
    },
    stockChange(item, index) {
      if (item) {
        const { id } = item;
        this.$refs[`area-${index}`].options = [];
        this.$refs[`area-${index}`].fetchAreaList(id);
      }
    },
    areaChange(item, index) {
      if (item) {
        const { id } = item;
        this.$refs[`location-${index}`].options = [];
        this.$refs[`location-${index}`].fetchLocationList(id);
      }
    },
    dialogClose() {
      this.reset();
    },
  },
};
</script>
<style></style>
