<template>
  <div class="app-container" ref="appPanel">
    <div ref="toolPanel" class="toolPanel">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <div class="toolTitle">{{ funTitle }}</div>
        </el-col>
        <el-col :span="1.5" v-if="this.goodsReturn">
          <el-button
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleExistTCkOrder"
            v-hasPermi="['system:trkNotice:add']"
          >选择出库单
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:trkNotice:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:trkNotice:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:trkNotice:remove']"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:trkNotice:export']"
          >导出
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-show="button"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleImport"
            v-hasPermi="['system:trkNotice:export']"
          >导入
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-show="showButton"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExcelImport"
            v-hasPermi="['system:trkNotice:export']"
          >一级库导入
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索
          </el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置
          </el-button
          >
        </el-col>
         <el-col :span="1.5">
          <el-button
            icon="el-icon-info"
            size="mini"
            :disabled="single"
            @click="sendNotice">发送通知单消息
          </el-button>
        </el-col>
<!--        <el-col :span="1.5">
          <el-button
            icon="el-icon-info"
            size="mini"
            :disabled="single"
            @click="sendIwms">发送iwms入库
          </el-button>
        </el-col>-->

        <right-toolbar
          ref="toolBarRef"
          @customCols="customColsHandler"
          :showSearch.sync="showSearch"
          showColumnsType="transfer"
          :columns="columns"
        ></right-toolbar>
      </el-row>
    </div>
    <div class="search-container" ref="searchPanel">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="mini"
        :inline="true"
        v-show="showSearch"
        label-width="75px"
      >
        <el-form-item label="入库通知单号" prop="noticeId">
          <el-input
            v-model="queryParams.noticeId"
            placeholder="请输入入库通知单号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="来源单号" prop="deliveryId">
          <el-input
            v-model="queryParams.deliveryId"
            placeholder="请输入来源单号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
<!--        <el-form-item label="供应商编号" prop="providerId">-->
<!--          <el-input-->
<!--            v-model="queryParams.providerId"-->
<!--            placeholder="请输入供应商编号"-->
<!--            clearable-->
<!--            @keyup.enter.native="handleQuery"-->
<!--          />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="供应商名称" prop="providerName">-->
<!--          <el-input-->
<!--            v-model="queryParams.providerName"-->
<!--            placeholder="请输入供应商名称"-->
<!--            clearable-->
<!--            @keyup.enter.native="handleQuery"-->
<!--          />-->
<!--        </el-form-item>-->
        <el-form-item label="发货单号" prop="purchaseId">
          <el-input
            v-model="queryParams.purchaseId"
            placeholder="请输入发货单号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
<!--        <el-form-item label="发货组织" prop="shippingDept">-->
<!--          <el-input-->
<!--            v-model="queryParams.shippingDept"-->
<!--            placeholder="请输入发货组织"-->
<!--            clearable-->
<!--            @keyup.enter.native="handleQuery"-->
<!--          />-->
<!--        </el-form-item>-->
        <el-form-item label="请购人" prop="purchaser">
          <el-input
            v-model="queryParams.purchaser"
            placeholder="请输入请购人"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
<!--        <el-form-item label="联系方式" prop="telephone">-->
<!--          <el-input-->
<!--            v-model="queryParams.telephone"-->
<!--            placeholder="请输入联系方式"-->
<!--            clearable-->
<!--            @keyup.enter.native="handleQuery"-->
<!--          />-->
<!--        </el-form-item>-->
        <el-form-item label="收货状态" prop="receivingStatus">
          <el-select v-model="queryParams.receivingStatus" placeholder="请选择收货状态" clearable>
            <el-option
              v-for="dict in dict.type.receive_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发货日期" prop="sendeDate">
          <el-date-picker
            clearable
            v-model="queryParams.sendeDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择发货日期"
          >
          </el-date-picker>
        </el-form-item>
<!--        <el-form-item label="采购组织" prop="purchaseDept">-->
<!--          <el-input-->
<!--            v-model="queryParams.purchaseDept"-->
<!--            placeholder="请输入采购组织"-->
<!--            clearable-->
<!--            @keyup.enter.native="handleQuery"-->
<!--          />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="收货人" prop="receiver">-->
<!--          <el-input-->
<!--            v-model="queryParams.receiver"-->
<!--            placeholder="请输入收货人"-->
<!--            clearable-->
<!--            @keyup.enter.native="handleQuery"-->
<!--          />-->
<!--        </el-form-item>-->
      </el-form>
    </div>

    <div class="table-container">
      <div ref="mainTablePanel" :style="{ height: 500 }">
        <el-table
          :key="rndKey"
          ref="providerTableRef"
          v-loading="loading"
          border
          size="mini"
          :height="mainTableHeight"
          :data="trkNoticeList"
          @selection-change="handleSelectionChange"
          @header-dragend="handleHeaderDragEnd"
        >
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column
            v-for="item in columns"
            :key="item.key"
            :label="item.label"
            align="center"
            :prop="item.columnName"
            v-if="item.visible"
            :width="item.width"
          >
            <template v-slot="scope">
              <el-input
                v-if="item.columnName === 'applicant'"
                v-model="scope.row[item.columnName]"
                size="small"
              />
              <dict-tag
                v-else-if="item.columnName === 'receivingStatus'"
                v-slot="scope"
                :options="dict.type.receive_status"
                :value="scope.row[item.columnName]"
              />
              <dict-tag
                v-else-if="item.columnName === 'status'"
                :options="dict.type.common_status"
                :value="scope.row[item.columnName]"
              />
              <span v-else>{{ scope.row[item.columnName] }}</span>
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            width="100"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-detail"
                @click="handleMainTableClick(scope.row)"
              >查看明细
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagePanel">
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </div>

      <div ref="subTablePanel" :style="{ height: subTableDivHeight }">
        <el-row class="mb5">
          <label class="subTableTitle"
          ><i class="el-icon-notebook-1"/>{{ funTitle }}通知单明细信息
            <span style="margin-left: 10px; font-size: 13px"
            >(通知单号：{{ noticeId }})</span
            ></label
          >
        </el-row>
        <div ref="toolPanel" class="toolPanel">
          <el-row :gutter="5">
          <el-col :span="1.5">
            <el-button
              icon="el-icon-plus"
              size="mini"
              @click="handleAddTRkWareNoticeTab"
            >添加
            </el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button icon="el-icon-check" size="mini" @click="confirmSave"
            >保存
            </el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button icon="el-icon-search" size="mini" @click="handleSubQuery"
            >搜索
            </el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button icon="el-icon-refresh" size="mini" @click="resetSubQuery"
            >重置
            </el-button
            >
          </el-col>
          <!--          <el-col :span="1.5">
                      <el-button icon="el-icon-edit" size="mini" @click="confirmReceive"
                      >收货
                      </el-button
                      >
                    </el-col>-->
          <!--          <el-col :span="1.5">
                      <el-button
                        icon="el-icon-download"
                        size="mini"
                        @click="handleManualCompletion"
                        >手动完成</el-button
                      >
                    </el-col>-->
          <el-col :span="1.5">
            <el-button
              icon="el-icon-delete"
              size="mini"
              @click="handleDeleteTRkWareNoticeTab"
            >删除
            </el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-select
              v-model="storageId"
              filterable
              placeholder="选择仓库"
              @change="handleSelectMainStorage"
            >
              <el-option
                v-for="storage in storageTotalList"
                :key="storage.storageId"
                :label="storage.storageShortName"
                :value="storage.storageId"
              >
              </el-option>
            </el-select>
          </el-col>
          <!--          <el-col :span="1.5">
                      <el-select v-model="storageLocation" filterable placeholder="选择库位">
                        <el-option v-for="storageLoc in filterStorageLoc" :key="storageLoc.locationId"
                                   :label="storageLoc.locationId" :value="storageLoc.locationId">
                        </el-option>
                      </el-select>
                    </el-col>-->
          <el-col :span="1.5">
            <el-select
              v-model="storageMode"
              :disabled="subStorageModeEnabled"
              placeholder="入库类型"
            >
              <el-option
                v-for="dict in dict.type.warehouse_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-col>
<!--          <right-toolbar
            ref="toolBarRef"
            @customCols="customColsHandler"
            :showSearch.sync="showSubSearch"
            showColumnsType="transfer"
            :columns="subColumns"
          ></right-toolbar>-->
        </el-row>
        </div>

        <div class="search-container" ref="subSearchPanel" style="padding-top: 3px;">
        <el-form
          :model="querySubParams"
          ref="querySubParams"
          size="mini"
          :inline="true"
          v-show="showSubSearch"
          label-width="75px"
        >
<!--          <el-form-item label="子需求编号" prop="businessId">
            <el-input
              v-model="querySubParams.businessId"
              placeholder="请输入子需求编号"
              clearable
              @keyup.enter.native="handleSubQuery"
            />
          </el-form-item>
          <el-form-item label="物料编号" prop="goodsId">
            <el-input
              v-model="querySubParams.goodsId"
              placeholder="请输入物料编号"
              clearable
              @keyup.enter.native="handleSubQuery"
            />
          </el-form-item>
          <el-form-item label="物料名称" prop="goodsName">
            <el-input
              v-model="querySubParams.goodsName"
              placeholder="请输入物料名称"
              clearable
              @keyup.enter.native="handleSubQuery"
            />
          </el-form-item>
          <el-form-item label="规格" prop="specification">
            <el-input
              v-model="querySubParams.specification"
              placeholder="请输入规格"
              clearable
              @keyup.enter.native="handleSubQuery"
            />
          </el-form-item>
          <el-form-item label="物料描述" prop="recoil">
            <el-input
              v-model="querySubParams.recoil"
              placeholder="请输入物料描述"
              clearable
              @keyup.enter.native="handleSubQuery"
            />
          </el-form-item>-->
          <!-- <el-form-item label="供应商名称" prop="providerId">
            <el-input
              v-model="querySubParams.providerId"
              placeholder="请输入供应商名称"
              clearable
              @keyup.enter.native="handleSubQuery"
            />
          </el-form-item> -->
<!--          <el-form-item label="仓库" prop="storageId">
            <el-select
              v-model="querySubParams.storageId"
              filterable
              placeholder="选择仓库"
              @keyup.enter.native="handleSubQuery"
            >
              <el-option
                v-for="storage in filterStorage"
                :key="storage.storageId"
                :label="storage.storageName"
                :value="storage.storageId"
              >
              </el-option>
            </el-select>
          </el-form-item>-->
        </el-form>
        </div>
        <el-table
          border
          :height="subTableHeight"
          size="mini"
          :data="trkWareNoticeTabList"
          :row-class-name="rowTRkWareNoticeTabIndex"
          @selection-change="handleTRkWareNoticeTabSelectionChange"
          ref="tRkWareNoticeTab"
        >
          <el-table-column type="selection" width="45" align="center"/>
          <el-table-column
            label="序号"
            align="center"
            prop="index"
            width="50"
          />
          <el-table-column
            label="子需求编号"
            prop="salesOrderNumber"
            width="150"
          >
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.salesOrderNumber"
                placeholder="请输入子需求编号"
              />
              <span v-else>{{ scope.row.salesOrderNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料编号" prop="goodsId" width="160">
            <template slot-scope="scope">
              <div v-if="scope.row.addFlg">
                <el-input
                  v-model="scope.row.goodsId"
                  placeholder="请输入物料编号"
                  style="width: 85% !important"
                />
                <el-button
                  icon="el-icon-search"
                  size="mini"
                  @click="handleRowGoodsSelect(scope.row)"
                  style="border: none; width: 15%; padding-left: 3px"
                ></el-button>
              </div>
              <span v-else>{{ scope.row.goodsId }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" prop="goodsName" width="200">
            <template slot-scope="scope">
              <!-- 移除了条件渲染的 el-input，改为始终显示 span -->
              <span>{{ scope.row.goodsName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否锁定" prop="goodsName" width="200">
            <template slot-scope="scope">
              <span v-if="scope.row.inStatus == '1'">冻结</span>
              <span v-else>正常</span>
            </template>
          </el-table-column>
          <el-table-column label="到货数量" prop="arraMount" width="160">
            <template slot-scope="scope">
              <el-input-number
                v-if="scope.row.addFlg"
                :min="1"
                v-model="scope.row.arraMount"
                placeholder="请输入到货数量"
              />
              <span v-else>{{ scope.row.arraMount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="到货单号" prop="arrivalNum" width="160">
            <template slot-scope="scope">
              <span>{{ scope.row.arrivalNum }}</span>
            </template>
          </el-table-column>

          <el-table-column label="签收数量" prop="receivingNum" width="160">
            <template slot-scope="scope">
              <el-input-number
                v-if="scope.row.editFlg"
                :min="0"
                v-model="scope.row.receivingNum"
                placeholder="请输入签收数量"
              />
              <span v-else>{{ scope.row.receivingNum }}</span>
            </template>
          </el-table-column>

          <!-- <el-table-column label="本次签收数量" prop="recNumNow" width="160">
            <template slot-scope="scope">
              <el-input-number
                v-if="scope.row.editFlg"
                :min="0"
                v-model="scope.row.recNumNow"
                placeholder="请输入签收数量"
              />
              <span v-else>{{ scope.row.recNumNow }}</span>
            </template>
          </el-table-column> -->
<!--          <el-table-column label="仓库" prop="storageId" width="150">
            <template slot-scope="scope">
              <el-select
                v-if="scope.row.editFlg"
                v-model="scope.row.storageId"
                filterable
                placeholder="请选择仓库"
                @change="handleSelectRowStorage(scope.row)"
              >
                <el-option
                  v-for="storage in filterStorage"
                  :key="storage.storageId"
                  :label="storage.storageName"
                  :value="storage.storageId"
                >
                </el-option>
              </el-select>
              <span v-else>{{ scope.row.storageId }}</span>
            </template>
          </el-table-column>-->
          <!-- <el-table-column label="库位" prop="storageLocation" width="150">
            <template slot-scope="scope">
              <el-select v-if="scope.row.editFlg" v-model="scope.row.storageLocation" filterable placeholder="请选择库位">
                <el-option v-for="storageLoc in scope.row.storageLocations" :key="storageLoc.locationId"
                  :label="storageLoc.locationId" :value="storageLoc.locationId">
                </el-option>
              </el-select>
              <span v-else>{{ scope.row.storageLocation }}</span>
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="库区" prop="storageAreaId" width="150">
            <template slot-scope="scope">
              <el-select v-if="scope.row.editFlg" v-model="scope.row.storageAreaId" width="150" placeholder="请选择库区">
                <el-option label="请选择库区" value="" />
              </el-select>
              <span v-else>{{ scope.row.storageAreaId }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="单位" prop="unit" width="150">
            <template slot-scope="scope">
              <el-select
                v-if="scope.row.addFlg"
                filterable
                v-model="scope.row.unit"
                placeholder="请选择物料单位"
              >
                <el-option
                  v-for="dict in dict.type.goods_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.label"
                />
              </el-select>
              <dict-tag
                v-else
                :options="dict.type.goods_unit"
                :value="scope.row.unit"
              />
              <!-- <span v-else>{{ scope.row.unit }}</span> -->
            </template>
          </el-table-column>
          <el-table-column label="规格型号" prop="specification" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.specification"
                placeholder="请输入规格型号"
              />
              <span v-else>{{ scope.row.specification }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料描述" prop="recoil" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.recoil"
                placeholder="请输入物料描述"
              />
              <span v-else>{{ scope.row.recoil }}</span>
            </template>
          </el-table-column>
          <el-table-column label="品牌" prop="brand" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.brand"
                placeholder="请输入品牌"
              />
              <span v-else>{{ scope.row.brand }}</span>
            </template>
          </el-table-column>
          <el-table-column label="计划单价" prop="price" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.price"
                placeholder="请输入计划单价"
              />
              <span v-else>{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column label="计划金额" prop="totalMoney" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.totalMoney"
                placeholder="请输入计划金额"
              />
              <span v-else>{{ scope.row.totalMoney }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工程项目" prop="project" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.project"
                placeholder="请输入工程项目"
              />
              <span v-else>{{ scope.row.project }}</span>
            </template>
          </el-table-column>
          <el-table-column label="需求部门" prop="needDept" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.needDept"
                placeholder="请输入需求部门"
              />
              <span v-else>{{ scope.row.needDept }}</span>
            </template>
          </el-table-column>
          <el-table-column label="需求人" prop="needPerson" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.needPerson"
                placeholder="请输入需求人"
              />
              <span v-else>{{ scope.row.needPerson }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用途" prop="useType" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.useType"
                placeholder="请选择用途"
              />
              <span v-else>{{ scope.row.useType }}</span>
            </template>
          </el-table-column>
          <el-table-column label="上报时间" prop="productionDate" width="240">
            <template slot-scope="scope">
              <el-date-picker
                v-if="scope.row.addFlg"
                clearable
                v-model="scope.row.productionDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择上报时间"
              />
              <span v-else>{{ scope.row.productionDate }}</span>
            </template>
          </el-table-column>
          <el-table-column label="技术需求附件" prop="packageId" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.packageId"
                placeholder="请输入技术需求附件"
              />
              <span v-else>{{ scope.row.packageId }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料分类" prop="goodsTypeId" width="150">
            <template slot-scope="scope">
              <el-select
                v-if="scope.row.addFlg"
                filterable
                v-model="scope.row.goodsTypeId"
                placeholder="请选择物料分类"
              >
                <el-option
                  v-for="dict in dict.type.goods_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
              <dict-tag
                v-else
                :options="dict.type.goods_type"
                :value="scope.row.goodsTypeId"
              />
            </template>
          </el-table-column>
          <el-table-column label="收货状态" prop="receivingStatus" width="150">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.receive_status"
                :value="scope.row.receivingStatus"
              />
            </template>
          </el-table-column>
          <el-table-column label="申请人" prop="applicant" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.applicant"
                placeholder="请输入申请人"
              />
              <span v-else>{{ scope.row.applicant }}</span>
            </template>
          </el-table-column>
          <el-table-column label="申请部门" prop="supplier" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.supplier"
                placeholder="请输入申请部门"
              />
              <span v-else>{{ scope.row.supplier }}</span>
            </template>
          </el-table-column>
          <el-table-column label="批次号" prop="batchNo" width="150">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.addFlg"
                v-model="scope.row.batchNo"
                placeholder="请输入批次号"
              />
              <span v-else>{{ scope.row.batchNo }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="100"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-if="!scope.row.editFlg"
                @click="handleRowEdit(scope.row, '1')"
              >编辑
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-if="scope.row.editFlg"
                @click="handleRowEdit(scope.row, '0')"
              >取消编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加或修改入库通知单对话框 -->
    <el-dialog
      id="dialog-container"
      :title="title"
      :visible.sync="open"
      width="1050px"
      append-to-body
    >
      <div class="edit-container">
        <el-form ref="form" :model="form" :rules="rules" label-width="95px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="来源单号" prop="deliveryId">
                <el-input v-model="form.deliveryId = generateUniqueId()" placeholder="请输入来源单号" disabled/>
              </el-form-item>

<!--              <el-col :span="24">
                <el-form-item label="agv执行" prop="isAvgExec">
                  <el-radio-group v-model="form.isAvgExec">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>-->


            </el-col>
            <el-col :span="6">
              <el-form-item label="供应商编号" prop="providerId">
                <el-input
                  v-model="form.providerId"
                  placeholder="请输入供应商编号"
                  style="width: 85% !important"
                />
                <el-button
                  icon="el-icon-search"
                  size="mini"
                  @click="handleRowProviderSelect"
                  style="border: none; width: 15%; padding-left: 3px"
                ></el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商名称" prop="providerName">
                <el-input
                  v-model="form.providerName"
                  placeholder="请输入供应商名称"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="发货单号" prop="purchaseId">
                <el-input
                  v-model="form.purchaseId"
                  placeholder="请输入发货单号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="发货组织" prop="shippingDept">
                <el-input
                  v-model="form.shippingDept"
                  placeholder="请输入发货组织"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系人" prop="contact">
                <el-input v-model="form.contact" placeholder="请输入联系人"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系方式" prop="telephone">
                <el-input
                  v-model="form.telephone"
                  placeholder="请输入联系方式"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="收货地址" prop="receiveAddr">
                <el-input
                  v-model="form.receiveAddr"
                  placeholder="请输入收货地址"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="发货日期" prop="sendeDate">
                <el-date-picker
                  clearable
                  v-model="form.sendeDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择发货日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="采购组织" prop="purchaseDept">
                <el-input
                  v-model="form.purchaseDept"
                  placeholder="请输入采购组织"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="送货区域" prop="receivingArea">
                <el-input
                  v-model="form.receivingArea"
                  placeholder="请输入送货区域"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="使用单位收货人" prop="useReceiver">
                <el-input
                  v-model="form.useReceiver"
                  placeholder="请输入使用单位收货人"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="使用单位保管员" prop="useCustodian">
                <el-input
                  v-model="form.useCustodian"
                  placeholder="请输入使用单位保管员"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="使用单位主管" prop="useLeader">
                <el-input
                  v-model="form.useLeader"
                  placeholder="请输入使用单位主管"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收货人" prop="receiver">
                <el-input v-model="form.receiver" placeholder="请输入收货人"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
<!--            <el-col :span="6">
              <el-form-item label="申请人" prop="applicant">
                <el-input v-model="form.applicant" placeholder="请输入申请人" disabled/>
              </el-form-item>
            </el-col>-->
            <el-col :span="6">
              <el-form-item label="收货组织" prop="produclotId">
                <el-input
                  v-model="form.produclotId"
                  placeholder="请输入收货组织"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收货人部门" prop="receiverDept">
                <el-input
                  v-model="form.receiverDept"
                  placeholder="请输入收货人部门"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="招标员" prop="tenderer">
                <el-input v-model="form.tenderer" placeholder="请输入招标员"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="入库类型" prop="storageMode">
                <el-select
                  v-model="form.storageMode"
                  :disabled="storageModeEnabled"
                  placeholder="入库类型"
                >
                  <el-option
                    v-for="dict in dict.type.warehouse_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="需求组织" prop="operatorId">
                <el-input
                  v-model="form.operatorId"
                  placeholder="请输入需求组织"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="form.remark"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择状态">
                  <el-option
                    v-for="dict in dict.type.common_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <!-- <el-col :span="6">
              <el-form-item label="收货状态" prop="receivingStatus">
                <el-select v-model="form.receivingStatus" placeholder="请选择收货状态">
                  <el-option
                    v-for="dict in dict.type.receive_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row></el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 数据导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox
            v-model="upload.updateSupport"
          />
          是否更新已经存在的通知单数据
          <el-link type="primary" style="font-size: 12px" @click="importTemplate">下载模板
          </el-link
          >
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

     <!-- 数据导入对话框 -->
     <el-dialog :title="uploadExcel.title" :visible.sync="uploadExcel.open" width="400px">
      <el-upload
        ref="uploadExcel"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="uploadExcel.headers"
        :action="uploadExcel.url + '?updateSupport=' + uploadExcel.updateSupport"
        :disabled="uploadExcel.isUploading"
        :on-progress="handleExcelFileUploadProgress"
        :on-success="handleExcelFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox
            v-model="uploadExcel.updateSupport"
          />
          是否更新已经存在的通知单数据
          <el-link type="primary" style="font-size: 12px" @click="importExcelTemplate">下载模板
          </el-link
          >
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitExcelFileForm">确 定</el-button>
        <el-button @click="uploadExcel.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <GoodsSelect ref="goodsSelect"></GoodsSelect>
    <ProviderSelect ref="providerSelect"></ProviderSelect>
    <ExistOrdersSelect v-if="this.storageMode == '2'" ref="existOrdersSelect"></ExistOrdersSelect>
  </div>
</template>

<script>
import { listCOLUMN } from "@/api/system/column";
import { listStorageAreaLocation } from "@/api/system/storage";
import {
  addTrkNotice,
  confirmNoticeTab,
  delTrkNotice,
  delTrkNoticeTabs,
  getTrkNotice,
  listTrkNotice,
  saveNoticeTab,
  updateTrkNotice,
  sendOrderNotice
} from "@/api/system/trkNotice";
import { listTrkWareNoticeTab } from "@/api/system/trkWareNoticeTab";
import TableMixin from "@/api/tableMixin";
import { getToken } from "@/utils/auth";
import ExistOrdersSelect from "@/views/system/dialog/ExistOrdersSelect";
import GoodsSelect from "@/views/system/dialog/GoodsSelect";
import ProviderSelect from "@/views/system/dialog/ProviderSelect";

export default {
  name: "TrkNotice",
  dicts: [
    "receive_status",
    "common_status",
    "warehouse_type",
    "goods_unit",
    "goods_type",
  ],
  components: {GoodsSelect, ProviderSelect, ExistOrdersSelect},
  mixins: [TableMixin],
  data() {
    return {
      nickName: '',
      rndKey: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 出库退库
      goodsReturn: false,
      // 子表选中数据
      checkedTRkWareNoticeTab: [],
      //选择数据 agv 校验
      agv: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 显示搜索条件
      showSubSearch: true,
      // 总条数
      total: 0,
      //明细总条数
      subTotal: 0,
      // 入库通知单表格数据
      trkNoticeList: [],
      // 入库通知单明细表格数据
      trkWareNoticeTabList: [],
      // 选中入库通知单ID
      noticeId: "",
      id: 0,
      // 仓库Id
      storageId: "",
      // 库位
      storageLocation: "",
      // 库区ID
      storageAreaId: "",
      // 入库类型
      storageMode: "",
      // 弹出层标题
      title: "",
      funTitle: "",
      mainTableHeight: "0px",
      mainTableDivHeight: "0px",
      subTableHeight: "0px",
      subTableDivHeight: "0px",
      businessCodeTrk: "trkNotice",
      rightToolbarShow: false,
      tableNo: 0,
      sidebarStatus: null,
      showButton: true,
      button: true,
      // 是否显示弹出层
      open: false,
      // 库存库区库位列表
      storageAreaLocations: [],
      storageIds: [],
      storageLocations: [],
      storageTotalList: [],
      totalStorageMap: {},
      // 查询窗口高度
      // searchHeight:0,
      storageModeEnabled: true,
      subStorageModeEnabled: false,
      // 托盘号
      ctlNo: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        noticeId: null,
        deliveryId: '',
        providerId: null,
        providerName: null,
        purchaseId: null,
        shippingDept: null,
        contact: null,
        telephone: null,
        sendeDate: null,
        purchaseDept: null,
        receiver: null,
        storageMode: null,
        purchaser: null,

      },
      // 查询子表参数
      querySubParams: {
        pageNum: 1,
        pageSize: 10,
        businessId: null,
        goodsId: '',
        goodsName: null,
        providerId: null,
        specification: null,
        noticeId: null,
        sendeDate: null,
        storageId: null,
        recoil: null,
        serialNumber:0
      },
      // 表单参数
      form: {
        deliveryId: '',
        isAvgExec: 0,
      },
      // 表单校验
      rules: {
        deliveryId: [
          {required: true, message: "来源单号不能为空", trigger: "blur"},
        ],
        storageMode: [
          {required: true, message: "请选择入库类型", trigger: "blur"},
        ],

        ctlNo: [
          {required: true, message: "楼层必须选", trigger: "blur"},
        ]
      },
      columns: [],
      subColumns: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/trkNotice/importData",
      },
       // 用户导入参数
       uploadExcel: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/trkNotice/importExcelData",
      },

    };
  },

  created() {
    this.getStorageAreaLocation();
    this.nickName = this.$store.state.user.nickName


    // 采购入库
    if (this.$route.path.indexOf("purchase") > -1) {
      this.storageMode = "1";
      this.funTitle = "一级入库";
      this.button = false;
    } else if (this.$route.path.indexOf("workShopReturn") > -1) {
      // 车间退货入库
      this.storageMode = "2";
      this.funTitle = "物资退库申请";
    } else if (this.$route.path.indexOf("secondaryWarehousing") > -1) {
      // 二级入库（采购入库）
      this.storageMode = "3";
      this.funTitle = "二级入库";
      this.showButton = false;
    } else if (this.$route.path.indexOf("otherWarehousing") > -1) {
      // 其它入库
      this.storageMode = "4";
      this.funTitle = "其它入库";
    } else if (this.$route.path.indexOf("storageWarehousing") > -1) {
      // 寄存入库（货主选择）
      this.storageMode = "5";
      this.funTitle = "VMI入库";
    } else {
      // 入库可选择
      this.storageMode = "";
      this.funTitle = "入库";
      this.storageModeEnabled = false;
    }

    // 入库类型
    this.queryParams.storageMode = this.storageMode;
    this.getList();
  },
  mounted() {
    this.computedTableHeight();

    if(this.storageMode == "2") {
      this.goodsReturn = true;
      this.handleExistTCkOrder();
    }
  },
  // computed: {
  //   ...mapGetters([
  //     'sidebar'
  //   ])
  // },
  watch: {
    showSearch: function () {
      this.computedTableHeight();
    },
  },
  computed: {
    filterStorage() {
      return this.storageIds;
    },
    filterStorageLoc() {
      return this.storageLocations;
    },
    searchHeight() {
      return this.$refs.searchPanel.clientHeight;
    },
  },
  methods: {
    generateUniqueId() {
      const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      const date = new Date();
      const uniqueId = date.getTime().toString(36).toUpperCase();
      const hours = ('0' + date.getHours()).slice(-2);
      const minutes = ('0' + date.getMinutes()).slice(-2);
      const seconds = ('0' + date.getSeconds()).slice(-2);
      const timeString = hours + minutes + seconds;
      const randomLetter = letters.charAt(Math.floor(Math.random() * letters.length));
      return uniqueId + timeString + randomLetter;
    },

    /** 查询用户展示字段定义管理列表 */
    getHideColumn() {
      var queryHideColumnParams = {
        pageNum: 1,
        pageSize: 100,
        businessCode: this.businessCodeTrk,
        tableNo: this.tableNo,
      };
      listCOLUMN(queryHideColumnParams).then((response) => {
        if (response.rows.length > 0) {
          var row = response.rows[0];
          var columnHide = row.columnHide.split(",");
          if (columnHide.length > 0) {
            for (let item in this.columns) {
              if (columnHide.indexOf(this.columns[item].columnName) > -1) {
                this.columns[item].visible = false;
              }
            }
          }
        }
        this.rightToolbarShow = true;
      });
    },
    computedTableHeight() {
      this.$nextTick(() => {
        var totalHeight = this.$refs.appPanel.clientHeight;
        var toolHeight = this.$refs.toolPanel.clientHeight;
        var searchHeight = this.$refs.searchPanel.clientHeight;
        var subSearchPanelHeight = this.$refs.subSearchPanel.clientHeight;

        var tablePanelHeight = totalHeight - toolHeight - searchHeight - subSearchPanelHeight - 7;

        var mainHeight = tablePanelHeight / 3;
        this.mainTableDivHeight = mainHeight + "px";
        this.mainTableHeight = mainHeight - 25 + "px";
        this.subTableDivHeight = tablePanelHeight - mainHeight + "px";
        this.subTableHeight = tablePanelHeight - mainHeight - 25 - 33 + "px";
      });
    },
    /** 查询入库通知单列表 */
    getList() {
      this.loading = true;
      listTrkNotice(this.queryParams).then((response) => {
        this.trkNoticeList = response.rows;
        this.total = response.total;
        if (this.columns.length == 0) this.columns = response.columns;
        this.loading = false;
      });
    },
    /** 查询入库通知单明细列表 */
    getSubList() {
      if (this.querySubParams.noticeId == null || this.querySubParams.noticeId == "") {
        this.$modal.msgError("请先选择通知单");
        return;
      }

      if (this.querySubParams.goodsId != null && this.querySubParams.goodsId != "") {
        this.querySubParams.goodsId = this.querySubParams.goodsId.replace(/\s+/g,"").toUpperCase();
      }
      listTrkWareNoticeTab(this.querySubParams).then((response) => {

        this.trkWareNoticeTabList = [];

        for (var i = 0; i < response.rows.length; i++) {
          this.$set(
            response.rows[i],
            "isNewRecord",
            false
          );
          // response.rows[i].receivingNum= response.rows[i].arraMount -;
              // = response.rows[i].arraMount - response.rows[i].recNum;
        }

        this.trkWareNoticeTabList = response.rows;
        this.subTotal = response.total;
        if (this.subColumns.length === 0) this.subColumns = response.columns;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        noticeId: null,
        deliveryId: null,
        providerId: null,
        providerName: null,
        purchaseId: null,
        shippingDept: null,
        contact: null,
        telephone: null,
        receiveAddr: null,
        sendeDate: null,
        purchaseDept: null,
        remark: null,
        receivingArea: null,
        useReceiver: null,
        useCustodian: null,
        useLeader: null,
        receiver: null,
        applicant: null,
        produclotId: null,
        receiverDept: null,
        tenderer: null,
        operatorId: null,
        factoryId: null,
        storageMode: this.storageMode,
        status: "0",
        receivingStatus: null,
        orderType: null,
        createBy: null,
        updateBy: null,
        createTime: null,
        updateTime: null,
        storageTotalList: [],
      };
      this.trkWareNoticeTabList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.trkWareNoticeTabList = [];
      this.id = "";
      this.noticeId = "";
    },
    /** 搜索按钮操作 */
    handleSubQuery() {
      this.querySubParams.pageNum = 1;
      this.getSubList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 重置按钮操作 */
    resetSubQuery() {
      this.resetForm("querySubForm");
      this.handleSubQuery();
    },
    // 增加主表行双击事件,查询子表数据
    handleMainTableClick(row) {
      this.noticeId = row.noticeId;
      this.id = row.id;
      this.storageMode = row.storageMode;
      this.subStorageModeEnabled = true;
      this.getTrkNoticeTabs(1);
    },
    getTrkNoticeTabs(type) {
      getTrkNotice(this.id).then((response) => {
        if (response.data.noticeId == null) {
          if (type == 2) {
            this.trkWareNoticeTabList = [];
            this.getList();
          } else {
            this.getList();
            this.$modal.msgSuccess("通知单数据已被其他用户更新，列表刷新");
          }
          this.trkWareNoticeTabList = [];
          this.id = "";
          this.noticeId = "";
          return;
        }

        for (var i = 0; i < response.data.trkWareNoticeTabList.length; i++) {
          this.$set(
            response.data.trkWareNoticeTabList[i],
            "storageAreaLocations",
            []
          );
          this.$set(response.data.trkWareNoticeTabList[i], "storageId", "");
          this.$set(
            response.data.trkWareNoticeTabList[i],
            "isNewRecord",
            false
          );
          // response.data.trkWareNoticeTabList[i].receivingNum =  response.data.trkWareNoticeTabList[i].arraMount;
            // response.data.trkWareNoticeTabList[i].arraMount -
            // response.data.trkWareNoticeTabList[i].recNum;
        }
        this.trkWareNoticeTabList = response.data.trkWareNoticeTabList;
        this.querySubParams.noticeId = this.id;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.agv = selection
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加入库通知单";
      this.form.applicant = this.$store.state.user.name
      console.log(this.form.applicant, "12313")
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getTrkNotice(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改入库通知单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.storageMode == "") {
            this.$modal.msgError("入库类型不能为空");
            return;
          }
          if (this.form.id != null) {
            this.form.trkWareNoticeTabList = this.trkWareNoticeTabList;
            updateTrkNotice(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.trkWareNoticeTabList = [];
            addTrkNotice(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.id = ""
              this.noticeId = ""
            });
          }
        }
      });
    },
    /** 删除按钮操作 */

    handleDelete(row) {
      const ids = row.id || this.ids;
      const that = this;
      this.$modal
        .confirm('是否确认删除入库通知单编号为"' + ids + '"的数据项？')
        .then(function () {
          if (ids.indexOf(that.id) > -1) {
            this.noticeId = "";
            this.id = "";
            this.trkWareNoticeTabList = [];
          }
          return delTrkNotice(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
        });
    },

    /** 入库通知单明细序号 */
    rowTRkWareNoticeTabIndex({row, rowIndex}) {
      row.index = rowIndex + 1;

      if (row.inStatus == "1") {
        return "warning-row";
      }
    },
    /** 入库通知单明细添加按钮操作 */
    handleAddTRkWareNoticeTab() {
      if (this.noticeId == "") {
        this.$modal.msgError("请先选择入库通知单");
        return;
      }

      if (this.ids.length > 1) {
        this.$modal.msgError("添加明细数据的入库通知单只能选择一个");
        return;
      }

      let obj = {};
      obj.salesOrderNumber = "";
      obj.goodsId = "";
      obj.goodsName = "";
      obj.unit = "";
      obj.specification = "";
      obj.recoil = "";
      obj.brand = "";
      obj.price = "";
      obj.totalMoney = "";
      obj.arraMount = "";
      obj.recNum = "";
      obj.receivingNum = "";
      obj.project = "";
      obj.needDept = "";
      obj.useType = "";
      obj.productionDate = "";
      obj.packageId = "";
      obj.remark = "";
      obj.goodsTypeId = "";
      obj.status = "";
      obj.applicant = "";
      obj.inStatus = "0";
      obj.supplier = "";
      obj.batchNo = "";
      obj.editFlg = true;
      obj.storageAreaId = "";
      obj.storageId = "";
      obj.storageLocation = "";
      obj.storageLocations = [];
      obj.recNumNow = "";
      obj.addFlg = true;
      obj.isNewRecord = true;
      this.trkWareNoticeTabList.push(obj);
    },
    /** 入库通知单明细删除按钮操作 */
    handleDeleteTRkWareNoticeTab() {
      if (this.checkedTRkWareNoticeTab.length == 0) {
        this.$modal.msgError("请先选择要删除的入库通知单明细数据");
      } else {
        var that = this;
        this.$modal
          .confirm("是否确认删除选中的入库通知单明细数据项？")
          .then(function () {
            const trkWareNoticeTabList = that.trkWareNoticeTabList;
            const checkedTRkWareNoticeTab = that.checkedTRkWareNoticeTab;

            var tabIds = [];
            for (var i = 0; i < checkedTRkWareNoticeTab.length; i++) {
              var tabObj = trkWareNoticeTabList[checkedTRkWareNoticeTab[i] - 1];
              if (!tabObj.isNewRecord) {
                tabIds.push(tabObj.id);
              }
            }

            if (tabIds.length == 0) {
              that.trkWareNoticeTabList = trkWareNoticeTabList.filter(function (
                item
              ) {
                return checkedTRkWareNoticeTab.indexOf(item.index) == -1;
              });
              return;
            }

            delTrkNoticeTabs(tabIds).then((response) => {
              if (response.code == 200) {
                if (response.data.error != "") {
                  that.$modal.msgError(response.data.error);
                  return;
                } else {
                  that.$modal.msgSuccess(response.data.success);

                  that.trkWareNoticeTabList = trkWareNoticeTabList.filter(
                    function (item) {
                      return checkedTRkWareNoticeTab.indexOf(item.index) == -1;
                    }
                  );
                }
              } else {
                that.$modal.msgError("发生系统错误，入库通知单明细删除失败");
                return;
              }
            });
          });
      }
    },
    handleRowEdit(row, type) {
      if (row.inStatus == "1") {
        this.$modal.msgError("物料已冻结，不可编辑");
        return;
      }

      if (type == "1") {
        row.editFlg = true;
        if (row.isNewRecord) {
          row.addFlg = true;
        }
      } else {
        row.editFlg = false;
        row.addFlg = false;
      }
    },
    /**手动完成 */
    /* handleManualCompletion() {
       if (this.checkedTRkWareNoticeTab.length == 0) {
         this.$modal.msgError("请选择要提交的入库通知单明细");
         return;
       }

       const commitTrkWareNoticeTabList = [];
       var checkResult = true;
       for (var i = 0; i < this.checkedTRkWareNoticeTab.length; i++) {
         var trkWareNoticeTab =
           this.trkWareNoticeTabList[this.checkedTRkWareNoticeTab[i] - 1];

         if (trkWareNoticeTab.isNewRecord) {
           this.$modal.msgError("未保存的入库通知单明细数据不能手动结束");
           return;
         }

         if (trkWareNoticeTab.inStatus == "1") {
           this.$modal.msgError(
             "物料【" + trkWareNoticeTab.goodsName + "】已冻结，不可手动结束"
           );
           return;
         }

         commitTrkWareNoticeTabList.push(trkWareNoticeTab);
       }

       var form = {
         id: this.id,
         noticeId: this.noticeId,
         trkWareNoticeTabList: commitTrkWareNoticeTabList,
       };

       var that = this;
       this.$modal.confirm("确认手动完成吗？").then(function () {
         manualCompletion(form).then((response) => {
           if (response.code != 200) {
             that.$modal.msgError("发生系统错误，通知单明细手动完成失败");
             return;
           }
           if (response.data.error != "") {
             that.$modal.msgError(response.data.error);
             return;
           } else {
             that.$modal.msgSuccess(response.data.success);
           }
           that.getTrkNoticeTabs(2);
         });
       });
     },*/
    /**保存通知单 */
    confirmSave() {
      if (this.checkedTRkWareNoticeTab.length == 0) {
        this.$modal.msgError("请选择要提交的入库通知单明细");
        return;
      }

      /*for (let i = 0; i < this.agv.length; i++) {
        const c = this.agv[i];
        console.log("当前项", c);
        if (c.isAvgExec === 1 && this.ctlNo === '') {
          this.$modal.msgWarning("agv执行必须选择库位绑定托盘");
          return; // 这将停止整个函数的执行
        }
      }*/

      const commitTrkWareNoticeTabList = [];
      var checkResult = true;

      var existData = [];

      for (var i = 0; i < this.trkWareNoticeTabList.length; i++) {
        var trkWareNoticeTab = this.trkWareNoticeTabList[i];
        if (!trkWareNoticeTab.isNewRecord) {
          existData.push(
            trkWareNoticeTab.salesOrderNumber + trkWareNoticeTab.goodsId
          );
        }
      }

      for (var i = 0; i < this.checkedTRkWareNoticeTab.length; i++) {
        var trkWareNoticeTab =
          this.trkWareNoticeTabList[this.checkedTRkWareNoticeTab[i] - 1];

        if (!trkWareNoticeTab.isNewRecord) {
          this.$modal.msgError("只能提交新追加的通知单明细数据");
          return;
        }

        if (trkWareNoticeTab.goodsId == "") {
          checkResult = false;
          this.$modal.msgError("物料编码不能为空");
          return;
        }

        if (trkWareNoticeTab.goodsName == "") {
          checkResult = false;
          this.$modal.msgError("物料名称不能为空");
          return;
        }

        if (trkWareNoticeTab.salesOrderNumber == "") {
          checkResult = false;
          this.$modal.msgError(
            "物料【" + trkWareNoticeTab.goodsName + "】的子需求编号不能为空"
          );
          return;
        }
        // if (trkWareNoticeTab.receivingNum > 0) {
        //   checkResult = false;
        //   this.$modal.msgError(
        //     "物料【" + trkWareNoticeTab.goodsName + "】签收数量必须大于0"
        //   );
        //   return;
        // }
        if (
          trkWareNoticeTab.arraMount == "" ||
          trkWareNoticeTab.arraMount == 0
        ) {
          checkResult = false;
          this.$modal.msgError("到货数量不能为空");
          return;
        }

        if (trkWareNoticeTab.receivingNum > trkWareNoticeTab.arraMount) {
          checkResult = false;
          this.$modal.msgError(
            "物料【" + trkWareNoticeTab.goodsName + "】签收数量不能大于到货数量"
          );
          return;
        }


        var existDataFlg =
          trkWareNoticeTab.salesOrderNumber + trkWareNoticeTab.goodsId;
        if (existData.indexOf(existDataFlg) > -1) {
          checkResult = false;
          this.$modal.msgError("子需求编号和物料编码不能重复");
          return;
        }
        existData.push(existDataFlg);
        commitTrkWareNoticeTabList.push(trkWareNoticeTab);
        commitTrkWareNoticeTabList.forEach(c => {
          c.ctl = this.ctlNo
        })
      }

      if (!checkResult) return;

      var form = {
        id: this.id,
        noticeId: this.noticeId,
        storageMode: this.storageMode,
        trkWareNoticeTabList: commitTrkWareNoticeTabList,
      };

      var that = this;
      this.$modal.confirm("确认保存吗？").then(function () {
        saveNoticeTab(form).then((response) => {
          if (response.code != 200) {
            that.$modal.msgError("发生系统错误，物料保存失败");
            return;
          }
          if (response.data.error != "") {
            that.$modal.msgError(response.data.error);
            return;
          } else {
            that.$modal.msgSuccess(response.data.success);
          }
          that.getTrkNoticeTabs(2);
        });
      });
    },
    /** 确认收货 */
    confirmReceive() {
      if (this.checkedTRkWareNoticeTab.length == 0) {
        this.$modal.msgError("请选择要提交的入库通知单明细");
        return;
      }

      if (this.storageMode == "") {
        this.$modal.msgError("请选择入库类型");
        return;
      }

      // if (this.ctlNo == "") {
      //   this.$modal.msgError("请输入托盘号");
      //   return;
      // }

      const commitTrkWareNoticeTabList = [];
      var checkResult = true;
      for (var i = 0; i < this.checkedTRkWareNoticeTab.length; i++) {
        var trkWareNoticeTab =
          this.trkWareNoticeTabList[this.checkedTRkWareNoticeTab[i] - 1];

        if (trkWareNoticeTab.isNewRecord) {
          checkResult = false;
          this.$modal.msgError("新增通知单明细，请先保存再收货");
          return;
          // if (trkWareNoticeTab.goodsId == "") {
          //   checkResult = false;
          //   this.$modal.msgError("物料编码不能为空");
          //   return;
          // }

          // if (trkWareNoticeTab.goodsName == "") {
          //   checkResult = false;
          //   this.$modal.msgError("物料名称不能为空");
          //   return;
          // }

          // if (trkWareNoticeTab.salesOrderNumber == "") {
          //   checkResult = false;
          //   this.$modal.msgError("物料【" + trkWareNoticeTab.goodsName + "】的子需求编号不能为空");
          //   return;
          // }

          // if (trkWareNoticeTab.arraMount == "" || trkWareNoticeTab.arraMount == 0) {
          //   checkResult = false;
          //   this.$modal.msgError("到货数量不能为空");
          //   return;
          // }

          // if (trkWareNoticeTab.recNum > trkWareNoticeTab.arraMount) {
          //   checkResult = false;
          //   this.$modal.msgError("已签收数量不能大于到货数量");
          //   return;
          // }
        }

        // if (!trkWareNoticeTab.addFlg && (trkWareNoticeTab.recNumNow == "" || trkWareNoticeTab.recNumNow <= 0)) {
        //   checkResult = false;
        //   this.$modal.msgError("物料【" + trkWareNoticeTab.goodsName + "】的本次签收数量为0");
        //   return;
        // }

        if (
          trkWareNoticeTab.receivingNum >
          trkWareNoticeTab.arraMount
        ) {
          checkResult = false;
          this.$modal.msgError(
            "物料【" +
            trkWareNoticeTab.goodsName +
            "】的本次签收数量不能超过" +
            (trkWareNoticeTab.arraMount)
          );
          return;
        }

        if (trkWareNoticeTab.inStatus == "1") {
          checkResult = false;
          this.$modal.msgError(
            "物料【" + trkWareNoticeTab.goodsName + "】已冻结，不可再收货"
          );
          return;
        }

        if (this.storageId == "" && trkWareNoticeTab.storageId == "") {
          checkResult = false;
          this.$modal.msgError("请指定物料的仓库");
          return;
        }
        commitTrkWareNoticeTabList.push(trkWareNoticeTab);
      }

      if (!checkResult) return;

      var form = {
        id: this.id,
        noticeId: this.noticeId,
        storageId: this.storageId,
        storageLocation: this.storageLocation,
        storageAreaId: this.storageAreaId,
        storageMode: this.storageMode,
        trkWareNoticeTabList: commitTrkWareNoticeTabList,
        ctlNo: this.ctlNo,
      };

      var that = this;
      this.$modal.confirm("确认收货吗？").then(function () {
        confirmNoticeTab(form).then((response) => {
          // this.$modal.msgSuccess("");
          if (response.code != 200) {
            that.$modal.msgError("发生系统错误，物料收货失败");
            return;
          }
          if (response.data.error != "") {
            that.$modal.msgError(response.data.error);
            return;
          } else {
            that.$modal.msgSuccess(response.data.success);
          }
          that.getTrkNoticeTabs(2);
        });
      });
    },
    /** 复选框选中数据 */
    handleTRkWareNoticeTabSelectionChange(selection) {
      this.checkedTRkWareNoticeTab = selection.map((item) => item.index);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/trkNotice/export",
        {
          ...this.queryParams,
        },
        `trkNotice_${new Date().getTime()}.xlsx`
      );
    },

    // 数据导入按钮操作
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "二级入库通知单导入";
      this.upload.open = true;
    },
    handleExcelImport() {
      this.uploadExcel.title = "一级入库通知单导入";
      this.uploadExcel.open = true;
    },

    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/trkNotice/importTemplate",
        {},
        `入库_template_${new Date().getTime()}.xlsx`
      );
    },
       /** 下载模板操作 */
     importExcelTemplate() {
      this.download(
        "system/trkNotice/importExcelTemplate",
        {},
        `入库_template_${new Date().getTime()}.xlsx`
      );
    },
     // 文件上传中处理
     handleExcelFileUploadProgress(event, file, fileList) {
      this.uploadExcel.isUploading = true;
    },
    // 文件上传成功处理
    handleExcelFileSuccess(response, file, fileList) {
      this.uploadExcel.open = false;
      this.uploadExcel.isUploading = false;
      this.$refs.uploadExcel.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
      // 提交上传文件
    submitExcelFileForm() {
      this.$refs.uploadExcel.submit();
    },
    /** 查询仓库列表 */
    getStorageAreaLocation() {
      listStorageAreaLocation({}).then((response) => {
        if (response.code == 200) {
          var storageArray = new Array();
          var storageLocationArray = new Array();
          const storageIds = new Set();
          this.storageTotalList = response.data.filter(item => {
            if (storageIds.has(item.storageId)) {
              return false;
            } else {
              storageIds.add(item.storageId);
              return true;
            }
          });

          for (var index = 0; index < response.data.length; index++) {
            var storageInfo = response.data[index];
            if (storageArray.indexOf(storageInfo.storageId) == -1) {
              storageArray.push(storageInfo.storageId);
              this.storageIds.push({
                storageId: storageInfo.storageId,
                storageName: storageInfo.storageName,
              });
              // this.totalStorageMap[storageInfo.storageId] = new Array();

              if (this.storageId == "") {
                this.storageId = storageArray[0];
              }
            }

            if (storageInfo.locationId != "") {
              var locData = {
                "storageId": storageInfo.storageId,
                "storageName": storageInfo.storageName,
                "locationId": storageInfo.locationId
              };

              if (storageLocationArray.indexOf(storageInfo.storageId + storageInfo.locationId) == -1) {
                if (storageInfo.storageId == storageArray[0]) {
                  this.storageLocations.push(locData);
                }
                /*this.totalStorageMap[storageInfo.storageId].push(locData);*/
              }
            }
          }
          storageArray = [];
          storageLocationArray = [];
          this.handleSelectMainStorage();
        } else {
          // this.$modal.msgError("查询仓库库位信息失败");
          this.$modal.msgError("查询仓库信息失败");
        }
      });
    },
    handleSelectMainStorage() {
      // if (this.storageId != "") {
      //   this.storageLocations = this.totalStorageMap[this.storageId];
      //   if (this.storageLocations.length > 0) {
      //     this.storageLocation = this.storageLocations[0].locationId;
      //   }
      // }
    },
    handleSelectRowStorage(row) {
      if (row.storageId != "") {
        row.storageLocations = this.totalStorageMap[row.storageId];
        if (row.storageLocations.length > 0) {
          row.storageLocation = row.storageLocations[0].locationId;
        }
      }
    },
    handleRowGoodsSelect(row) {
      const callBack = (item) => {
        row.goodsId = `${item.goodsId}`;
        row.goodsName = item.goodsName;
        row.goodsTypeId = `${item.goodsTypeId}`;
        row.unit = item.unit;
        row.recoil = item.recoil;
        row.specification = item.specification;
        row.providerId = item.providerId;
        row.barcode = item.barcode;
      };
      this.$refs.goodsSelect.showModal(callBack);
    },
    handleRowProviderSelect() {
      const callBack = (item) => {
        this.form.providerId = `${item.providerId}`;
        this.form.providerName = `${item.providerName}`;
      };
      this.$refs.providerSelect.showModal(callBack);
    },
    handleExistTCkOrder() {
      const callBack = (item) => {
        this.queryParams.noticeId = `${item.noticeId}`;
        this.queryParams.deliveryId = `${item.deliveryId}`;

        this.handleQuery();

        var row = {
          noticeId: `${item.noticeId}`,
          id: `${item.id}`,
          storageMode: "2"
        }
        this.handleMainTableClick(row);
      };

      this.$refs.existOrdersSelect.showModal(callBack);
    },
     sendNotice() {

       const tmpId = this.ids;

       console.log(tmpId)
       if (tmpId.length == 0) {
         this.$modal.msgError("请选择入库通知单");
         return;
       }

       var form = {
         id: tmpId[0],
       };

       var that = this;
       this.$modal.confirm("确认是否发送入库通知单录入完成消息到手持设备？").then(function () {
         sendOrderNotice(form).then((response) => {
           if (response.code != 200) {
             that.$modal.msgError("发生系统错误，通知单消息发送失败");
             return;
           }
           if (response.data.error != "") {
             that.$modal.msgError(response.data.error);
             return;
           } else {
             that.$modal.msgSuccess(response.data.success);
           }
         });
       });
     },

   /* sendIwms() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const tmpId = this.ids;
          console.log(tmpId)
          if (tmpId.length == 0) {
            this.$modal.msgError("请选择入库通知单");
            return;
          }
          var form = {
            id: tmpId[0],
          };
          console.log(this.form.ctlNo,'ctlno')
          for (let i = 0; i < this.agv.length; i++) {
            const c = this.agv[i];
            console.log(c,"12231213123")
            if (c.isAvgExec == 0) {
              this.$modal.msgWarning("该单据不是agv任务");
              return; // 这将停止整个函数的执行
            }
          }
          if(this.form.ctlNo.startsWith('A2')){
            this.$modal.confirm("确认是否发送入库通知单录入完成消息到iwms？").then(function () {
              sendTwoIwms(form).then((response) => {
                if (response.code != 200) {
                  that.$modal.msgError("发生系统错误，通知单消息发送失败");
                  return;
                }
                if (response.data.error != "") {
                  that.$modal.msgError(response.data.error);
                  return;
                } else {
                  that.$modal.msgSuccess(response.data.success);
                }
              });
            });
          }else if (this.form.ctlNo.startsWith('A1')) {
            this.$modal.confirm("确认是否发送入库通知单录入完成消息到iwms？").then(function () {
              sendIwms(form).then((response) => {
                if (response.code != 200) {
                  that.$modal.msgError("发生系统错误，通知单消息发送失败");
                  return;
                }
                if (response.data.error != "") {
                  that.$modal.msgError(response.data.error);
                  return;
                } else {
                  that.$modal.msgSuccess(response.data.success);
                }
              });
            });
          }
        }
      });
    },*/
  },
};
</script>
<style scoped>
.app-container {
  height: calc(100vh - 84px);
}

::v-deep .el-table .warning-row {
  background: #9aa89d;
}
</style>
