<template>
  <div>
    <el-row style="margin-top: 25px">
      <el-row v-if="flag == 'edit'" class="table-title">
        <div>
          <el-button size="small" type="primary" @click="removeBatch">{{
            $t("批量移出合包")
          }}</el-button>
          <!--lanbm 2024-06-20 处理封箱确认对话框带出的体积异常问题-->
          <el-button size="small" type="primary" @click="sealBox">{{
            $t("封箱")
          }}</el-button>
        </div>
        <div>
          <template>
            <el-input
              v-model="qrCode"
              :placeholder="$t('请输入二维码/条码编号')"
              clearable
            ></el-input>
            <el-button type="primary" @click="handlerBatchCreate()">{{
              $t("确定")
            }}</el-button>
            <el-button
              type="primary"
              @click="handlerClick('batchInput', $t('批量输入'))"
              >{{ $t("批量输入") }}</el-button
            >
            <el-button
              type="primary"
              @click="handlerClick('correction', $t('装箱纠错'))"
              >{{ $t("装箱纠错") }}</el-button
            >
            <el-button
              type="primary"
              @click="handlerClick('correctionOrder', $t('批量装箱纠错'))"
              >{{ $t("批量装箱纠错") }}</el-button
            >
          </template>
        </div>
      </el-row>
      <el-row style="margin-top: 5px">
        <el-table
          border
          :data="pagList"
          max-height="600px"
          @select="checkboxSelect"
          @select-all="checkboxSelect"
        >
          <el-table-column
            type="selection"
            align="center"
            width="55"
            fixed="left"
          />
          <el-table-column
            align="center"
            :label="$t('序号')"
            width="50"
            type="index"
          />
          <el-table-column :label="$t('订单号')" align="center" prop="orderNo">
            <template slot-scope="scope">
              <router-link
                :to="{
                  path: '/order/detail',
                  query: { orderId: scope.row.orderId },
                }"
                class="link-type"
              >
                <span>{{ scope.row.orderNo }}</span>
              </router-link>
            </template>
          </el-table-column>
          <el-table-column :label="$t('商品信息')" width="250px" align="center">
            <template slot-scope="{ row }">
              <div v-for="item in row.orderItemDOS" :key="item.orderItemId">
                {{ $l(item, "prodTitle") }}
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="$t('备案')" align="center">
            <template slot-scope="{ row }">
              <dict-tag
                :type="DICT_TYPE.PRODUCT_RECORD_ATTRIBUTE"
                :value="row.productRecord"
              />
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('计划/已装')"
            align="center"
            prop="sumNum"
          >
            <template slot-scope="scope">
              <el-link type="primary" @click.native="orderClick(scope.row)">
                {{ scope.row.sumNum }}/{{ scope.row.installNum }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column :label="$t('纸箱尺寸')" align="center">
            <template slot-scope="{ row }">
              <div v-for="item in row.orderItemDOS" :key="item.orderItemId">
                {{
                  item.warehouseInInfoVO ? item.warehouseInInfoVO.boxGauge : ""
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('体积')"
            align="center"
            prop="sumVolume"
          />
          <el-table-column
            :label="$t('重量')"
            align="center"
            prop="sumWeight"
          />
          <el-table-column
            :label="$t('数量（个）')"
            align="center"
            prop="sumQuantity"
          />
          <el-table-column
            :label="$t('储位')"
            align="center"
            prop="positionNo"
            width="250px"
          >
            <template slot-scope="{ row }">
              <div v-for="item in row.orderItemDOS" :key="item.orderItemId">
                {{
                  item.warehouseInInfoVO &&
                  item.warehouseInInfoVO.orderLocationMergeVOSet
                    ? notset(
                        getpositionNo(
                          item.warehouseInInfoVO.orderLocationMergeVOSet
                        )
                      )
                    : ""
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="$t('理货时间')" align="center">
            <template slot-scope="scope">
              {{ formatDate(scope.row.tallyTime, "YYYY-MM-DD HH:mm:ss") }}
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('操作')"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="removePkg(scope.row)"
                >{{ $t("移出") }}</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.page"
          :limit.sync="queryParams.rows"
          @pagination="getList"
        />
      </el-row>
      <!-- 封箱 -->
      <el-dialog
        :title="$t('封箱确认')"
        :visible.sync="sealBoxdialogVisible"
        width="800px"
        :modal-append-to-body="false"
        append-to-body
      >
        <el-form ref="sealBoxForm" :model="sealBoxForm" label-width="100px">
          <el-form-item :label="$t('箱号')" prop="pkgNum">
            {{ pkgData.pkgNum }}
          </el-form-item>
          <el-row>
            <el-col :span="8">
              <el-form-item
                :label="$t('长')"
                prop="pkgLength"
                :rules="[
                  {
                    pattern:
                      /^((0{1}\.\d{1,2})|([1-9]\d*\.{1}\d{1,2})|([1-9]+\d*))$/,
                    message: $t('长度保留两位小数'),
                  },
                ]"
              >
                <el-input
                  v-model="sealBoxForm.pkgLength"
                  style="width: 150px"
                  @change="culSumVolume"
                >
                  <template slot="append">
                    {{ $t("cm") }}
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                :label="$t('宽')"
                prop="pkgWidth"
                :rules="[
                  {
                    pattern:
                      /^((0{1}\.\d{1,2})|([1-9]\d*\.{1}\d{1,2})|([1-9]+\d*))$/,
                    message: $t('宽度保留两位小数'),
                  },
                ]"
              >
                <el-input
                  v-model="sealBoxForm.pkgWidth"
                  style="width: 150px"
                  @change="culSumVolume"
                >
                  <template slot="append">
                    {{ $t("cm") }}
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                :label="$t('高')"
                prop="pkgHight"
                :rules="[
                  {
                    pattern:
                      /^((0{1}\.\d{1,2})|([1-9]\d*\.{1}\d{1,2})|([1-9]+\d*))$/,
                    message: $t('高度保留两位小数'),
                  },
                ]"
              >
                <el-input
                  v-model="sealBoxForm.pkgHight"
                  style="width: 150px"
                  @change="culSumVolume"
                >
                  <template slot="append">
                    {{ $t("cm") }}
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item
            :label="$t('体积')"
            prop="sumVolume"
            :rules="[
              { required: true, message: $t('请填写体积') },
              {
                pattern:
                  /^((0{1}\.\d{1,2})|([1-9]\d*\.{1}\d{1,2})|([1-9]+\d*))$/,
                message: $t('体积保留两位小数'),
              },
            ]"
          >
            <el-input v-model="sealBoxForm.sumVolume" style="width: 180px">
              <template slot="append">
                {{ $t("m³") }}
              </template>
            </el-input>
          </el-form-item>
          <el-form-item
            :label="$t('重量')"
            prop="sumWeight"
            :rules="[
              { required: true, message: $t('请填写重量') },
              {
                pattern:
                  /^((0{1}\.\d{1,2})|([1-9]\d*\.{1}\d{1,2})|([1-9]+\d*))$/,
                message: $t('重量保留两位小数'),
              },
            ]"
          >
            <el-input v-model="sealBoxForm.sumWeight" style="width: 180px">
              <template slot="append">
                {{ $t("kg") }}
              </template>
            </el-input>
          </el-form-item>
          <el-form-item
            :label="$t('箱数')"
            prop="sumNum"
            :rules="[
              { required: true, message: $t('请填写数量') },
              {
                pattern:
                  /^((0{1}\.\d{1,2})|([1-9]\d*\.{1}\d{1,2})|([1-9]+\d*))$/,
                message: $t('数量保留两位小数'),
              },
            ]"
          >
            <el-input v-model="sealBoxForm.sumNum" style="width: 180px">
              <template slot="append">
                {{ $t("箱") }}
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <div style="text-align: center">
          <el-button size="small" type="primary" @click="sealBoxSubmit">{{
            $t("确定")
          }}</el-button>
          <el-button
            size="small"
            type="primary"
            @click="sealBoxdialogVisible = false"
            >{{ $t("取消") }}</el-button
          >
        </div>
      </el-dialog>
      <!-- 打印标签 -->
      <el-dialog
        :title="$t('封箱标签')"
        :visible.sync="printdialogVisible"
        width="350px"
        :modal-append-to-body="false"
        append-to-body
      >
        <print-tag v-if="printdialogVisible" :tagData="tagData" />
      </el-dialog>
      <!-- 对话框 -->
      <el-dialog
        custom-class="shipping-dialog"
        :title="checkDialogConfig.title"
        :visible.sync="checkDialogConfig.dialogVisible"
        :fullscreen="checkDialogConfig.fullscreen"
        :width="checkDialogConfig.width"
        :modal-append-to-body="false"
        append-to-body
      >
        <!-- 已装未装订单 -->
        <template v-if="checkDialogConfig.type === 'orderTable'">
          <el-table :data="orderList" height="500px" border>
            <el-table-column
              :label="$t('已装')"
              align="center"
              prop="loadTag"
            />
            <el-table-column
              :label="$t('未装')"
              align="center"
              prop="unloadTag"
            />
          </el-table>
        </template>
        <!-- 装柜纠错 -->
        <template
          v-if="
            checkDialogConfig.type === 'correction' &&
            checkDialogConfig.dialogVisible
          "
        >
          <el-form
            ref="correctionForm"
            :rules="rules"
            :model="correctionObj"
            label-position="top"
          >
            <el-form-item
              :label="$t('装柜纠错（二维码/条形码编号）')"
              prop="qrCode"
            >
              <el-input
                v-model="correctionObj.qrCode"
                :placeholder="$t('请输入二维码/条形码编号')"
                clearable
              />
            </el-form-item>
          </el-form>
          <el-row class="operate-button">
            <el-button type="primary" @click="delCheck()">{{
              $t("提交")
            }}</el-button>
            <el-button @click="closeDialog2">{{ $t("取消") }}</el-button>
          </el-row>
        </template>
        <!-- 批量装柜纠错（订单号） -->
        <template
          v-if="
            checkDialogConfig.type === 'correctionOrder' &&
            checkDialogConfig.dialogVisible
          "
        >
          <el-form
            ref="orderForm"
            :rules="rules"
            :model="orderObj"
            label-position="top"
          >
            <el-form-item
              :label="$t('装柜纠错') + '（' + $t('订单号') + '）'"
              prop="orderNo"
            >
              <el-input
                type="textarea"
                :rows="3"
                v-model="orderObj.orderNo"
                :placeholder="$t('请输入，多个以逗号分隔')"
                clearable
              />
            </el-form-item>
          </el-form>
          <el-row class="operate-button">
            <el-button type="primary" @click="batchDelCheck()">{{
              $t("提交")
            }}</el-button>
            <el-button @click="closeDialog2">{{ $t("取消") }}</el-button>
          </el-row>
        </template>
        <!-- 装柜批量输入 -->
        <template
          v-if="
            checkDialogConfig.type === 'batchInput' &&
            checkDialogConfig.dialogVisible
          "
        >
          <el-form ref="batchForm" :rules="rules" :model="batchObj">
            <el-form-item label="" prop="qrCode" class="two-element">
              <el-input
                v-model="batchObj.qrCode"
                :placeholder="$t('请输入订单号')"
                clearable
              />
              <el-button
                style="marginleft: 10px"
                type="primary"
                @click="queryOrderInfo"
                >{{ $t("确定") }}</el-button
              >
            </el-form-item>

            <el-row>
              <el-col :span="12">
                <el-form-item :label="$t('订单号')">
                  {{ boxOrderInfo.orderNo }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('箱数')">
                  <el-input-number
                    v-if="boxOrderInfo.isExternalWarehouse === 1"
                    v-model="batchObj.boxNum"
                    :min="0"
                    :max="boxOrderInfo.num"
                  />
                  <template v-else>
                    {{ boxOrderInfo.num }}
                  </template>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item :label="$t('方数')">
                  {{ getTotlContent(boxOrderInfo, ["volume"]) }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('重量')">
                  {{ getTotlContent(boxOrderInfo, ["weight"]) }}
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-row class="operate-button">
            <el-button
              type="primary"
              :disabled="boxOrderInfo.orderId ? false : true"
              @click="batchLoad"
              >{{ $t("提交") }}</el-button
            >
            <el-button @click="closeDialog2">{{ $t("取消") }}</el-button>
          </el-row>
        </template>
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
import {
  getPkgPageByPkgId,
  deleteRelate,
  deleteBatchRelate,
  getMergePkgInfoById,
  updateMergePkg,
  getMergeTagById,
  checkInfoSingleCreate,
  checkInfoBatchCreate,
  getOrderTagList,
  checkInfoSingleDelete,
  checkInfoBatchDelete,
} from "@/api/ecw/boxAir";
import { formatDate, serviceMsg, getTotlContent } from "../../utils";
import { getOrderDetailByBoxNo } from "@/api/ecw/boxSea";
import printTag from "./printTag.vue";
export default {
  props: {
    pkgData: Object,
    shipmentObj: Object,
    flag: {
      type: String,
      default: "edit",
    },
  },
  components: {
    printTag,
  },
  data() {
    return {
      pagList: [],
      // 查询参数
      queryParams: {
        page: 1,
        rows: 10,
      },
      total: 0,
      // 勾选行
      selectedRows: [],
      sealBoxdialogVisible: false,
      sealBoxForm: {},
      printdialogVisible: false,
      tagData: {},
      // 二维码/条码编号
      qrCode: "",
      // 批量输入
      batchObj: {
        boxNum: 0,
      },
      // 批量纠错（订单号）
      orderObj: {},
      // 纠错
      correctionObj: {},
      // 弹窗配置
      checkDialogConfig: {
        title: "",
        dialogVisible: false,
        width: "30%",
        type: "",
        fullscreen: false,
      },
      // 订单信息
      boxOrderInfo: {},
      rules: {
        qrCode: [
          { required: true, message: this.$t("必填"), trigger: "change" },
        ],
        orderNo: [
          { required: true, message: this.$t("必填"), trigger: "change" },
        ],
      },
      // 已理/未理
      orderList: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      let queryParams = {
        id: this.pkgData.id,
        shipmentId: this.shipmentObj.id,
        ...this.queryParams,
      };
      getPkgPageByPkgId(queryParams).then((res) => {
        this.pagList = res.data.list;
        this.total = res.data.total;
        console.log(this.pagList, "222");
      });
    },
    // 格式化日期
    formatDate,
    getTotlContent,
    //去重
    notset(string) {
      if (!string) return string;
      let arr = string.split(",");
      arr = arr.filter((item, index) => {
        return arr.indexOf(item) == index;
      });
      return arr.toString();
    },
    //计算封箱体积
    culSumVolume() {
      let temp =
        this.sealBoxForm.pkgLength * this.sealBoxForm.pkgWidth * 0.01 * 0.01;
      let sumVolume = this.accMul(temp, this.sealBoxForm.pkgHight * 0.01);
      if (sumVolume <= 0) {
        sumVolume = 0.01;
      }
      this.$set(this.sealBoxForm, "sumVolume", sumVolume);
    },
    accMul(arg1, arg2) {
      var m = 0,
        s1 = arg1.toString(),
        s2 = arg2.toString();
      try {
        m += s1.split(".")[1].length;
      } catch (e) {}
      try {
        m += s2.split(".")[1].length;
      } catch (e) {}
      let num =
        (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
        Math.pow(10, m);
      return num.toFixed(2);
    },
    getpositionNo(arr) {
      if (!arr) return arr;
      let data = [];
      arr.forEach((item) => {
        data.push(item.areaName + item.locationName);
      });
      return data.toString();
    },
    removePkg(row) {
      deleteRelate(this.pkgData.id, row.orderId).then(() => {
        this.$message.success(this.$t("移出成功"));
        this.getList();
        this.$emit("reload");
      });
    },
    // 选中
    checkboxSelect(selection) {
      this.selectedRows = selection;
    },
    removeBatch() {
      if (this.selectedRows.length === 0) {
        this.$message.error(this.$t("请选择需要移出的订单"));
        return;
      }
      let data = [];
      this.selectedRows.forEach((item) => {
        let json = {
          pkgId: this.pkgData.id,
          orderId: item.orderId,
        };
        data.push(json);
      });
      deleteBatchRelate(data).then(() => {
        this.$message.success(this.$t("移出成功"));
        this.getList();
      });
    },
    //封箱
    sealBox() {
      let flag = false;
      let orderNo = "";
      this.pagList.forEach((item) => {
        if (item.installNum != item.sumNum) {
          flag = true;
          orderNo = orderNo + "《" + item.orderNo + "》";
        }
      });
      if (flag) {
        this.$message.error(
          this.$t(`订单号${orderNo}未完成装箱,请完成全部订单装箱后重试`)
        );
        return;
      }
      getMergePkgInfoById(this.pkgData.id).then((res) => {
        this.sealBoxForm = {
          pkgHight: res.data.pkgHight,
          pkgLength: res.data.pkgLength,
          pkgWidth: res.data.pkgWidth,
          sumNum: res.data.sumNum,
          sumVolume: res.data.sumVolume,
          sumWeight: res.data.sumWeight,
        };
        this.sealBoxdialogVisible = true;
      });
    },
    sealBoxSubmit() {
      this.$refs["sealBoxForm"].validate((valid) => {
        if (!valid) {
          return;
        }
        this.sealBoxForm.shipmentId = this.shipmentObj.id;
        this.sealBoxForm.id = this.pkgData.id;
        this.sealBoxForm.status = 3;
        updateMergePkg(this.sealBoxForm).then(() => {
          this.sealBoxdialogVisible = false;
          this.$confirm(
            this.$t("箱号:") +
              this.pkgData.pkgNum +
              this.$t("，请问是否打印封箱标签?"),
            this.$t("封箱成功"),
            {
              confirmButtonText: this.$t("立刻打印"),
              cancelButtonText: this.$t("稍后再试"),
            }
          )
            .then((_) => {
              getMergeTagById(this.pkgData.id).then((res) => {
                this.tagData = res.data;
                this.printdialogVisible = true;
              });
            })
            .catch((_) => {
              this.$emit("closeDialog");
            });
        });
      });
    },
    /** 表格订单号点击 */
    orderClick(row) {
      getOrderTagList({ orderId: row.orderId, type: 1 }).then((res) => {
        const { data = {} } = res;
        this.orderList = [];
        // 取最长的list
        let dataLength = data.loadList.length;
        if (data.unLoadList.length > dataLength) {
          dataLength = data.unLoadList.length;
        }

        // 组装数据，用一个table组件渲染
        for (let index = 0; index < dataLength; index++) {
          this.orderList.push({
            loadTag: data.loadList[index],
            unloadTag: data.unLoadList[index],
          });
        }
      });
      this.shwoDialog({
        type: "orderTable",
        title: row.selfNo,
      });
    },
    /** 点击事件统一入口 */
    handlerClick(type, title) {
      this.shwoDialog({ type, title });
    },
    /** 弹窗事件 */
    shwoDialog(config) {
      this.$set(this.checkDialogConfig, "title", config.title);
      this.$set(this.checkDialogConfig, "type", config.type);
      switch (config.type) {
        case "orderTable":
          this.$set(this.checkDialogConfig, "fullscreen", false);
          break;
        case "batchInput":
          this.$set(this.checkDialogConfig, "fullscreen", false);
          this.batchObj = { boxNum: 0 };
          this.boxOrderInfo = {};
          break;
        case "correction":
          this.$set(this.checkDialogConfig, "fullscreen", false);
          this.correctionObj = {};
          break;
        case "correctionOrder":
          this.$set(this.checkDialogConfig, "fullscreen", false);
          this.orderObj = {};
          break;
      }
      this.$set(this.checkDialogConfig, "dialogVisible", true);
    },
    /** 关闭弹窗 */
    closeDialog2() {
      this.$set(this.checkDialogConfig, "dialogVisible", false);
    },
    /* 创建装柜标签 */
    handlerBatchCreate() {
      if (!this.qrCode) {
        this.$message.error(this.$t("请输入二维码/条码编号"));
        return;
      }
      let params = {
        shipmentId: this.shipmentObj.id,
        pkgId: this.pkgData.id,
        type: 1,
      };
      params.orderNumCode = this.qrCode;
      checkInfoSingleCreate(params).then((res) => {
        serviceMsg(res, this).then(() => {
          this.qrCode = "";
          this.getList();
        });
      });
    },
    queryOrderInfo() {
      this.$refs["batchForm"].validate((valid) => {
        if (valid) {
          getOrderDetailByBoxNo({
            orderNumCode: this.batchObj.qrCode,
            shipmentId: this.shipmentObj.id,
          }).then((res) => {
            const { data } = res;
            this.boxOrderInfo = data;
            this.batchObj.boxNum = Number(data.num);
          });
        }
      });
    },
    /**批量创建装柜标签 */
    batchLoad() {
      if (!this.boxOrderInfo.orderId) {
        this.$message.error(this.$t("请输入订单号"));
        return;
      }
      if (this.batchObj.boxNum === 0) {
        this.$message.error(this.$t("箱数不能为0"));
        return;
      }

      let params = {
        orderId: this.boxOrderInfo.orderId,
        orderNo: this.boxOrderInfo.orderNo,
        shipmentId: this.shipmentObj.id,
        pkgId: this.pkgData.id,
        type: 1,
      };
      checkInfoBatchCreate(params).then((res) => {
        serviceMsg(res, this).then(() => {
          this.closeDialog2();
          this.boxOrderInfo = {};
          this.getList();
        });
      });
    },
    /**装柜纠错 */
    delCheck() {
      if (!this.correctionObj.qrCode) {
        this.$message.error(this.$t("请输入二维码/条码编号"));
        return;
      }
      let params = {
        shipmentId: this.shipmentObj.id,
        type: 1,
        pkgId: this.pkgData.id,
        orderNumCode: this.correctionObj.qrCode,
      };
      checkInfoSingleDelete(params).then((res) => {
        serviceMsg(res, this).then(() => {
          this.closeDialog2();
          this.getList();
        });
      });
    },
    /**批量装柜纠错 */
    batchDelCheck() {
      if (!this.orderObj.orderNo) {
        this.$message.error(this.$t("请输入订单号"));
        return;
      }
      let params = {
        shipmentId: this.shipmentObj.id,
        pkgId: this.pkgData.id,
        type: 1,
        orderNo: this.orderObj.orderNo,
      };
      checkInfoBatchDelete(params).then((res) => {
        serviceMsg(res, this).then(() => {
          this.closeDialog2();
          this.getList();
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.table-title {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  > div:first-child {
    flex: 1;
    font-size: 16px;
  }
  > div:last-child {
    display: flex;
    > .el-input {
      margin-right: 10px;
    }
  }
}
</style>
