<template>
  <div class="app-container">
    <!-- 出货单详情步骤条 -->
    <el-card class="mb10">
      <div slot="header" class="clearfix flexbox">
        <span class="font-bold">出货单详情</span>
      </div>
      <el-steps
        :active="orderStatus"
        finish-status="success"
        simple
        style="margin-bottom: 20px"
      >
        <el-step title="出货通知下达" />
        <el-step title="出货打码" />
        <el-step title="装箱确认" />
        <el-step title="出货签收" />
      </el-steps>
      <el-form
        v-show="showSearch"
        ref="queryForm"
        :model="queryParams"
        size="small"
        :rules="rules"
        label-width="98px"
      >
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="出货单号" prop="saleOutNo">
              <el-input
                v-model="queryParams.saleOutNo"
                placeholder="创建后自动生成出货单号"
                clearable
                disabled
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户编码" prop="customerCode">
              <CustomerCodeSelect
                v-model="queryParams.customerCode"
                clearable
                @change="handleCustomerCodeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称" prop="customerName">
              <el-input
                v-model="queryParams.customerName"
                placeholder="请输入客户名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="送货地址" prop="deliveryAddress">
              <el-input
                v-model="queryParams.deliveryAddress"
                placeholder="请输入送货地址"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="送货时间" prop="deliveryTime">
              <el-date-picker
                v-model="queryParams.deliveryTime"
                type="datetime"
                placeholder="请选择送货时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="签收状态" prop="signStatus">
              <DictSelect
                v-model="queryParams.signStatus"
                disabled
                placeholder="请选择签收状态"
                dict-type="WMS_SIGN_STATUS"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收货方地址" prop="shipToAddress">
              <el-input
                v-model="queryParams.shipToAddress"
                placeholder="请输入收货方地址"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收货人姓名" prop="consignee">
              <el-input
                v-model="queryParams.consignee"
                placeholder="请输入收货人姓名"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="phoneNumber">
              <el-input
                v-model="queryParams.phoneNumber"
                placeholder="请输入联系电话"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb5">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            size="mini"
            icon="el-icon-thumb"
            :loading="submitLoading"
            @click="handleSubmit"
            >提交</el-button
          >
          <el-button
            type="primary"
            plain
            size="mini"
            icon="el-icon-printer"
            :disabled="!$route.query.saleOutNo"
            @click="handleToSelectPrint"
            >标签打印</el-button
          >
          <el-button
            type="warning"
            plain
            size="mini"
            icon="el-icon-check"
            @click="handleApproval"
            >审批</el-button
          >
        </el-col>
      </el-row>
    </el-card>

    <el-tabs
      ref="tabs"
      v-model="tabSelected"
      type="border-card"
      @tab-click="handleTabClick"
    >
      <!-- 列表 -->
      <el-tab-pane label="出货信息" name="info">
        <el-row :gutter="5" class="mb5">
          <el-col :span="1.5" class="fr">
            <el-button
              icon="el-icon-plus"
              size="mini"
              plain
              type="primary"
              @click="handleAdd"
              >新增</el-button
            >
            <el-button
              size="mini"
              icon="el-icon-delete"
              plain
              type="danger"
              @click="handleDelete"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <AutoResizer :given-height="166">
          <template #default="{ height }">
            <el-table
              ref="multipleTable"
              v-loading="loading"
              :data="list"
              :height="height"
              border
              @selection-change="tableSelected"
            >
              <el-table-column
                type="selection"
                width="55"
                fixed="left"
                align="center"
              />
              <el-table-column
                label="产品编码"
                align="center"
                prop="materialNo"
                min-width="160"
                show-overflow-tooltip
              >
                <template slot-scope="{ row }">
                  <span>{{ row.materialNo }}</span>
                </template>
              </el-table-column>
              <el-table-column
                :key="Math.random()"
                label="产品名称"
                align="center"
                prop="materialName"
                min-width="150"
                show-overflow-tooltip
              >
                <template slot-scope="{ row, $index }">
                  <div class="customeSelect">
                    <el-select
                      v-model="row.materialName"
                      remote
                      filterable
                      :remote-method="handleGetMaterialList"
                      @change="handleChangeMaterialName($event, row, $index)"
                    >
                      <el-option
                        v-for="item in materialPageList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                        <el-row :gutter="6">
                          <el-col
                            :span="12"
                            class="long-text"
                            :title="item.materialNo"
                            >{{ item.code }}</el-col
                          >
                          <el-col :span="12" class="text-right long-text">{{
                            item.name
                          }}</el-col>
                        </el-row>
                      </el-option>
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="生产订单"
                align="center"
                prop="workOrderNo"
                width="150"
              >
                <template slot-scope="scope">
                  <div class="workOrderSearch">
                    <ProductSingleSelect
                      v-model="scope.row.workOrderNo"
                      class="workInput"
                      :material-no="scope.row.materialNo"
                      @change="productedChange"
                    />
                    <el-button
                      v-if="!scope.row.workOrderNo"
                      class="icon"
                      icon="el-icon-zoom-out"
                      @click="handleToWorkOrder"
                    />
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="客户订单号"
                align="center"
                prop="erpOrderNo"
                min-width="150"
              >
                <template slot-scope="scope">
                  <div class="customeSelect">
                    <CustomerSelect
                      v-model="scope.row.erpOrderNo"
                      class="customerInput"
                      :customer-code="queryParams.customerCode"
                      :material-no="scope.row.materialNo"
                      @change="salesChange"
                    />
                    <el-button
                      v-if="!scope.row.erpOrderNo"
                      class="customerIcon"
                      icon="el-icon-zoom-out"
                      @click="handleToCustomer(scope.row)"
                    />
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="出货数量"
                align="center"
                prop="deliveredQty"
                width="140"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.deliveredQty"
                    oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,8})?).*$/g, '$1')"
                    @change="
                      deliverQtyChange(scope.row.deliveredQty, scope.row)
                    "
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="内包数量"
                align="center"
                prop="insideQty"
                width="100"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.insideQty"
                    oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,8})?).*$/g, '$1')"
                    @change="insideQtyChange(scope.row.insideQty, scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="装箱件数"
                align="center"
                prop="pieceQty"
                width="100"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.pieceQty"
                    oninput="value=value.replace(/^\D*(\d*(?:.\d)?).*$/g, '$1')"
                    @change="piceQtyChange(scope.row.pieceQty, scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="尾数"
                align="center"
                prop="mantissaQty"
                width="100"
              />
              <el-table-column
                label="应出货量"
                align="center"
                prop="shouldDeliveredQty"
                width="120"
                show-overflow-tooltip
              />

              <el-table-column
                label="备注"
                align="center"
                prop="note"
                width="140"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.note" />
                </template>
              </el-table-column>
            </el-table>
          </template>
        </AutoResizer>
      </el-tab-pane>
      <el-tab-pane label="待装箱列表" name="list">
        <el-row style="margin-bottom: 12px">
          <el-col :span="6">
            <el-radio v-model="isSearch" size="mini" :label="true" border
              >查询</el-radio
            >
            <el-radio v-model="isSearch" size="mini" :label="false" border
              >扫描打印</el-radio
            >
          </el-col>
        </el-row>
        <!-- 搜索工作栏 -->
        <el-form
          v-show="isSearch"
          ref="searchForm"
          :model="queryParams"
          size="small"
          label-width="68px"
        >
          <QueryFormWrapper>
            <el-col :span="8">
              <el-form-item label="条码号" prop="batchNumber">
                <el-input
                  v-model="queryParams.batchNumber"
                  placeholder="请输入条码号"
                  clearable
                  @keyup.enter.native="handleGetPackingList()"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="存货编码" prop="materialNo">
                <el-input
                  v-model="queryParams.materialNo"
                  placeholder="请输入存货编码"
                  clearable
                  @keyup.enter.native="handleGetPackingList()"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="存货名称" prop="materialName">
                <el-input
                  v-model="queryParams.materialName"
                  placeholder="请输入存货名称"
                  clearable
                  @keyup.enter.native="handleGetPackingList()"
                />
              </el-form-item>
            </el-col>
            <div slot="right">
              <el-form-item label-width="0" class="text-right" style="word">
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  @click="handleGetPackingList()"
                  >搜索</el-button
                >
                <el-button icon="el-icon-refresh" @click="resetQuery"
                  >重置</el-button
                >
              </el-form-item>
            </div>
          </QueryFormWrapper>
        </el-form>
        <!-- 扫码打印 -->
        <el-form v-show="!isSearch" size="small" label-width="68px">
          <QueryFormWrapper>
            <el-col :span="8">
              <el-form-item label="条码号">
                <el-input
                  v-model="qrCode"
                  placeholder="请扫入/输入条码号进行打印"
                  clearable
                  @keyup.enter.native="handleScanBoxQrCode()"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="打印机" prop="printer">
                <el-select
                  v-model="queryParams.printer"
                  clearable
                  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="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>
            <div slot="right">
              <el-form-item label-width="0" class="text-right" style="word">
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  @click="handleScanBoxQrCode()"
                  >批量打印</el-button
                >
                <el-button
                  icon="el-icon-printer"
                  size="small"
                  plain
                  type="primary"
                  @click="handlePreviewLabel('box')"
                  >打印预览</el-button
                >
              </el-form-item>
            </div>
          </QueryFormWrapper>
        </el-form>
        <AutoResizer :given-height="166">
          <template #default="{ height }">
            <el-table
              ref="multipleTable"
              v-loading="loading"
              :data="packingList"
              :height="height"
              border
              @selection-change="boxTableSelected"
            >
              <el-table-column
                type="selection"
                width="55"
                fixed="left"
                align="center"
              />
              <el-table-column
                label="存货编码"
                align="center"
                prop="materialNo"
                min-width="160"
                show-overflow-tooltip
              />
              <el-table-column
                :key="Math.random()"
                label="存货名称"
                align="center"
                prop="materialName"
                min-width="150"
                show-overflow-tooltip
              />
              <el-table-column
                label="销售订单"
                align="center"
                prop="saleOrderNo"
                min-width="150"
                show-overflow-tooltip
              />
              <el-table-column
                label="工票号"
                align="center"
                prop="erpWorkOrderNo"
                min-width="150"
                show-overflow-tooltip
              />
              <el-table-column
                label="条码号"
                align="center"
                prop="batchNumber"
                min-width="150"
                show-overflow-tooltip
              />
              <el-table-column
                label="数量"
                align="center"
                prop="qty"
                min-width="140"
              />
              <el-table-column
                label="订单数量"
                align="center"
                prop="orderQty"
                min-width="140"
              />
            </el-table>
          </template>
        </AutoResizer>
      </el-tab-pane>
      <el-tab-pane label="条码装箱" name="box">
        <el-form
          ref="queryForm2"
          :model="boxForm"
          size="small"
          :rules="rules2"
          label-width="88px"
        >
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="设定装箱数" prop="pieceQty">
                <el-input-number
                  v-model="boxForm.pieceQty"
                  disabled
                  :min="0"
                  style="min-width: 200px; width: 320px; max-width: 400px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="成品SN" prop="qrCode">
                <el-input
                  v-model="boxForm.qrCode"
                  placeholder="请扫入/输入成品SN"
                  clearable
                  :disabled="!boxForm.masterId"
                  @keyup.enter.native="handleScanQrCode"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="已扫数量" prop="casesNumber">
                <el-input v-model="boxForm.casesNumber" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button
                icon="el-icon-printer"
                size="small"
                plain
                type="primary"
                @click="handlePreviewLabel"
                >打印预览</el-button
              >
            </el-col>
            <el-col :span="4">
              <el-button
                icon="el-icon-s-release"
                size="small"
                type="primary"
                @click="handleHicorePrint"
                >完成装箱/打印外箱标签</el-button
              >
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="箱型" prop="modelEnable">
                <DictSelect
                  v-model="boxForm.modelEnable"
                  placeholder="请选择状态"
                  dict-type="BOX_TYPE"
                />
              </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="6">
              <el-form-item label="打印机" prop="printer">
                <el-select
                  v-model="queryParams.printer"
                  clearable
                  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="6">
              <el-form-item label-width="20px">
                <el-button
                  icon="el-icon-plus"
                  size="small"
                  type="primary"
                  @click="handleAddBox"
                  >增箱</el-button
                >
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-row>
          <el-col :span="8">
            <AutoResizer :given-height="166">
              <template #default="{ height }">
                <el-table
                  v-loading="loading"
                  :data="salePackageMasterList"
                  :height="height"
                  border
                  :row-class-name="tableAddClass"
                  @row-click="handleRowClick"
                >
                  <el-table-column
                    label="箱号"
                    align="center"
                    prop="boxNo"
                    min-width="50"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="包数"
                    align="center"
                    prop="casesNumber"
                    min-width="50"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="销售单号"
                    align="center"
                    prop="saleOrderNo"
                    min-width="150"
                    show-overflow-tooltip
                  >
                    <template slot-scope="scope">
                      <div class="customeSelect">
                        <CustomerSaleOrderNoSelect
                          v-model="scope.row.saleOrderNo"
                          class="customerInput"
                          :customer-code="queryParams.customerCode"
                          :material-no="scope.row.materialNo"
                          @change="handleSaleOrderNoChange($event, scope.row)"
                        />
                        <!-- v-if="!scope.row.saleOrderNo" -->
                        <el-button
                          class="customerIcon"
                          icon="el-icon-zoom-out"
                          @click="handleToCustomer(scope.row)"
                        />
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </AutoResizer>
          </el-col>
          <el-col :span="16">
            <AutoResizer :given-height="166">
              <template #default="{ height }">
                <el-table
                  v-loading="loading"
                  :data="salePackageDetailsList"
                  :height="height"
                  border
                >
                  <el-table-column
                    label="条码"
                    align="center"
                    prop="qrCode"
                    min-width="160"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="存货名称"
                    align="center"
                    prop="materialName"
                    min-width="150"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="工票号"
                    align="center"
                    prop="erpWorkOrderNo"
                    min-width="150"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="数量"
                    align="center"
                    prop="qty"
                    min-width="150"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="胶批号"
                    align="center"
                    prop="originBatchNumber"
                    min-width="150"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="操作"
                    align="center"
                    width="80"
                    show-overflow-tooltip
                    fixed="right"
                  >
                    <template slot-scope="scope">
                      <el-button
                        v-hasPermi="['']"
                        type="text"
                        class="text-danger"
                        icon="el-icon-delete"
                        size="mini"
                        @click="handleDeleteSalePackageDetails(scope.row)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </AutoResizer>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>

    <!-- 选择生产订单 -->
    <ProductOrderSelect
      ref="productOrderSelect"
      :row-details="infoRowDetail"
      @send-data="handleProductSelected"
    />
    <!-- 选择客户订单 -->
    <SaleSelect
      ref="saleSelect"
      :row-details="infoRowDetail"
      :state="state"
      @send-data="handleSaleSelected"
    />
    <!-- 出货单打印 -->
    <IssuePrinit ref="issuePrint" />
    <HicoreLabelPreview ref="hicoreLabelPreview" :list="previewUrlList" />
    <!-- 标签选择 -->
    <ReportPrintSelect ref="reportPrintSelect" />
  </div>
</template>

<script>
import {
  createSalePackageMaster,
  createSalePackageDetails,
  updateSalePackageMaster,
  getSaleOutOrderDetail,
  createNewSaleOut,
  getPackingList,
  getMaterialPageList,
  getSalePackageMasterPage,
  getSalePackageDetailsPage,
  getSaleBoxLabelPrintData,
  getBeforeSalePackageLabelPrintData,
  deleteSalePackageDetail,
} from "@/api/wms/output/shipmentDetail";
import ProductOrderSelect from "./components/ProductOrderSelect.vue";
import SaleSelect from "./components/SaleSelect.vue";
import CustomerSelect from "./components/CustomerSelect.vue";
import CustomerSaleOrderNoSelect from "./components/CustomerSaleOrderNoSelect.vue";
import ProductSingleSelect from "./components/ProductSingleSelect.vue";
import CustomerCodeSelect from "./components/CustomerCodeSelect.vue";
import IssuePrinit from "./salesIssueDetails/IssuePrinit.vue";
import HicoreLabelPreview from "@/components/HicoreLabelPreview/index.vue";
import { GetPrinters, Print } from "@/utils/hicorePrinterFunction";
import { getAppendixTableData } from "@/api/system/appendix.js";
import ReportPrintSelect from "./components/ReportPrintSelect.vue";
const AccessTokenKey = "ACCESS_TOKEN";

export default {
  name: "ShipmentDetail",
  components: {
    ProductOrderSelect,
    SaleSelect,
    CustomerSelect,
    ProductSingleSelect,
    CustomerCodeSelect,
    CustomerSaleOrderNoSelect,
    IssuePrinit,
    HicoreLabelPreview,
    ReportPrintSelect,
  },
  data() {
    return {
      // 是否查询
      isSearch: false,
      // 待装箱列表条码号
      qrCode: "",
      // 打印数据
      printers: [],
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 提交遮罩层
      submitLoading: false,
      // 总条数
      total: 0,
      // 产品信息-当前行信息
      infoRowDetail: {
        materialNo: "",
      },
      // 0出货信息table使用，1条码装箱table使用
      state: 0,
      // 列表
      list: [],
      // 待装箱列表
      packingList: [],
      // 已装箱列表
      salePackageMasterList: [],
      // 已装箱明细列表
      salePackageDetailsList: [],
      // 物料列表
      materialPageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      tabSelected: "info",
      // 条码装箱表单字段
      boxForm: {
        pieceQty: 0,
        casesNumber: 0,
        qrCode: "",
        masterId: "",
      },
      btTemplateList: [],
      // 当前行数据
      currentRow: {},
      // 选中的数据
      currentRows: [],
      // 步骤条高亮  (1:出货单下达 2：出货打码 3：装箱确认 4：出货签收)
      orderStatus: 1,
      // 报表参数
      reportId: "",
      tokens: "",
      baseUrl: "",
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        saleOutNo: null,
        materialNo: null,
        materialName: null,
        batchNumber: null,
        deliveryTime: null,
        customerCode: null,
        customerName: null,
        shipToAddress: null, // 收货方地址
        consignee: null, // 收货人姓名
        phoneNumber: null, // 联系电话
        // 打印机
        printer: "",
        HicoreReportName: "",
        // 签收状态
        signStatus: "0",
        deliveryAddress: null,
      },
      preview: false,
      previewUrlList: [],
      // 数组id
      nextId: 0,
      // 选中的生产订单
      productsObject: {},
      // 选中的客户订单
      salesObject: {},
      // 表单校验
      rules: {
        customerCode: [
          { required: true, message: "客户编码不能为空", trigger: "change" },
        ],
        customerName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" },
        ],
        deliveryAddress: [
          { required: true, message: "送货地址不能为空", trigger: "blur" },
        ],
        deliveryTime: [
          { required: true, message: "送货时间不能为空", trigger: "blur" },
        ],
        shipToAddress: [
          { required: true, message: "收货方地址不能为空", trigger: "blur" },
        ],
        consignee: [
          { required: true, message: "收货人姓名不能为空", trigger: "blur" },
        ],
        phoneNumber: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
        ],
      },
      rules2: {
        qrCode: [
          { required: true, message: "SN码不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.tokens = localStorage.getItem(AccessTokenKey);
    this.baseUrl = process.env.VUE_APP_REPORT_API;
    this.reportId = this.$route.meta.reportId;
    this.getList();
    this.handleGetMaterialList();
    GetPrinters()
      .then(({ printer, printers }) => {
        // 设置上次使用的打印机
        this.queryParams.printer = printer;
        this.printers = printers;
      })
      .catch((e) => {
        this.$message.error(e);
      });
    this.getTemplateList();
  },
  methods: {
    reportChange(e) {
      const fdIndex = this.btTemplateList.findIndex((ret) => ret.id === e);
      this.queryParams.HicoreReportName = this.btTemplateList[fdIndex].sysName;
    },
    // 获取BT打印模板
    getTemplateList() {
      getAppendixTableData({
        pageNum: 1,
        pageSize: 999,
        printFlag: "1",
        filesMenuId: "1000000000000000001",
      }).then(({ data }) => {
        this.btTemplateList = data?.list ?? [];
      });
    },
    // 打印预览
    handlePreviewLabel(state) {
      this.preview = true;
      this.previewUrlList = [];
      this.$refs.hicoreLabelPreview.visable = true;
      if (state === "box") {
        this.handleScanBoxQrCode();
      } else {
        this.handleHicorePrint();
      }
    },
    // 高亮行
    tableAddClass({ row, rowIndex }) {
      //  rowIndex 表示哪一行
      if (row.id === this.boxForm.masterId) {
        return "tr-highlight";
      }
      return "";
    },
    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 handleHicorePrint() {
      if (
        !this.queryParams.printer ||
        Object.prototype.toString.call(this.queryParams.printer) !==
          "[object String]"
      ) {
        this.$message.warning("请选择打印机");
        return;
      }
      const { data } = await getSaleBoxLabelPrintData({
        id: this.boxForm.masterId,
      });
      const reportDataList = data.data ?? [];
      const totalSize = reportDataList.length;
      // loading
      this.reLoading(reportDataList.length);
      if (totalSize === 0) return;

      const printParams = {
        printer: this.queryParams.printer,
        Preview: this.preview ? "3" : "0",
        TemplateURL: "http://113.105.183.190:9167/bucket159",
        TemplateName: this.queryParams.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("标签打印成功");
    },
    // 待装箱列表扫码打印
    async handleScanBoxQrCode() {
      if (
        !this.queryParams.printer ||
        Object.prototype.toString.call(this.queryParams.printer) !==
          "[object String]"
      ) {
        this.$message.warning("请选择打印机");
        return;
      }
      const { data } = await getBeforeSalePackageLabelPrintData({
        qrCode: this.qrCode,
      });
      const reportDataList = data.data ?? [];
      const totalSize = reportDataList.length;
      if (totalSize === 0 || !reportDataList[0]) {
        this.$message.warning("未查询到数据，请扫描正确条码！");
        return;
      }
      // loading
      this.reLoading(reportDataList.length);

      for (let x = 0; x < reportDataList.length; x++) {
        for (let y = 0; y < 3; y++) {
          const printParams = {
            printer: this.queryParams.printer,
            Preview: this.preview ? "3" : "0",
            TemplateURL: "http://113.105.183.190:9167/bucket159",
            TemplateName: this.queryParams.HicoreReportName,
            PrintData: [reportDataList[x]],
          };
          switch (y) {
            case 0:
              printParams.TemplateName =
                "2024-04-10-16-10-49-1712736650022_Label3.Lblx";
              break;
            case 1:
              printParams.TemplateName =
                "2024-04-10-16-10-49-1712736650022_Label3.Lblx";
              break;
            case 2:
              printParams.TemplateName =
                "2024-04-10-16-10-49-1712736650022_Label3.Lblx";
              break;
          }
          const _this = this;
          if (printParams.Preview === "3") {
            Print(printParams)
              .then((data) => {
                _this.previewUrlList.push(data[1]);
              })
              .catch((e) => {
                _this.$message.error(e);
              });
          } else {
            Print(printParams)
              .then((data) => {})
              .catch((e) => {
                this.$message.error(e);
              });
          }
        }
      }
      this.preview = false;
      this.$message.success("标签打印成功");
    },
    // 扫描SN码
    handleScanQrCode() {
      const { masterId, qrCode } = this.boxForm;
      createSalePackageDetails({ masterId, qrCode }).then(
        ({ code, data, msg }) => {
          if (code === 0) {
            this.boxForm.casesNumber += 1;
            this.$message.success("扫描成功");
            this.handleGetBoxList(this.queryParams.id);
            this.handleRowClick({
              id: this.boxForm.masterId,
              casesNumber: this.boxForm.casesNumber,
            });
          }
        }
      );
    },
    // 物料名称下拉框选中事件
    handleChangeMaterialName(e, row, index) {
      const filterData = this.materialPageList.filter((item) => item.id === e);
      this.list[index].materialNo = filterData[0]?.code;
      this.list[index].materialName = filterData[0]?.name;
      Object.assign(this.infoRowDetail, this.list[index]);
    },
    // 获取物料列表数据
    handleGetMaterialList(keyWorld) {
      getMaterialPageList({ pageNo: 1, pageSize: 500, keyWorld }).then(
        ({ code, data, msg }) => {
          this.materialPageList = data?.list ?? [];
        }
      );
    },
    // 已装箱列表行点击事件
    handleRowClick(row) {
      this.boxForm.masterId = row.id;
      this.boxForm.casesNumber = row.casesNumber;
      getSalePackageDetailsPage({ masterId: row.id }).then(
        ({ code, data, msg }) => {
          if (code === 0) {
            this.salePackageDetailsList = data?.list ?? [];
          }
        }
      );
    },
    // 待装箱列表搜索
    handleGetPackingList(params) {
      const { pageNo, pageSize, batchNumber, materialNo, materialName } =
        this.queryParams;
      const queryParams = params || {
        pageNo,
        pageSize,
        batchNumber,
        materialNo,
        materialName,
      };
      getPackingList({ ...queryParams }).then(({ code, data, msg }) => {
        if (code === 0) {
          this.packingList = data;
        }
      });
    },
    // 跳转待装箱列表
    handleViewDetailList(row) {
      const { id } = this.queryParams;
      this.currentRow = row;
      this.salePackageDetailsList = [];
      this.$refs.tabs.currentName = "list";
      this.handleGetPackingList({ materialNo: row?.materialNo });

      const queryParams = { wmsSaleOutOrderId: row?.id };
      if (id) queryParams.wmsSaleOutMasterId = id;
      getSalePackageMasterPage({ ...queryParams }).then(
        ({ code, data, msg }) => {
          if (code === 0) {
            this.salePackageMasterList = data?.list ?? [];
          }
        }
      );
    },
    // 获取条码装箱左table数据
    handleGetBoxList(id) {
      const queryParams = {};
      if (id) queryParams.wmsSaleOutMasterId = id;
      if (this.currentRow?.id) {
        queryParams.wmsSaleOutOrderId = this.currentRow?.id;
      }
      getSalePackageMasterPage({ ...queryParams }).then(
        ({ code, data, msg }) => {
          if (code === 0) {
            this.salePackageMasterList = data?.list ?? [];
          }
        }
      );
    },
    // 不带条件获取箱号数据
    handleGetSalePackageMasterPage() {
      getSalePackageMasterPage().then(({ code, data, msg }) => {
        if (code === 0) {
          this.salePackageMasterList = data?.list ?? [];
        }
      });
    },
    // 增箱
    handleAddBox() {
      const { id } = this.queryParams;
      createSalePackageMaster({
        wmsSaleOutMasterId: id ?? "",
        wmsSaleOutOrderId: this.currentRow?.id ?? "",
      }).then(({ code, data, msg }) => {
        if (code === 0) {
          this.boxForm.masterId = data;
          this.handleGetBoxList(this.queryParams.id);
        }
      });
    },
    // tab切换事件
    handleTabClick({ name }) {
      this.boxForm.qrCode = "";
      this.boxForm.masterId = "";
      this.boxForm.casesNumber = 0;
      this.boxForm.pieceQty = this.currentRows[0]?.pieceQty;
      name === "box" ? (this.state = 1) : (this.state = 0);

      // 选中出货信息tab
      if (name !== "info") {
        // 选中待装箱/条码装箱tab
        if (this.currentRows.length === 1 || this.currentRows.length > 1) {
          this.handleViewDetailList(this.currentRows[0]);
        } else {
          this.handleViewDetailList();
        }
      } else {
        this.getList();
      }
    },
    /** 查询列表 */
    async getList() {
      this.loading = true;
      // 执行查询

      if (this.$route.query.saleOutNo) {
        try {
          const response = await getSaleOutOrderDetail({
            saleOutNo: this.$route.query.saleOutNo,
          });
          const deliveryTimeTransformed = (dateStr) =>
            new Date(dateStr).toISOString().slice(0, 19).replace("T", " ");

          this.queryParams = { ...this.queryParams, ...response.data };
          this.orderStatus = response.data.orderStatus;
          // this.queryParams.deliveryTime = deliveryTimeTransformed(
          //   response.data.deliveryTime
          // );
          this.list = response.data?.detail || [];
          // if (this.list.length === 0) {
          //   this.list.push({
          //     materialNo: '',
          //     materialName: '',
          //     deliveredQty: '',
          //     mantissaQty: '',
          //     shouldDeliveredQty: 6000,
          //     id: this.nextId
          //   })
          // }
        } catch (error) {
          console.log(error);
        } finally {
          this.loading = false;
        }
      } else {
        this.loading = false;
        // this.list.push({
        //   workOrderNo: '',
        //   materialNo: '',
        //   materialName: '',
        //   deliveredQty: '',
        //   mantissaQty: '',
        //   erpOrderNo: '',
        //   shouldDeliveredQty: '',
        //   id: this.nextId
        // })
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      // this.getList()
      this.handleGetPackingList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("searchForm");
      this.handleQuery();
    },
    /** 查看明细 */
    handleView(row) {
      const { id } = row;
      this.$refs.purchaseDetail.queryParams.inStockId = id;
      this.$refs.purchaseDetail.open = true;
    },
    // 表格选中
    tableSelected(val) {
      this.currentRows = val;
    },
    // 待装箱列表表格选中
    boxTableSelected(val) {
      const qrCodeList = val.map((ret) => ret.batchNumber)?.toString(",");
      this.qrCode = qrCodeList;
    },
    // 删除出货通知单
    handleDelete() {
      if (this.currentRows.length === 0) {
        this.$modal.msgWarning("请选择您要删除的单据!");
        return;
      }
      const productNos = this.currentRows
        .map((item) => {
          const { materialNo } = item;
          return materialNo;
        })
        .join(",");
      const message = `您正在删除产品编码为${productNos},请确认是否继续？`;
      const deleteId = this.currentRows.map((item) => item.id);
      this.$modal
        .confirm(message)
        .then(() => {
          this.list = this.list.filter((item) => !deleteId.includes(item.id));
        })
        .catch(() => {});
    },
    // 删除条码装箱明细
    handleDeleteSalePackageDetails(row) {
      const { materialName } = row;
      const message = `您正在删除存货名称为${materialName},请确认是否继续？`;
      this.$modal
        .confirm(message)
        .then(() => {
          deleteSalePackageDetail(row?.id).then(({ code, data, msg }) => {
            // 重新获取列表数据
            this.handleGetBoxList(this.queryParams.id);
            this.handleRowClick({
              id: this.boxForm.masterId,
              casesNumber: this.boxForm.casesNumber,
            });
          });
        })
        .catch(() => {});
    },
    // 新增
    handleAdd() {
      this.list.push({
        workOrderNo: "",
        materialNo: "",
        materialName: "",
        deliveredQty: "",
        mantissaQty: "",
        erpOrderNo: "",
        shouldDeliveredQty: 6000,
        // id: ++this.nextId
      });
    },
    // 校验出货数量不能超过应出货量
    deliverQtyChange(v, row) {
      const { shouldDeliveredQty, insideQty, pieceQty } = row;
      if (v > shouldDeliveredQty) {
        this.$modal.msgWarning("出货数量不能超过应出货量!");
        row.deliveredQty = "";
      }
      // 结算尾数 尾数=出货数量-内包数量*装箱件数
      if (!v || !pieceQty || !insideQty) {
        return;
      }
      row.mantissaQty = this.getHandleNumber(v - pieceQty * insideQty);
      if (row.mantissaQty < 0) {
        this.$modal.msgWarning("尾数不能小于0!");
        row.mantissaQty = "";
      }
    },
    // 选择生产订单
    handleToWorkOrder() {
      this.$refs.productOrderSelect.open = true;
    },
    // 选择生产订单完成回调
    handleProductSelected(row) {
      this.productsObject = row || {};
      const { materialNo, detailErpId, erpOrderNo } = row;
      const insertItem = this.list.find((item) => item.workOrderNo === "");
      insertItem.workOrderNo = erpOrderNo;
      insertItem.workDetailErpId = detailErpId;
      if (
        Object.keys(this.salesObject).length > 0 &&
        this.salesObject.materialNo !== materialNo
      ) {
        this.$modal.msgWarning(
          "生产订单和客户订单的物料编码不同，请重新选择生产订单!"
        );
        insertItem.workOrderNo = "";
      }
    },
    // 生产订单选择完成之后的回调
    productedChange(v) {
      this.productsObject = v || {};
      const { erpOrderNo, detailErpId, materialNo, materialName } = v;
      const selecedProduct = this.list.filter(
        (item) => item.workOrderNo === erpOrderNo
      );
      selecedProduct.map((prodcut) => {
        prodcut.materialNo = materialNo;
        prodcut.materialName = materialName;
        prodcut.workDetailErpId = detailErpId;
        if (
          Object.keys(this.salesObject).length > 0 &&
          this.salesObject.materialNo !== materialNo
        ) {
          this.$modal.msgWarning(
            "生产订单和客户订单的物料编码不同，请重新选择生产订单!"
          );
          prodcut.workOrderNo = "";
        }
      });
    },
    // 选择客户订单
    handleToCustomer(row) {
      if (row?.id) Object.assign(this.infoRowDetail, row);
      this.$refs.saleSelect.queryParams.customerCode =
        this.queryParams.customerCode;
      this.$refs.saleSelect.open = true;
    },
    // 选择产品名称
    handleToCustomerMaterialSelect() {
      // this.$refs.materialSelect.queryParams.customerCode = this.queryParams.customerCode
      this.$refs.materialSelect.open = true;
    },
    // 选择客户订单完回调
    handleSaleSelected(row) {
      // 出货信息客户订单号选择
      if (row.state === 0) {
        this.salesObject = row || {};
        const {
          shouldDeliveredQty,
          id,
          erpOrderNo,
          materialNo,
          materialName,
          customerCode,
          customerName,
          deliveryAddress,
          deliveryTime,
        } = row;
        const insertSaleItem = this.list.find((item) => item.erpOrderNo === "");
        // 新增时为出货单详情赋值
        if (!this.queryParams.customerCode && !this.queryParams.customerName) {
          this.queryParams.customerCode = customerCode;
          this.queryParams.customerName = customerName;
          this.queryParams.deliveryAddress = deliveryAddress;
          this.queryParams.deliveryTime = new Date(
            deliveryTime
          ).toLocaleString();
        }
        if (
          Object.keys(this.productsObject).length > 0 &&
          this.productsObject.materialNo !== materialNo
        ) {
          this.$modal.msgWarning(
            "生产订单和客户订单的物料编码不同，请重新选择生产订单!"
          );
          insertSaleItem.workOrderNo = "";
        }
        insertSaleItem.materialName = materialName;
        insertSaleItem.materialNo = materialNo;
        insertSaleItem.erpOrderNo = erpOrderNo;
        insertSaleItem.shouldDeliveredQty = shouldDeliveredQty;
        insertSaleItem.saleOrderDetailId = id;
      } else {
        // 条码装箱销售订单号选择
        this.salesObject = row || {};
        const { erpOrderNo } = row;
        const insertSaleItem = this.salePackageMasterList.find(
          (item) => item.id === this.infoRowDetail.id
        );
        insertSaleItem.saleOrderNo = erpOrderNo;
        if (this.infoRowDetail?.id) {
          updateSalePackageMaster({
            id: this.infoRowDetail?.id,
            saleOrderDetailId: row.id,
          }).then(({ code, data, msg }) => {
            this.handleGetBoxList(this.queryParams.id);
          });
        }
      }
    },
    // 条码装箱销售订单列选择change事件
    handleSaleOrderNoChange(v, row) {
      this.salesObject = v || {};
      const { erpOrderNo } = v;
      const insertSaleItem = this.salePackageMasterList.filter(
        (item) => item.id === row.id
      );
      insertSaleItem.saleOrderNo = erpOrderNo;
      if (row?.id) {
        updateSalePackageMaster({ id: row?.id, saleOrderDetailId: v.id }).then(
          ({ code, data, msg }) => {
            if (code === 0) {
              this.handleGetBoxList(this.queryParams.id);
            }
          }
        );
      }
    },
    // 客户订单选择change事件
    salesChange(v) {
      this.salesObject = v || {};
      const {
        erpOrderNo,
        shouldDeliveredQty,
        id,
        materialNo,
        materialName,
        customerCode,
        customerName,
        deliveryAddress,
        deliveryTime,
      } = v;
      const selectItem = this.list.filter(
        (item) => item.erpOrderNo === erpOrderNo
      );
      // 新增时为出货单详情赋值
      if (!this.queryParams.customerCode && !this.queryParams.customerName) {
        this.queryParams.customerCode = customerCode;
        this.queryParams.customerName = customerName;
        this.queryParams.deliveryAddress = deliveryAddress;
        this.queryParams.deliveryTime = new Date(deliveryTime).toLocaleString();
      }
      selectItem.map((select) => {
        select.materialNo = materialNo;
        select.materialName = materialName;
        select.shouldDeliveredQty = shouldDeliveredQty;
        select.saleOrderDetailId = id;
        if (
          Object.keys(this.productsObject).length > 0 &&
          this.productsObject.materialNo !== materialNo
        ) {
          this.$modal.msgWarning(
            "生产订单和客户订单的物料编码不同，请重新选择生产订单!"
          );
          select.workOrderNo = null;
        }
      });
    },
    // 表头选择客户订单change
    handleCustomerCodeChange(v) {
      const { name, addres } = v;
      this.queryParams.customerName = name || "";
      this.queryParams.deliveryAddress = addres || "";
    },
    // 小数点问题处理
    getHandleNumber(val) {
      return Math.round(parseFloat(val) * 100000000) / 100000000;
    },
    // 计算尾数 尾数=出货数量-内包数量*装箱件数
    piceQtyChange(v, row) {
      const { deliveredQty, insideQty } = row;
      if (!v || !deliveredQty || !insideQty) {
        return;
      }
      row.mantissaQty = this.getHandleNumber(deliveredQty - v * insideQty);
      if (row.mantissaQty < 0) {
        this.$modal.msgWarning("尾数不能小于0!");
        row.mantissaQty = "";
      }
    },
    // 计算尾数 尾数=出货数量-内包数量*装箱件数
    insideQtyChange(v, row) {
      const { deliveredQty, pieceQty } = row;
      if (!v || !deliveredQty || !pieceQty) {
        return;
      }
      row.mantissaQty = this.getHandleNumber(deliveredQty - v * pieceQty);
      if (row.mantissaQty < 0) {
        this.$modal.msgWarning("尾数不能小于0!");
        row.mantissaQty = "";
      }
    },
    // 创建出货单
    handleSubmit() {
      // queryForm
      this.$refs["queryForm"].validate((valid) => {
        if (!valid) {
          return;
        }
        const list = this.list.map((item) => {
          const { deliveredQty: nowDeliveredQty, ...rest } = item;
          return {
            ...rest,
            nowDeliveredQty,
          };
        });
        const {
          customerCode,
          customerName,
          deliveryTime,
          deliveryAddress,
          shipToAddress,
          consignee,
          phoneNumber,
        } = this.queryParams;
        const params = {
          customerCode,
          customerName,
          deliveryTime: new Date(deliveryTime)
            .toISOString()
            .slice(0, 19)
            .replace("T", " "),
          deliveryAddress,
          shipToAddress,
          consignee,
          phoneNumber,
          saleOutNo: this.$route.query.saleOutNo || null,
          list,
        };
        this.loading = true;
        createNewSaleOut(params)
          .then((res) => {
            this.$modal.msgSuccess("操作成功！");
            if (!this.$route.query.saleOutNo) {
              // 关闭当前窗口
              this.$tab.closeOpenPage();
              this.$router.push({
                path: "/entry-exit/sales-in-out/shipment-notification",
              });
            }
            this.getList();
          })
          .finally(() => {
            this.loading = false;
          });
      });
    },
    // 标签打印
    handleToSelectPrint() {
      this.$refs.reportPrintSelect.title = "标签选择";
      this.$refs.reportPrintSelect.form.headId = this.$route.query.id;
      this.$refs.reportPrintSelect.open = true;
    },
    // 出货单打印
    handleToSelectPrint1() {
      const src = `${this.baseUrl}/jmreport/view/${this.reportId}?token=${this.tokens}&saleOutNo=${this.queryParams.saleOutNo}`;
      this.$refs.issuePrint.dialogVisible = true;
      this.$refs.issuePrint.title = "出货通知单";
      this.$refs.issuePrint.src = src;
    },
    // 审批
    handleApproval() {
      this.$modal.msgWarning("该功能暂未开放！");
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-step__title {
  font-size: 14px !important;
}
.workOrderSearch {
  width: 100%;
  .workInput {
    position: relative;
  }
  .icon {
    position: absolute;
    top: 8px;
    right: 12px;
    width: 40px;
    height: 30px;
    border: none;
    padding: 10px;
  }
}

.customeSelect {
  width: 100%;
  .customerInput {
    width: 100%;
    position: relative;
  }
  .customerIcon {
    position: absolute;
    top: 8px;
    right: 12px;
    width: 40px;
    height: 30px;
    border: none;
    padding: 10px;
  }
}

::v-deep .el-table .tr-highlight {
  color: white !important;
  background-color: rgba(44, 154, 255, 1) !important;
}
// 鼠标滑过背景颜色
::v-deep .el-table tbody tr:hover > td {
  color: white !important;
  background-color: rgba(24, 144, 255, 0.8) !important;
}
</style>
