<template>
  <div class="app-container">
    <!-- 管控栏 -->
    <el-row :gutter="10" class="mb10">
      <el-radio-group v-model="control" @change="controlChange">
        <el-radio :label="0">按宽度拆分</el-radio>
        <el-radio :label="2">按数量拆分</el-radio>
        <el-radio :label="1">按长度拆分</el-radio>
        <el-radio :label="3">长宽混拆</el-radio>
      </el-radio-group>
    </el-row>
    <!-- 分界线 -->
    <el-divider content-position="center">信息录入</el-divider>

    <!-- 信息录入和右侧信息数量提醒 -->
    <el-row :gutter="10">
      <!-- 信息录入 -->
      <el-col :span="18">
        <el-form
          v-show="showSearch"
          ref="queryForm"
          :model="queryParams"
          size="small"
          :rules="rules"
          label-width="98px"
        >
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="条形码" prop="qrCode">
                <el-input
                  ref="barCode"
                  v-model="queryParams.qrCode"
                  placeholder="请输入/扫入条形码"
                  clearable
                  @keyup.enter.native="readQrCode(queryParams.qrCode)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="总长度" prop="sumLength">
                <el-input
                  v-model="queryParams.sumLength"
                  placeholder="请输入总长度"
                  clearable
                  disabled
                >
                  <template slot="append">m</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="总宽度" prop="sumWidth">
                <el-input
                  v-model="queryParams.sumWidth"
                  placeholder="请输入总宽度"
                  clearable
                  disabled
                >
                  <template slot="append">mm</template>
                </el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                size="mini"
                @click="handleToMaterialBatch"
              >
                条码库存查询
              </el-button>
            </el-col> -->
          </el-row>
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item :label="totalWidthLabel" prop="width">
                <el-input
                  v-model="queryParams.width"
                  :disabled="lockedDisabled"
                  placeholder="请输入分拆总宽度"
                  clearable
                >
                  <template v-if="control !== 2" slot="append">{{
                    control === 1 ? "m" : "mm"
                  }}</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="singleWidthLabel" prop="singleQty">
                <el-input
                  v-model="queryParams.singleQty"
                  placeholder="请输入单件宽度"
                  clearable
                >
                  <template v-if="control !== 2" slot="append">{{
                    control === 1 ? "m" : "mm"
                  }}</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="分拆件数" prop="pieceQty">
                <el-input-number
                  v-model="queryParams.pieceQty"
                  style="width: 100%"
                  :min="1"
                  label="分拆件数"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-checkbox
                v-model="isLocked"
                true-label="1"
                false-label="0"
                @change="isLockedChange"
              >
                锁定
              </el-checkbox>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="剩余数量" prop="remainQty">
                <el-input
                  v-model="queryParams.remainQty"
                  disabled
                  placeholder="请输入剩余数量"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="已拆数量" prop="splitQty">
                <el-input
                  v-model="queryParams.splitQty"
                  disabled
                  placeholder="请输入已拆数量"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="打印模板" prop="BtReportId">
                <el-select
                  v-model="queryParams.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="1.5" class="text-right">
              <el-button
                v-hasPermi="['wms:split-order-master:create']"
                type="danger"
                plain
                size="mini"
                :loading="splitLoading"
                @click="handleSplit"
              >
                分拆
              </el-button>
              <!-- <el-button
                type="primary"
                plain
                icon="el-icon-printer"
                size="mini"
                @click="handlePrint"
              >
                打印标签
              </el-button> -->
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="20">
              <el-form-item label="备注说明" prop="remark">
                <el-input
                  v-model="queryParams.remark"
                  type="textarea"
                  :rows="2"
                  placeholder="备注"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
      <!-- 数量信息回显提醒 -->
      <el-col :span="6">
        <el-form
          ref="orderInfoForm"
          :model="orderInfoParams"
          size="small"
          label-width="88px"
        >
          <el-form-item label="条码数量" prop="sumQty" class="item">
            <el-input
              v-model="orderInfoParams.sumQty"
              placeholder="请输入条码数量"
              clearable
              disabled
            />
          </el-form-item>
          <el-form-item label="分拆总数量" prop="splitQty" class="item">
            <el-input
              v-model="orderInfoParams.splitQty"
              placeholder="请输入分拆总数量"
              clearable
              disabled
            />
          </el-form-item>
          <el-form-item label="剩余数量" prop="remainQty" class="item">
            <el-input
              v-model="orderInfoParams.remainQty"
              placeholder="请输入剩余数量"
              clearable
              disabled
            />
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <!-- 主材 -->
    <MainMaterial ref="mainMaterial" class="mb5" />
    <!-- 辅材信息 -->
    <SecondaryMaterials
      ref="secondaryMaterials"
      @toLossSuccess="getList"
      @refresh="getList"
    />
  </div>
</template>

<script>
import {
  getMaterialDemolitionBatch,
  createSplitOrderMaster,
  getSplitOrderInfo,
  getSplitPrintData,
} from "@/api/wms/inLibrary/demergeOrder";
// 是否锁定
const localKey = "IS_LOCKED_ORDER_KEY";
const getLocalIsLocked = () => localStorage.getItem(localKey) || "0";

import MainMaterial from "./components/MainMaterial.vue";
import SecondaryMaterials from "./components/SecondaryMaterials.vue";
import { getAppendixTableData } from "@/api/system/appendix.js";
import { printLabel } from "@/api/common";

export default {
  name: "DemergeOrderDetails",
  components: {
    MainMaterial,
    SecondaryMaterials,
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分拆遮罩层
      splitLoading: false,
      // 管控
      control: 0,
      // 根据管控勾选显示不同
      totalWidthLabel: "分拆总宽度",
      singleWidthLabel: "单件宽度",
      // 锁定时数据置灰
      lockedDisabled: false,
      // 列表
      list: [],
      // 是否锁定
      isLocked: getLocalIsLocked(),
      // 查看参数
      orderInfoParams: {
        remainQty: null,
        sumQty: null,
        splitQty: null,
      },
      // bartender模板列表
      btTemplateList: [],
      // 录入参数
      queryParams: {
        BtReportId: "",
        BtReportUrl: "",
        BtReportName: "",
        HicoreReportName: "",
        reportType: "1",
        pageNo: 1,
        pageSize: 10,
        qrCode: null,
        eBillNo: null,
        length: null,
        width: null,
        singleQty: null,
        createTime: null,
        pieceQty: 1, // 分拆件数
        splitQty: 0,
        remark: null,
        sumLength: null,
        sumWidth: null,
      },
      // 表单参数
      form: {},
      printData: [], // 打印参数
      // 表单校验
      rules: {
        qrCode: [
          { required: true, message: "条形码不能为空", trigger: "blur" },
        ],
        singleQty: [
          { required: true, message: "单件数量(长宽或数量)", trigger: "blur" },
        ],
        pieceQty: [
          { required: true, message: "分拆件数不能为空", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    computedShowBtRow: function () {
      return !!this.$route.query.splitNo;
    },
  },
  created() {
    this.getTemplateList();
    this.autoFocus();
    if (this.$route.query.splitNo) {
      this.getList();
    }
    // eslint-disable-next-line no-unneeded-ternary
    this.lockedDisabled = this.isLocked === "1" ? true : false;
  },
  methods: {
    reportChange(e) {
      const fdIndex = this.btTemplateList.findIndex((ret) => ret.id === e);
      this.queryParams.HicoreReportName = this.btTemplateList[fdIndex].sysName;
      this.queryParams.BtReportName = this.btTemplateList[fdIndex].originName;
      this.queryParams.BtReportUrl = this.btTemplateList[fdIndex].url;
    },
    // 获取BT打印模板
    getTemplateList() {
      getAppendixTableData({
        pageNum: 1,
        pageSize: 999,
        printFlag: "1",
        filesMenuId: "1000000000000000001",
      }).then(({ data }) => {
        this.btTemplateList = data?.list ?? [];
      });
    },
    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);
    },

    async handlePrint() {
      if (!this.queryParams.BtReportUrl || !this.queryParams.BtReportName) {
        this.$message.warning("请选择bartender打印模板");
        return;
      }

      // 打印
      try {
        const data = await getSplitPrintData({
          splitNo: this.$route.query.splitNo,
        });
        const dataParams = data.data?.data || [];
        this.printData.push(...dataParams);
        // 打印参数
        const printParams = {
          printJson: JSON.stringify(this.printData),
          fileUrl: this.queryParams.BtReportUrl,
        };
        await printLabel(printParams); // 打印
      } catch (error) {
        console.log(error);
      } finally {
        this.printData.length = 0;
      }
    },
    /** 查询列表 */
    getList() {
      const params = {
        splitNo: this.$route.query.splitNo,
      };
      getSplitOrderInfo(params).then((res) => {
        const {
          id,
          wmsLabelMasterId,
          parentInfoRespVOList,
          sonInfoRespVOList,
          splitQty,
          splitType,
          remainLength,
          remainQty,
          remainWidth,
          splitLength,
          splitWidth,
        } = res.data;

        // 为$route赋值
        this.$route.query.id = id;

        // 右侧查看参数
        res.data.pieceQty = 1;
        res.data.qrCode = null;

        // 录入参数
        this.queryParams = JSON.parse(JSON.stringify(res.data));
        // 总宽度和总长度不变
        this.queryParams.sumWidth = res.data.width;
        this.queryParams.sumLength = res.data.length;

        this.queryParams.qrCode = wmsLabelMasterId;
        this.control = JSON.parse(JSON.stringify(splitType));

        this.initValues();
        this.orderInfoParams = JSON.parse(JSON.stringify(res.data));

        // 根据分拆类型 填入不同的剩余数量值和已拆数量值
        // 0-》按宽度拆分（默认） 1-》按长度拆分 2-》按数量拆分 3-》长宽混批
        if (splitType === 1) {
          this.queryParams.remainQty = this.queryParams.width = remainLength;
          this.queryParams.splitQty = splitLength;
        } else if (splitType === 2) {
          this.queryParams.remainQty = this.queryParams.width = remainQty;
          this.queryParams.splitQty = splitQty;
        } else {
          this.queryParams.remainQty = this.queryParams.width = remainWidth;
          this.queryParams.splitQty = splitWidth;
        }
        // this.$nextTick(() => {
        // 母卷信息
        this.$refs.mainMaterial.list = parentInfoRespVOList || [];
        // 子卷信息
        this.$refs.secondaryMaterials.list = sonInfoRespVOList || [];
        // })
      });
    },
    // 自动聚焦到条形码
    autoFocus() {
      this.$nextTick(() => {
        this.$refs.barCode.focus();
      });
    },
    // 查询条码库存
    handleToMaterialBatch() {
      this.$router.push({ path: "/inLibrary/material-demolition-batch" });
    },
    // 管控change事件
    controlChange(v) {
      if (this.control === 2) {
        this.totalWidthLabel = "分拆总数量";
        this.singleWidthLabel = "单件数量";
        if (!this.$route.query.splitNo) {
          this.queryParams.width = this.queryParams.remainQty =
            this.queryParams.inQty;
          this.queryParams.splitQty = 0;
        } else {
          this.queryParams.width = this.queryParams.remainQty =
            this.orderInfoParams.remainQty;
          this.queryParams.splitQty = this.orderInfoParams.splitQty;
        }
        // this.queryParams.remainQty = this.queryParams.remainQty
      } else if (this.control === 1) {
        this.totalWidthLabel = "分拆总长度";
        this.singleWidthLabel = "单件长度";
        if (!this.$route.query.splitNo) {
          this.queryParams.width = this.queryParams.remainQty =
            this.queryParams.length;
          this.queryParams.splitQty = 0;
        } else {
          this.queryParams.width = this.queryParams.remainQty =
            this.queryParams.remainLength;
          this.queryParams.splitQty = this.queryParams.splitLength;
        }
      } else if (this.control === 0 || this.control === 3) {
        this.totalWidthLabel = "分拆总宽度";
        this.singleWidthLabel = "单件宽度";
        if (!this.$route.query.splitNo) {
          this.queryParams.width = this.queryParams.remainQty =
            this.$refs.mainMaterial.list[0]?.width;
          this.queryParams.splitQty = 0;
        } else {
          this.queryParams.width = this.queryParams.remainQty =
            this.queryParams.remainWidth;
          this.queryParams.splitQty = this.queryParams.splitWidth;
        }
      }
    },
    // 扫入条形码获取母卷数据
    readQrCode(id) {
      const params = {
        id,
      };
      if (!id || !id.trim()) {
        this.$modal.msgWarning("无效条码，请重新扫入!");
        return;
      }
      getMaterialDemolitionBatch(params).then((res) => {
        if (res.data.list.length === 0) {
          this.$modal.msgWarning("该条码暂未获取到数据！");
          return;
        }
        this.$refs.mainMaterial.list = JSON.parse(
          JSON.stringify(res.data.list)
        );
        // this.queryParams = { ...res.data.list[0], mergedQty: 0, pieceQty: 1 }
        res.data.list[0].pieceQty = 1;
        this.queryParams = JSON.parse(JSON.stringify(res.data.list[0]));
        this.queryParams.sumWidth = this.queryParams.width;
        this.queryParams.sumLength = this.queryParams.length;

        this.queryParams.remainQty = this.queryParams.width;
        this.queryParams.splitQty = 0;
        this.orderInfoParams.sumQty = this.orderInfoParams.remainQty =
          res.data.list[0].inQty;
        this.initValues();
      });
    },
    // 设置初始值
    initValues() {
      this.queryParams.mergedQty = 0;
      // this.queryParams.pieceQty = 1
      this.orderInfoParams.splitQty = 0;
    },
    // 分拆
    async handleSplit() {
      const { id } = this.$route.query;
      try {
        const validate = await this.$refs["queryForm"].validate();
        if (!validate) return; // 验证不通过直接返回

        // 分拆参数
        const params = {
          splitType: this.control,
          wmsLabelMasterId: this.queryParams.qrCode,
          nowSplitQtySum: this.queryParams.width,
          singleQty: this.queryParams.singleQty,
          pieceQty: this.queryParams.pieceQty,
          remark: this.queryParams.remark,
        };
        // 存在id时，带入接口
        if (id) params.id = id;
        this.splitLoading = true;
        const data = await createSplitOrderMaster(params);
        this.$modal.msgSuccess("拆分成功!");
        this.$router.replace({
          path: "/inLibrary/demerge-order-details",
          query: { id, splitNo: data.data },
        });
        this.getList();
      } catch (error) {
        console.log(error);
      } finally {
        this.splitLoading = false;
      }
    },
    // 锁定的change事件
    isLockedChange(v) {
      localStorage.setItem(localKey, v);
      // eslint-disable-next-line no-unneeded-ternary
      this.lockedDisabled = v === "1" ? true : false;
    },
  },
};
</script>
<style lang="scss" scoped>
.item {
  ::v-deep .el-form-item__label {
    color: #f56c6c !important;
  }
}
</style>
