<template>
  <div class="mod-config">
    <!-- 条件查询 -->
    <el-card :class="['search-card', { 'collapsed': !searchExpanded }]" shadow="hover">
      <div slot="header" class="search-header">
        <div class="header-left">
          <i class="el-icon-search"></i>
          <span class="header-title">收货入库任务通知</span>
        </div>
        <div class="header-right">
          <el-button
            type="text"
            size="small"
            @click="toggleSearchExpand"
            class="collapse-btn">
            <i :class="searchExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
            {{ searchExpanded ? '收起' : '展开' }}
          </el-button>
        </div>
      </div>

      <el-form
        :inline="true"
        label-position="top"
        :model="searchData"
        class="search-form"
        @keyup.enter.native="getDataList">

        <!-- 所有查询条件 - 可展开/收起 -->
        <template v-if="searchExpanded">
          <!-- 第一行 -->
          <el-row :gutter="16">
            <el-col :span="4">
              <el-form-item label="单据号">
                <el-input v-model="searchData.orderNo" placeholder="请输入单据号" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="单据类型">
                <el-select v-model="searchData.orderType" placeholder="请选择" clearable style="width: 100%">
                  <el-option label="采购入库" value="采购入库"></el-option>
                  <el-option label="生产入库" value="生产入库"></el-option>
                  <el-option label="销售退货" value="销售退货"></el-option>
                  <el-option label="其他入库" value="其他入库"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="单据状态">
                <el-select multiple collapse-tags v-model="searchData.orderStatusList" placeholder="请选择" clearable style="width: 100%">
                  <el-option label="草稿" value="草稿"></el-option>
                  <el-option label="待检验" value="待检验"></el-option>
                  <el-option label="编辑中" value="编辑中"></el-option>
                  <el-option label="待入库" value="待入库"></el-option>
                  <el-option label="已完成" value="已完成"></el-option>
                  <el-option label="已关闭" value="已关闭"></el-option>
                  <el-option label="已归档" value="已归档"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="部门">
                <el-select v-model="searchData.departmentNo" placeholder="请选择" clearable style="width: 100%">
                  <el-option
                    v-for="item in departmentList"
                    :key="item.departmentNo"
                    :label="item.departmentDesc"
                    :value="item.departmentNo">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="要求入库日期(起)">
                <el-date-picker
                  style="width: 91%"
                  v-model="searchData.startDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="开始日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="要求入库日期(止)">
                <el-date-picker
                  style="width: 91%"
                  v-model="searchData.endDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第二行 -->
          <el-row :gutter="16">
            <el-col :span="4">
              <el-form-item label="创建日期(起)">
                <el-date-picker
                  style="width: 91%"
                  v-model="searchData.createdStartDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="开始日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="创建日期(止)">
                <el-date-picker
                  style="width: 91%"
                  v-model="searchData.createdEndDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <!-- 操作按钮区域 -->
        <el-row :gutter="16">
          <el-col :span="24">
            <div class="search-actions">
              <div class="action-left">
                <el-button
                  v-if="!authSearch"
                  type="primary"
                  icon="el-icon-search"
                  :loading="searchLoading"
                  @click="getDataList()">
                  查询
                </el-button>
                <el-button
                  icon="el-icon-refresh"
                  @click="resetSearch">
                  重置
                </el-button>
                <el-button v-if="!authSave" type="success" icon="el-icon-plus" @click="saveModal()">新增</el-button>
                <el-button v-if="!authDelete" type="danger" icon="el-icon-delete" @click="deleteModal()">删除</el-button>
                <el-button v-if="!authArchive" type="warning" icon="el-icon-folder" @click="archiveModal()">归档</el-button>
                <el-button type="primary" icon="el-icon-download" @click="exportExcel()">导出</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 展示列表 -->
    <el-table
      :height="height"
      :data="dataList"
      border
      v-loading="searchLoading"
      ref="inboundTable"
      :row-style="rowStyle"
      @row-click="inboundClickRow"
      @current-change="changeCurrentRow"
      @selection-change="selectionInbound"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        v-for="(item,index) in columnList" :key="index"
        :sortable="item.columnSortable"
        :prop="item.columnProp"
        :header-align="item.headerAlign"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :align="item.align"
        :fixed="item.fixed==''?false:item.fixed"
        :min-width="item.columnWidth"
        :label="item.columnLabel">
        <template slot-scope="scope">
          <span v-if="!item.columnHidden"> {{ scope.row[item.columnProp] }}</span>
          <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]" style="width: 100px; height: 80px"/></span>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="120"
        label="操作">
        <template slot-scope="scope">
          <template v-if="!authUpdate">
            <el-link v-if="scope.row.orderStatus === '草稿' || scope.row.orderStatus === '待检验' || scope.row.orderStatus === '编辑中' || scope.row.orderStatus === '待入库'" style="cursor: pointer" @click="updateModal(scope.row)">编辑</el-link>
          </template>
          <template v-if="!authClose">
            <el-link v-if="scope.row.orderStatus !== '草稿' && scope.row.orderStatus !== '已关闭'" style="cursor: pointer" @click="closeModal(scope.row)">关闭</el-link>
          </template>
          <template v-if="!authIssue">
            <el-link v-if="scope.row.orderStatus === '草稿' || scope.row.orderStatus === '编辑中'" style="cursor: pointer" @click="issueModal(scope.row)">下达</el-link>
          </template>
          <el-link v-if="(scope.row.orderStatus === '已关闭' || scope.row.orderStatus === '已完成')" style="cursor: pointer" @click="openModal(scope.row)">打开</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页栏 -->
    <el-pagination
      style="margin-top: 0px"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[20, 50, 100, 200, 500]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <!-- 收货入库通知新增/修改 -->
    <el-dialog title="收货入库通知" :close-on-click-modal="false" v-drag :visible.sync="modalFlag" width="545px">
      <el-form :inline="true" label-position="top" :model="modalData" :rules="rules" ref="modalForm" style="margin-left: 7px;margin-top: -5px;">
        <el-form-item label="BU" prop="bu">
          <el-select v-model="modalData.bu" placeholder="请选择" :disabled="modalDisableFlag" style="width: 100px">
            <el-option
              v-for = "i in userBuList"
              :key = "i.buNo"
              :label = "i.sitename"
              :value = "i.buNo">
              <span style="float: left;width: 60px">{{ i.sitename }}</span>
              <span style="float: right; color: #8492a6;white-space:nowrap;overflow:hidden;text-overflow:ellipsis; font-size: 11px;width: 70px">
                {{ i.buDesc }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单据类型" prop="orderType">
          <el-select v-model="modalData.orderType" placeholder="请选择" :disabled="modalDisableFlag" style="width: 100px">
            <el-option label="生产入库" value="生产入库"></el-option>
            <el-option label="其他入库" value="其他入库"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="要求入库日期" prop="requiredInboundDate">
          <el-date-picker
            style="width: 120px"
            v-model="modalData.requiredInboundDate"
            type="date"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="入库类别" prop="category">
          <el-select v-model="modalData.category" placeholder="请选择" style="width: 140px">
            <el-option
              v-for="item in categoryList"
              :key="item.crdcode"
              :label="item.crdcode + '-' + item.crdname"
              :value="item.crdcode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <span style="cursor: pointer" slot="label" @click="getBaseList(506)"><a href="#">供应商</a></span>
          <el-input v-model="modalData.supplierId" @change="supplierBlur(506)" style="width: 120px"></el-input>
          <el-input v-model="modalData.supplierName" disabled style="width: 223px"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="departmentNo">
          <el-select v-model="modalData.departmentNo" placeholder="请选择" style="width: 140px">
            <el-option
              v-for="item in departmentList"
              :key="item.departmentNo"
              :label="item.departmentNo + '-' + item.departmentDesc"
              :value="item.departmentNo">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="'备注'">
          <el-input type="textarea" v-model="modalData.remarks" :rows="3" resize='none' show-word-limit style="width: 505px;height: 20px"></el-input>
        </el-form-item>
      </el-form>
      <el-footer style="height:35px;margin-top: 55px;text-align:center">
        <el-button type="primary" :loading="saveLoading" @click="saveData()">保存</el-button>
        <el-button type="primary" @click="modalFlag = false">关闭</el-button>
      </el-footer>
    </el-dialog>

    <!-- 页签 -->
    <el-tabs v-model="activeTable" style="width: 100%" :style="{height: secondHeight + 'px'}" type="border-card" @tab-click="tabClick" class="customer-tab">
      <el-tab-pane label="入库明细" name="inboundDetail">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
          <el-form label-position="top" style="margin-left: 2px; margin-bottom: 0;">
            <el-button v-if="(currentRow.orderStatus === '草稿' || currentRow.orderStatus === '编辑中') && !hasActualInboundQty" type="primary" @click="addInboundDetailModal()" icon="el-icon-plus">新增</el-button>
            <el-button v-if="(currentRow.orderStatus === '草稿' || currentRow.orderStatus === '编辑中') && !hasActualInboundQty" type="primary" @click="deleteInboundDetail()" icon="el-icon-minus">删除</el-button>
            <el-button v-if="!editBatchVisible && (currentRow.orderStatus === '草稿' || currentRow.orderStatus === '编辑中') && !hasActualInboundQty" @click="editBatchModel">批量编辑</el-button>
            <el-button v-if="!editBatchVisible && (currentRow.orderStatus === '草稿' || currentRow.orderStatus === '编辑中')" @click="changeWarehouseBatch">更换仓库</el-button>
            <el-button v-if="editBatchVisible" @click="batchModel" :loading="saveLoading">批量保存</el-button>
            <el-button v-if="editBatchVisible" @click="editBatchVisible = false" type="info">取消编辑</el-button>
          </el-form>
          <div style="display: flex; align-items: center; font-size: 14px; color: #606266;">
            <span style="margin-right: 20px;">总张数：<span style="color: #409EFF; font-weight: bold;">{{ detailList.length }}</span></span>
            <span>总数量：<span style="color: #409EFF; font-weight: bold;">{{ detailTotalQty }}</span></span>
          </div>
        </div>
        <el-table
          :data="detailList"
          :height="secondHeight - 68"
          border
          @selection-change="selectionInboundDetail"
          style="width: 100%;">
          <el-table-column
            type="selection"
            header-align="center"
            align="center"
            width="50">
          </el-table-column>
          <el-table-column
            v-for="(item,index) in columnDetailList" :key="index"
            :sortable="item.columnSortable"
            :prop="item.columnProp"
            :header-align="item.headerAlign"
            :show-overflow-tooltip="item.showOverflowTooltip"
            :align="item.align"
            :fixed="item.fixed==''?false:item.fixed"
            :min-width="item.columnWidth"
            :label="item.columnLabel">
            <template slot-scope="scope">
              <span v-if="!item.columnHidden">{{scope.row[item.columnProp]}}</span>
              <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]" style="width: 100px; height: 80px"/></span>
            </template>
          </el-table-column>
          <el-table-column
            prop="requiredQty"
            header-align="center"
            align="right"
            min-width="100"
            label="要求入库数量">
            <template slot-scope="scope">
              <span v-if="editBatchVisible">
                <el-input :controls="false" v-model="scope.row.requiredQty"
                          @input="value => scope.row.requiredQty = value.match(/^(\d+\.?\d*|\.\d+)$/) ? value : ''"
                          style="height: 11px; width: 98%;">
                </el-input>
              </span>
              <span v-else>
                <span>{{scope.row[scope.column.property]}}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="inWarehouseName"
            header-align="center"
            align="center"
            min-width="180"
            label="入库仓库">
            <template slot-scope="scope">
              <span v-if="editBatchVisible">
                <el-button type="text" @click="chooseWareHouse(scope.row)" style="width:18%;padding: 3px 7px">选择</el-button>
                <el-input v-model="scope.row.inWarehouseName" readonly style="width:77%"></el-input>
              </span>
              <span v-else>
                <span>{{scope.row[scope.column.property]}}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="actualStockInQty"
            header-align="center"
            align="right"
            min-width="100"
            label="实际入库数量">
          </el-table-column>
          <el-table-column
            prop="remark"
            header-align="center"
            align="left"
            min-width="150"
            label="备注">
            <template slot-scope="scope">
              <span v-if="editBatchVisible">
                <el-input v-model="scope.row.remark" clearable style="width: 98%;"></el-input>
              </span>
              <span v-else>
                <span>{{scope.row[scope.column.property]}}</span>
              </span>
            </template>
          </el-table-column>
<!--          <el-table-column-->
<!--            prop="inBatchNo"-->
<!--            header-align="center"-->
<!--            align="left"-->
<!--            min-width="100"-->
<!--            label="入库批次号">-->
<!--            <template slot-scope="scope">-->
<!--              <span v-if="editBatchVisible">-->
<!--                <el-input :controls="false" v-model="scope.row.inBatchNo" style="height: 11px; width: 98%;"></el-input>-->
<!--              </span>-->
<!--              <span v-else>-->
<!--                <span>{{scope.row[scope.column.property]}}</span>-->
<!--              </span>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            width="150"
            label="操作">
            <template slot-scope="scope">
              <el-link style="cursor: pointer" @click="inboundDetailModal(scope.row)">入库明细</el-link>
              <el-link v-if="currentRow.orderStatus === '待入库'" style="cursor: pointer; margin-left: 10px;" type="warning" @click="labelImportModal(scope.row)">标签导入</el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 收获入库单明细新增 -->
    <el-dialog title="收货入库单明细" :close-on-click-modal="false" v-drag :visible.sync="detailModal" width="900px">
      <div style="font-size: 12px">
        <el-form :inline="true" label-position="top" :model="detailSearchData">
          <el-form-item :label="'物料编码'">
            <el-input v-model="detailSearchData.partNo" clearable style="width: 120px"></el-input>
          </el-form-item>
          <el-form-item :label="'物料名称'">
            <el-input v-model="detailSearchData.partDesc" clearable style="width: 120px"></el-input>
          </el-form-item>
          <el-form-item :label="'规格型号'">
            <el-input v-model="detailSearchData.spec" clearable style="width: 120px"></el-input>
          </el-form-item>
          <template v-if="detailSearchData.orderType === '生产入库'">
            <el-form-item :label="'生产订单'">
              <el-input v-model="detailSearchData.relatedOrderNo" clearable style="width: 120px"></el-input>
            </el-form-item>
            <el-form-item :label="'订单状态'">
              <el-select v-model="detailSearchData.status" clearable style="width: 100px">
                <el-option label="已计划" value="已计划"></el-option>
                <el-option label="已下达" value="已下达"></el-option>
                <el-option label="已排产" value="已排产"></el-option>
                <el-option label="已开工" value="已开工"></el-option>
                <el-option label="已取消" value="已取消"></el-option>
                <el-option label="已停工" value="已停工"></el-option>
                <el-option label="已关闭" value="已关闭"></el-option>
              </el-select>
            </el-form-item>
          </template>
          <el-form-item label=" ">
            <el-button type="primary" @click="searchTypeChange">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-container v-if="detailSearchData.orderType === '其他入库'">
        <el-header style="width: 880px;height: 200px;padding: 0 0 0 0">
          <span style="font-size: 12px" >可选物料</span>
          <el-table
            key="otherInboundTablePart1"
            height="200px"
            :data="partList1"
            border
            ref="partTable1Other"
            @selection-change="selectionPart1"
            highlight-current-row
            style="width: 100%">
            <el-table-column
              type="selection"
              header-align="center"
              align="center"
              width="50">
            </el-table-column>
            <el-table-column
              prop="partNo"
              header-align="center"
              align="left"
              min-width="120"
              label="物料编码">
            </el-table-column>
            <el-table-column
              prop="partDesc"
              header-align="center"
              align="left"
              min-width="200"
              label="物料名称">
            </el-table-column>
            <el-table-column
              prop="spec"
              header-align="center"
              align="left"
              min-width="120"
              label="规格型号">
            </el-table-column>
            <el-table-column
              prop="umName"
              header-align="center"
              align="center"
              min-width="100"
              label="物料单位">
            </el-table-column>
          </el-table>
          <!-- 分页-->
          <el-pagination
            style="margin-top: 5px"
            @size-change="sizeChangeHandle2"
            @current-change="currentChangeHandle2"
            :current-page="pageIndex2"
            :page-sizes="[20, 50, 100, 200, 500]"
            :page-size="pageSize2"
            :total="totalPage2"
            layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
        </el-header>
        <el-main style="width: 880px;height: 27px;margin-top: 70px;padding: 0 0 0 0;text-align:center">
          <div>
            <el-button type="primary" @click="addPart">添加>></el-button>
            <el-button type="primary" @click="deletePart">删除<<</el-button>
          </div>
        </el-main>
        <el-footer style="width: 880px;height: 200px;padding: 0 0 0 0;">
          <span style="font-size: 12px" >已选物料</span>
          <div class="rq">
            <el-table
              key="otherInboundTable"
              height="200px"
              :data="partList2"
              border
              ref="partTable2Other"
              @selection-change="selectionPart2"
              highlight-current-row
              style="width: 100%">
              <el-table-column
                type="selection"
                header-align="center"
                align="center"
                width="50">
              </el-table-column>
              <el-table-column
                prop="partNo"
                header-align="center"
                align="left"
                min-width="120"
                label="物料编码">
              </el-table-column>
              <el-table-column
                prop="partDesc"
                header-align="center"
                align="left"
                min-width="200"
                label="物料名称">
              </el-table-column>
              <el-table-column
                prop=""
                header-align="center"
                align="right"
                min-width="80"
                label="要求入库数量">
                <template slot-scope="scope">
                  <el-input
                    :controls="false"
                    v-model="scope.row.requiredQty"
                    @input="value => scope.row.requiredQty = value.match(/^(\d+\.?\d*|\.\d+)$/) ? value : ''"
                    style="height: 11px; width: 98%;">
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop=""
                header-align="center"
                align="left"
                min-width="100"
                label="关联单号">
                <template slot-scope="scope">
                  <el-input
                    :controls="false"
                    v-model="scope.row.relatedOrderNo"
                    style="height: 11px; width: 98%;">
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop=""
                header-align="center"
                align="left"
                min-width="100"
                label="关联单行号">
                <template slot-scope="scope">
                  <el-input
                    :controls="false"
                    v-model="scope.row.relatedOrderLineNo"
                    style="height: 11px; width: 98%;">
                  </el-input>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-footer>
      </el-container>

      <el-container v-else-if="detailSearchData.orderType === '生产入库'">
        <el-header style="width: 880px;height: 200px;padding: 0 0 0 0">
          <span style="font-size: 12px" >可选物料</span>
          <el-table
            key="productionInboundTablePart1"
            height="200px"
            :data="partList1"
            border
            ref="partTable1Production"
            @selection-change="selectionPart1"
            highlight-current-row
            style="width: 100%">
            <el-table-column
              type="selection"
              header-align="center"
              align="center"
              width="50">
            </el-table-column>
            <el-table-column
              prop="relatedOrderNo"
              header-align="center"
              align="left"
              min-width="120"
              label="生产订单">
            </el-table-column>
            <el-table-column
              prop="partNo"
              header-align="center"
              align="left"
              min-width="120"
              label="物料编码">
            </el-table-column>
            <el-table-column
              prop="partDesc"
              header-align="center"
              align="left"
              min-width="200"
              label="物料名称">
            </el-table-column>
            <el-table-column
              prop="spec"
              header-align="center"
              align="left"
              min-width="120"
              label="规格型号">
            </el-table-column>
            <el-table-column
              prop="umName"
              header-align="center"
              align="center"
              min-width="100"
              label="物料单位">
            </el-table-column>
            <el-table-column
              prop="orderQty"
              header-align="center"
              align="right"
              min-width="80"
              label="订单数量">
            </el-table-column>
            <el-table-column
              prop="requiredQty"
              header-align="center"
              align="right"
              min-width="80"
              label="可入库数">
            </el-table-column>
            <el-table-column
              prop="rollNo"
              header-align="center"
              align="left"
              min-width="120"
              label="卷号">
            </el-table-column>
            <el-table-column
              prop="packingList"
              header-align="center"
              align="left"
              min-width="150"
              show-overflow-tooltip
              label="Packing List">
            </el-table-column>
            <el-table-column
              prop="remark"
              header-align="center"
              align="left"
              min-width="150"
              show-overflow-tooltip
              label="备注">
            </el-table-column>
            <el-table-column
              prop="jobRemark"
              header-align="center"
              align="left"
              min-width="150"
              show-overflow-tooltip
              label="任务备注">
            </el-table-column>
          </el-table>
          <!-- 分页-->
          <el-pagination
            style="margin-top: 5px"
            @size-change="sizeChangeHandle2"
            @current-change="currentChangeHandle2"
            :current-page="pageIndex2"
            :page-sizes="[20, 50, 100, 200, 500]"
            :page-size="pageSize2"
            :total="totalPage2"
            layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
        </el-header>
        <el-main style="width: 880px;height: 27px;margin-top: 70px;padding: 0 0 0 0;text-align:center">
          <div>
            <el-button type="primary" @click="addPart">添加>></el-button>
            <el-button type="primary" @click="deletePart">删除<<</el-button>
          </div>
        </el-main>
        <el-footer style="width: 880px;height: 200px;padding: 0 0 0 0;">
          <span style="font-size: 12px" >已选物料</span>
          <div class="rq">
            <el-table
              key="productionInboundTable"
              height="200px"
              :data="partList2"
              border
              ref="partTable2Production"
              @selection-change="selectionPart2"
              highlight-current-row
              style="width: 100%">
              <el-table-column
                type="selection"
                header-align="center"
                align="center"
                width="50">
              </el-table-column>
              <el-table-column
                prop="relatedOrderNo"
                header-align="center"
                align="left"
                min-width="100"
                label="关联单号">
              </el-table-column>
              <el-table-column
                prop="relatedOrderLineNo"
                header-align="center"
                align="left"
                min-width="80"
                label="关联单行号">
              </el-table-column>
              <el-table-column
                prop="partNo"
                header-align="center"
                align="left"
                min-width="100"
                label="物料编码">
              </el-table-column>
              <el-table-column
                prop="partDesc"
                header-align="center"
                align="left"
                min-width="150"
                label="物料名称">
              </el-table-column>
              <el-table-column
                prop="rollNo"
                header-align="center"
                align="left"
                min-width="100"
                label="卷号">
              </el-table-column>
              <el-table-column
                prop=""
                header-align="center"
                align="center"
                min-width="100"
                label="要求入库数量">
                <template slot-scope="scope">
                  <el-input
                    :controls="false"
                    v-model="scope.row.requiredQty"
                    @input="value => scope.row.requiredQty = value.match(/^(\d+\.?\d*|\.\d+)$/) ? value : ''"
                    style="height: 11px; width: 98%;">
                  </el-input>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-footer>
      </el-container>
      <el-footer style="height:30px;margin-top: 35px;text-align:center">
        <el-button type="primary" :loading="saveLoading" @click="saveInboundDetail">保存</el-button>
        <el-button type="primary" @click="detailModal = false">关闭</el-button>
      </el-footer>
    </el-dialog>

    <!-- 入库明细 -->
    <el-dialog title="入库明细" :close-on-click-modal="false" v-drag :visible.sync="detailModal2" width="900px">
      <el-table
        height="400px"
        :data="detailList2"
        border
        style="width: 100%;">
        <el-table-column
          v-for="(item,index) in columnDetailList2" :key="index"
          :sortable="item.columnSortable"
          :prop="item.columnProp"
          :header-align="item.headerAlign"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :align="item.align"
          :fixed="item.fixed===''?false:item.fixed"
          :min-width="item.columnWidth"
          :label="item.columnLabel">
        </el-table-column>
      </el-table>
      <el-footer style="height:35px;margin-top: 15px;text-align:center">
        <el-button type="primary" @click="detailModal2 = false">关闭</el-button>
      </el-footer>
    </el-dialog>

    <Chooselist ref="baseList" @getBaseData="getBaseData"></Chooselist>

    <!-- 标签导入组件 -->
    <LabelImportUpload ref="labelImportUpload" @refreshPageTables="getInboundDetail"></LabelImportUpload>

  </div>
</template>

<script>
  import {
    searchInboundNotification, // 查询收获入库单
    saveInboundNotification, // 新增收获入库单
    updateInboundNotification, // 编辑收获入库单
    openInboundNotification, // 打开收获入库单
    deleteInboundNotification, // 删除收获入库单
    closeInboundNotification, // 关闭收获入库单
    issueInboundNotification, // 下达收获入库单
    getInboundDetail, // 查询收获入库单明细
    saveInboundDetail, // 新增收获入库单明细
    deleteInboundDetail, // 删除收获入库单明细
    getInboundPartList, // 查物料
    updateInboundDetail, // 批量编辑明细
    getInboundDetail2, // 获取入库明细
    getInboundCategoryList, // 查询入库类别列表
    getDepartmentList, // 查询部门列表
  } from "@/api/qc/Inbound_notification.js"
  import {
    getSiteAndBuByUserName,
  } from "@/api/qc/qc.js"
  import {getTableDefaultListLanguage, getTableUserListLanguage} from "@/api/table.js"
  import Chooselist from '@/views/modules/common/Chooselist_eam'
  import LabelImportUpload from './label_import_upload'
  import {userFavoriteList, saveUserFavorite, removeUserFavorite} from '@/api/userFavorite.js'
  import excel from "@/utils/excel-util.js"
  import {verifyData} from "@/api/chooselist/chooselist.js"
  export default {
    components: {
      Chooselist,
      LabelImportUpload,
    },
    data () {
      return {
        searchExpanded: true, // 搜索条件展开状态
        columnsProp:['createBy', 'updateBy'],
        // 是否收藏
        favorite: false,
        // 导出 start
        exportData: [],
        exportName: "收货入库" + this.dayjs().format('YYYYMMDDHHmmss'),
        exportHeader: ["收货入库"],
        exportFooter: [],
        exportList: [],
        // 导出 end
        tagNo: '',
        tagType: '',
        searchData: {
          site: '',
          userName: this.$store.state.user.name,
          orderNo: '',
          orderType: '',
          orderStatus: '',
          orderStatusList: ['草稿'],
          departmentNo: '', // 部门查询条件
          startDate: '',
          endDate: '',
          createdStartDate: '', // 创建时间开始
          createdEndDate: '', // 创建时间结束
          page: 1,
          limit: 10,
        },
        detailSearchData: {
          site: '',
          buNo: '',
          orderNo: '',
          partNo: '',
          partDesc: '',
          spec: '',
          partNos: '',
          orderType: '',
          relatedOrderNo: '',
          status: '',
          page: 1,
          limit: 10,
        },
        height: 200,
        secondHeight: 200,
        pageIndex: 1,
        pageSize: 20,
        totalPage: 0,
        pageIndex2: 1,
        pageSize2: 20,
        totalPage2: 0,
        modalFlag: false,
        modalDisableFlag: false,
        modalData: {
          site: '',
          bu: '',
          buNo: '',
          flag: '',
          orderNo: '',
          orderType: '',
          orderStatus: '',
          requiredInboundDate: '',
          supplierId: '',
          supplierName: '',
          remarks: '',
          createdBy: '',
          updatedBy: '',
          category: '', // 入库类别
        },
        categoryList: [], // 入库类别列表
        departmentList: [], // 部门列表
        dataList: [],
        detailList: [],
        userBuList: [],
        inboundSelection: [],
        inboundDetailSelection: [],
        partSelections1: [],
        partSelections2: [],
        partList1: [],
        partList2: [],
        dataListLoading: false,
        // 展示列集
        columnList: [
          {
            userId: this.$store.state.user.name,
            functionId: 610,
            serialNumber: '610Table1OrderNo',
            tableId: "610Table1",
            tableName: "收货入库任务表",
            columnProp: 'orderNo',
            headerAlign: "center",
            align: "center",
            columnLabel: '单据号',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 120,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 610,
            serialNumber: '610Table1OrderType',
            tableId: "610Table1",
            tableName: "收货入库任务表",
            columnProp: 'orderType',
            headerAlign: "center",
            align: "center",
            columnLabel: '单据类型',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 610,
            serialNumber: '610Table1OrderStatus',
            tableId: "610Table1",
            tableName: "收货入库任务表",
            columnProp: 'orderStatus',
            headerAlign: "center",
            align: "left",
            columnLabel: '单据状态',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 610,
            serialNumber: '610Table1SupplierId',
            tableId: "610Table1",
            tableName: "收货入库任务表",
            columnProp: 'supplierId',
            headerAlign: "center",
            align: "left",
            columnLabel: '供应商编码',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 120,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 610,
            serialNumber: '610Table1SupplierName',
            tableId: "610Table1",
            tableName: "收货入库任务表",
            columnProp: 'supplierName',
            headerAlign: "center",
            align: "left",
            columnLabel: '供应商名称',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 200,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 610,
            serialNumber: '610Table1RequiredInboundDate',
            tableId: "610Table1",
            tableName: "收货入库任务表",
            columnProp: 'requiredInboundDate',
            headerAlign: "center",
            align: "center",
            columnLabel: '要求入库日期',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 150,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 610,
            serialNumber: '610Table1Category',
            tableId: "610Table1",
            tableName: "收货入库任务表",
            columnProp: 'categoryName',
            headerAlign: "center",
            align: "center",
            columnLabel: '入库类别',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 610,
            serialNumber: '610Table1DepartmentName',
            tableId: "610Table1",
            tableName: "收货入库任务表",
            columnProp: 'departmentName',
            headerAlign: "center",
            align: "center",
            columnLabel: '部门',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 120,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 610,
            serialNumber: '610Table1CreatedDate',
            tableId: "610Table1",
            tableName: "收货入库任务表",
            columnProp: 'createdDate',
            headerAlign: "center",
            align: "center",
            columnLabel: '创建时间',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 170,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 610,
            serialNumber: '610Table1CreatedBy',
            tableId: "610Table1",
            tableName: "收货入库任务表",
            columnProp: 'createdBy',
            headerAlign: "center",
            align: "center",
            columnLabel: '创建人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 610,
            serialNumber: '610Table1UpdatedDate',
            tableId: "610Table1",
            tableName: "收货入库任务表",
            columnProp: 'updatedDate',
            headerAlign: "center",
            align: "center",
            columnLabel: '更新时间',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 170,
          },
          {
            userId: this.$store.state.user.name,
            functionId: 610,
            serialNumber: '610Table1UpdatedBy',
            tableId: "610Table1",
            tableName: "收货入库任务表",
            columnProp: 'updatedBy',
            headerAlign: "center",
            align: "center",
            columnLabel: '更新人',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
        ],
        columnDetailList: [
          {
            columnProp: 'relatedOrderNo',
            headerAlign: "center",
            align: "left",
            columnLabel: '关联单号',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            columnProp: 'relatedOrderLineNo',
            headerAlign: "center",
            align: "left",
            columnLabel: '关联单行号',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            columnProp: 'partNo',
            headerAlign: "center",
            align: "left",
            columnLabel: '物料编码',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 120,
          },
          {
            columnProp: 'partDesc',
            headerAlign: "center",
            align: "left",
            columnLabel: '物料名称',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 200,
          },
          {
            columnProp: 'rollNo',
            headerAlign: "center",
            align: "left",
            columnLabel: '卷号',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 120,
          },
          {
            columnProp: 'umName',
            headerAlign: "center",
            align: "center",
            columnLabel: '单位',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 80,
          },
        ],
        columnDetailList2: [
          {
            columnProp: 'subNo',
            headerAlign: "center",
            align: "left",
            columnLabel: '标签条码',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            columnProp: 'subQty',
            headerAlign: "center",
            align: "right",
            columnLabel: '入库数量',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            columnProp: 'orderRef4',
            headerAlign: "center",
            align: "left",
            columnLabel: '入库仓库',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 150,
          },
          {
            columnProp: 'orderRef5',
            headerAlign: "center",
            align: "left",
            columnLabel: '入库库位',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 150,
          },
          {
            columnProp: 'userName',
            headerAlign: "center",
            align: "left",
            columnLabel: '操作员',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 100,
          },
          {
            columnProp: 'transDate',
            headerAlign: "center",
            align: "center",
            columnLabel: '操作时间',
            columnHidden: false,
            columnImage: false,
            columnSortable: false,
            sortLv: 0,
            status: true,
            fixed: '',
            columnWidth: 170,
          },
        ],
        rules: {
          bu: [
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          orderType: [
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          requiredInboundDate: [
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          category: [
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ],
          departmentNo: [
            {
              required: true,
              message: ' ',
              trigger: ['blur','change']
            }
          ]
        },
        searchLoading: false,
        saveLoading: false,
        activeTable: 'inboundDetail',
        detailModal: false,
        authSearch: false,
        authSave: false,
        authUpdate: false,
        authDelete: false,
        authArchive: false,
        authClose: false,
        authIssue: false,
        editBatchVisible: false,
        menuId: this.$route.meta.menuId,
        tempWareHouseRow: {},
        isChangeWarehouseBatch: false, // 是否批量更换仓库
        detailList2: [],
        detailModal2: false,
        currentRow: {}
      }
    },

    computed: {
      // 计算明细列表要求入库数量总和
      detailTotalQty() {
        if (!this.detailList || this.detailList.length === 0) {
          return 0;
        }
        return this.detailList.reduce((sum, item) => {
          const qty = parseFloat(item.requiredQty) || 0;
          return sum + qty;
        }, 0);
      },
      // 判断是否有实际入库数量大于零的明细（有则禁止编辑）
      hasActualInboundQty() {
        if (!this.detailList || this.detailList.length === 0) {
          return false;
        }
        return this.detailList.some(item => {
          const qty = parseFloat(item.actualStockInQty) || 0;
          return qty > 0;
        });
      }
    },

    mounted () {
      this.$nextTick(() => {
        this.calculateTableHeight()
        // 监听窗口大小变化
        window.addEventListener('resize', this.calculateTableHeight)
      })
    },

    beforeDestroy() {
      // 移除窗口大小变化监听
      window.removeEventListener('resize', this.calculateTableHeight)
    },

    created () {
      // 按钮控制
      this.getButtonAuthData()
      // 获取用户的 site 和 bu
      this.getSiteAndBuByUserName()
      // 校验用户是否收藏
      this.favoriteIsOk()
      // 加载部门列表（用于查询条件）
      this.loadDepartmentList()
      // 动态列
      this.getTableUserColumn(this.$route.meta.menuId+'table1',1)
      this.getTableUserColumn(this.$route.meta.menuId+'table2',2)
      if (!this.authSearch) {
        // 获取数据列表
        this.getDataList()
      }
    },

    methods: {
      // 切换搜索条件展开/收起
      toggleSearchExpand() {
        this.searchExpanded = !this.searchExpanded
        this.$nextTick(() => {
          this.calculateTableHeight()
        })
      },

      // 计算表格高度
      calculateTableHeight() {
        // 展开时搜索区域高度约180px，收起时约80px
        const windowHeight = window.innerHeight;
        const headerHeight = this.searchExpanded ? 244 : 124;
        this.height = (windowHeight - headerHeight - 85) / 2 - 30;
        this.secondHeight = windowHeight - this.height - headerHeight - 120;
      },

      // 重置搜索条件
      resetSearch() {
        this.searchData = {
          site: '',
          userName: this.$store.state.user.name,
          orderNo: '',
          orderType: '',
          orderStatus: '',
          orderStatusList: ['草稿'],
          departmentNo: '',
          startDate: '',
          endDate: '',
          createdStartDate: '',
          createdEndDate: '',
          page: 1,
          limit: 10,
        }
        this.pageIndex = 1
      },

      // 获取用户的bu
      getSiteAndBuByUserName () {
        let tempData = {
          username: this.$store.state.user.name,
        }
        getSiteAndBuByUserName(tempData).then(({data}) => {
          if (data.code === 0) {
            this.userBuList = data.rows
          }
        })
      },

      // 获取数据列表
      getDataList () {
        this.searchData.limit = this.pageSize
        this.searchData.page = this.pageIndex
        this.searchData.orderStatus = this.searchData.orderStatusList.join(',')
        this.searchLoading = true
        searchInboundNotification(this.searchData).then(({data}) => {
          if (data.code === 0) {
            this.dataList = data.page.list
            this.pageIndex = data.page.currPage
            this.pageSize = data.page.pageSize
            this.totalPage = data.page.totalCount
            // 判断是否全部存在数据
            if (this.dataList.length > 0) {
              // 设置选中行
              this.$refs.inboundTable.setCurrentRow(this.dataList[0])
              this.inboundClickRow(this.dataList[0])
              this.refreshCurrentTabTable()
            } else {
              this.currentRow = {}
              this.refreshCurrentTabTable()
            }
          }
        }).finally(()=>{
          this.searchLoading = false
        })
      },

      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },

      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },

      // 子明细每页数
      sizeChangeHandle2 (val) {
        this.pageSize2 = val
        this.pageIndex2 = 1
        this.searchTypeChange()
      },

      // 子明细当前页
      currentChangeHandle2 (val) {
        this.pageIndex2 = val
        this.searchTypeChange()
      },

      saveModal () {
        this.modalData = {
          flag: '1',
          site: '',
          bu: this.userBuList[0].buNo,
          buNo: '',
          orderNo: '',
          orderType: '',
          orderStatus: '草稿',
          requiredInboundDate: this.dayjs().format('YYYY-MM-DD'), // 默认为当天
          supplierId: '',
          supplierName: '',
          remarks: '',
          createdBy: this.$store.state.user.name,
          category: '', // 入库类别
          departmentNo: '', // 部门
        }
        this.modalDisableFlag = false
        this.loadCategoryList() // 加载入库类别列表
        this.loadDepartmentList() // 加载部门列表
        this.modalFlag = true
        // 重置表单验证状态
        this.$nextTick(() => {
          if (this.$refs.modalForm) {
            this.$refs.modalForm.clearValidate()
          }
        })
      },

      updateModal (row) {
        // 先更新当前行数据,确保使用的是点击行的数据
        this.currentRow = JSON.parse(JSON.stringify(row))

        if (this.currentRow.orderType === '采购入库' || this.currentRow.orderType === '销售退货') {
          this.$message.warning('该类型单据不能编辑！')
          return
        }
        // 校验当前行的明细是否有实际入库数量大于零
        if (this.hasActualInboundQty) {
          this.$message.warning('该单据已有实际入库数量，不能编辑主信息！')
          return
        }
        this.modalData = {
          flag: '2',
          site: row.site,
          bu: row.site + '_' + row.buNo,
          buNo: row.buNo,
          orderNo: row.orderNo,
          orderType: row.orderType,
          requiredInboundDate: row.requiredInboundDate,
          supplierId: row.supplierId,
          supplierName: row.supplierName,
          remarks: row.remarks,
          updatedBy: this.$store.state.user.name,
          category: row.category || '', // 入库类别
          departmentNo: row.departmentNo || '', // 部门
        }
        this.modalDisableFlag = true
        this.loadCategoryList() // 加载入库类别列表
        this.loadDepartmentList() // 加载部门列表
        this.modalFlag = true
        // 重置表单验证状态
        this.$nextTick(() => {
          if (this.$refs.modalForm) {
            this.$refs.modalForm.clearValidate()
          }
        })
      },

      saveData () {
        // 使用表单验证
        this.$refs.modalForm.validate((valid) => {
          if (!valid) {
            this.$message.warning('请填写完整的必填项！')
            return false
          }

          this.saveLoading = true
          if (this.modalData.flag === '1') { // 新增
            saveInboundNotification(this.modalData).then(({data}) => {
              if (data && data.code === 0) {
                const newOrderNo = data.orderNo // 获取新创建的单据号
                this.modalFlag = false
                this.$message.success('操作成功')
                // 清空搜索条件，设置为新单据号以便精确查询
                this.searchData.orderNo = newOrderNo
                this.searchData.orderStatusList = [] // 清空状态筛选以确保能找到新单据
                // 刷新列表并定位到新单据
                this.searchData.limit = this.pageSize
                this.searchData.page = 1
                this.pageIndex = 1
                this.searchData.orderStatus = ''
                this.searchLoading = true
                searchInboundNotification(this.searchData).then(({data: listData}) => {
                  if (listData.code === 0) {
                    this.dataList = listData.page.list
                    this.pageIndex = listData.page.currPage
                    this.pageSize = listData.page.pageSize
                    this.totalPage = listData.page.totalCount
                    // 找到新创建的单据并定位
                    const foundRow = this.dataList.find(item => item.orderNo === newOrderNo)
                    if (foundRow) {
                      this.currentRow = JSON.parse(JSON.stringify(foundRow))
                      this.$nextTick(() => {
                        this.$refs.inboundTable.setCurrentRow(foundRow)
                        this.refreshCurrentTabTable()
                      })
                    } else if (this.dataList.length > 0) {
                      this.$refs.inboundTable.setCurrentRow(this.dataList[0])
                      this.inboundClickRow(this.dataList[0])
                    }
                  }
                  // 恢复搜索条件
                  this.searchData.orderNo = ''
                  this.searchData.orderStatusList = ['草稿']
                }).finally(() => {
                  this.searchLoading = false
                })
              } else {
                this.$message.error(data.msg)
              }
            }).finally(()=>{
              this.saveLoading = false
            })
          } else { // 修改
            updateInboundNotification(this.modalData).then(({data}) => {
              if (data && data.code === 0) {
                this.getDataList()
                this.modalFlag = false
                this.$message.success('操作成功')
              } else {
                this.$message.error(data.msg)
              }
            }).finally(()=>{
              this.saveLoading = false
            })
          }
        })
      },

      // 删除
      deleteModal () {
        if (this.inboundSelection.length === 0) {
          this.$message.warning('请勾选要删除的单据！')
          return
        }
        this.$confirm(`是否删除该 `+ this.inboundSelection.length +` 条记录?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let tempData = {
            submitList: this.inboundSelection
          }
          deleteInboundNotification(tempData).then(({data}) => {
            if (data && data.code === 0) {
              this.getDataList()
              this.inboundSelection = []
              this.$message.success('操作成功')
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },

      // 归档
      archiveModal () {

      },

      // 关闭
      closeModal (row) {
        // 先更新当前行数据
        this.currentRow = JSON.parse(JSON.stringify(row))

        // if (this.currentRow.orderType === '采购入库' || this.currentRow.orderType === '销售退货') {
        //   this.$message.warning('该类型单据不能编辑！')
        //   return
        // }
        closeInboundNotification(row).then(({data}) => {
          if (data && data.code === 0) {
            this.getDataList()
            this.$message.success('操作成功')
          } else {
            this.$message.error(data.msg)
          }
        })
      },

      // 下达
      issueModal (row) {
        // 先更新当前行数据
        this.currentRow = JSON.parse(JSON.stringify(row))

        if (this.currentRow.orderType === '采购入库' || this.currentRow.orderType === '销售退货') {
          this.$message.warning('该类型单据不能编辑！')
          return
        }
        // 校验明细是否有数据
        if (!this.detailList || this.detailList.length === 0) {
          this.$message.warning('入库明细不能为空，请先添加明细！')
          return
        }
        // 校验所有明细的仓库、关联单号、关联单行号必填
        for (let i = 0; i < this.detailList.length; i++) {
          const detail = this.detailList[i]
          if (!detail.inWarehouse) {
            this.$message.warning(`第${i + 1}行明细的入库仓库不能为空！`)
            return
          }
          if (!detail.relatedOrderNo) {
            this.$message.warning(`第${i + 1}行明细的关联单号不能为空！`)
            return
          }
          if (!detail.relatedOrderLineNo) {
            this.$message.warning(`第${i + 1}行明细的关联单行号不能为空！`)
            return
          }
        }
        issueInboundNotification(row).then(({data}) => {
          if (data && data.code === 0) {
            this.getDataList()
            this.$message.success('操作成功')
          } else {
            this.$message.error(data.msg)
          }
        })
      },

      // 打开
      openModal (row) {
        this.$confirm('确认打开?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let inData = {
            site: row.site,
            buNo: row.buNo,
            orderNo: row.orderNo
          }
          openInboundNotification(inData).then(({data}) => {
            if (data && data.code === 0) {
              this.getDataList()
              this.$message.success('操作成功')
            } else {
              this.$message.error(data.msg)
            }
          })
        });
      },

      // 列表表格选择替换
      tabClick (tab, event) {
        // 刷新列表数据
        this.refreshCurrentTabTable()
      },

      // 当前值发生变化的时候修改
      changeCurrentRow (row, oldRow) {
        // 判断是否是获取焦点的事件
        if (row) {
          this.currentRow = JSON.parse(JSON.stringify(row))
          //刷新当前页表
          this.refreshCurrentTabTable()
        }
      },

      // 复选
      selectionInbound (val) {
        this.inboundSelection = val
      },

      // 明细复选
      selectionInboundDetail (val) {
        this.inboundDetailSelection = val
      },

      rowStyle ({row}) {
        if (this.currentRow.orderNo === row.orderNo) {
          return { 'background-color': '#E8F7F6', cursor: 'pointer' }
        }
      },

      // 单机选中信息
      inboundClickRow (row,column) {
        this.currentRow = JSON.parse(JSON.stringify(row))
      },

      // 刷新页签的table数据
      refreshCurrentTabTable () {
        if (this.activeTable === 'inboundDetail') {
          this.getInboundDetail()
        }
      },

      // 查询物料缺陷跟踪
      getInboundDetail () {
        let templateData = {
          site: this.currentRow.site,
          buNo: this.currentRow.buNo,
          orderNo: this.currentRow.orderNo,
        }
        getInboundDetail(templateData).then(({data}) => {
          this.detailList = data.rows
        })
      },

      // 新增明细
      addInboundDetailModal () {
        if (this.currentRow.orderType === '采购入库' || this.currentRow.orderType === '销售退货') {
          this.$message.warning('该类型单据不能编辑！')
          return
        }
        this.detailSearchData = {
          site: this.currentRow.site,
          buNo: this.currentRow.buNo,
          orderNo: this.currentRow.orderNo,
          orderType: this.currentRow.orderType,
          relatedOrderNo: '',
          status: '',
          partNo: '',
          partDesc: '',
          spec: '',
          partNos: '',
          page: 1,
          limit: 10,
        }
        this.partSelections1 = []
        this.partSelections2 = []
        this.partList1 = []
        this.partList2 = []
        this.pageIndex2 = 1
        this.pageSize2 = 20
        this.totalPage2 = 0
        if (this.currentRow.orderType === '生产入库') {
          this.detailSearchData.status = ''
        }
        // 仅打开弹窗，不默认查询可选物料，等待用户手动点击“查询”
        this.detailModal = true
      },

      handleGetProjectPartList () {
        this.detailSearchData.limit = this.pageSize2
        this.detailSearchData.page = this.pageIndex2
        getInboundPartList(this.detailSearchData).then(({data}) => {
          if (data && data.code === 0){
            this.partList1 = data.page.list
            this.pageIndex2 = data.page.currPage
            this.pageSize2 = data.page.pageSize
            this.totalPage2 = data.page.totalCount
          }
        })
      },

      // 可选物料
      partClickRow1 (row) {
        const tableRef = this.detailSearchData.orderType === '其他入库'
          ? this.$refs.partTable1Other
          : this.$refs.partTable1Production
        if (tableRef) {
          tableRef.toggleRowSelection(row)
        }
      },

      // 已有物料
      partClickRow2 (row) {
        const tableRef = this.detailSearchData.orderType === '其他入库'
          ? this.$refs.partTable2Other
          : this.$refs.partTable2Production
        if (tableRef) {
          tableRef.toggleRowSelection(row)
        }
      },

      selectionPart1 (val) {
        this.partSelections1 = val
      },

      selectionPart2 (val) {
        this.partSelections2 = val
      },

      // 改变事件
      searchTypeChange () {
        // 生产入库按卷号排除，其他入库按物料编码排除
        if (this.detailSearchData.orderType === '生产入库') {
          let rollNos = this.partList2.map(part => part.rollNo)
          this.detailSearchData.partNos = rollNos.join(",")
        } else {
          let partNos = this.partList2.map(part => part.partNo)
          this.detailSearchData.partNos = partNos.join(",")
        }
        this.handleGetProjectPartList()
      },

      // 添加物料
      addPart () {
        if (this.partSelections1 == null || this.partSelections1.length === 0) {
          this.$message.warning('请选择可选物料！')
          return
        }
        this.partSelections1.forEach(item => {
          this.partList2.push(item)
        })
        this.searchTypeChange()
      },

      // 删除物料
      deletePart () {
        if(this.partSelections2 == null || this.partSelections2.length === 0) {
          this.$message.warning('请选择已选物料！')
          return
        }
        this.partSelections2.forEach(item => {
          // 生产入库按卷号删除，其他入库按物料编码删除
          if (this.detailSearchData.orderType === '生产入库') {
            this.partList2 = this.partList2.filter(part => part.rollNo !== item.rollNo)
          } else {
            this.partList2 = this.partList2.filter(part => part.partNo !== item.partNo)
          }
        })
        this.searchTypeChange()
      },

      // 新增明细
      saveInboundDetail () {
        // 校验已选物料列表不能为空
        if (!this.partList2 || this.partList2.length === 0) {
          this.$message.warning('请选择物料！')
          return
        }
        // 校验关联单号和关联单行号必填
        for (let i = 0; i < this.partList2.length; i++) {
          const part = this.partList2[i]
          if (!part.relatedOrderNo || part.relatedOrderNo.trim() === '') {
            this.$message.warning(`物料 ${part.partNo} 的关联单号不能为空！`)
            return
          }
          if (!part.relatedOrderLineNo || part.relatedOrderLineNo.toString().trim() === '') {
            this.$message.warning(`物料 ${part.partNo} 的关联单行号不能为空！`)
            return
          }
        }
        let tempData = {
          orderNo: this.detailSearchData.orderNo,
          createdBy: this.$store.state.user.name,
          partList: this.partList2,
        }
        this.saveLoading = true
        saveInboundDetail(tempData).then(({data}) => {
          if (data && data.code === 0) {
            this.getInboundDetail()
            this.detailModal = false
            this.$message.success('操作成功')
          } else {
            this.$message.error(data.msg)
          }
        }).finally(()=>{
          this.saveLoading = false
        })
      },

      // 删除入库明细
      deleteInboundDetail () {
        if (this.currentRow.orderType === '采购入库' || this.currentRow.orderType === '销售退货') {
          this.$message.warning('该类型单据不能编辑！')
          return
        }
        if (this.inboundDetailSelection.length === 0) {
          this.$message.warning('请勾选要删除的单据！')
          return
        }
        this.$confirm(`是否删除该 `+ this.inboundDetailSelection.length +` 条记录?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let tempData = {
            submitList: this.inboundDetailSelection
          }
          deleteInboundDetail(tempData).then(({data}) => {
            if (data && data.code === 0) {
              this.getInboundDetail()
              this.inboundDetailSelection = []
              this.$message.success('操作成功')
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },

      // 批量编辑模态框
      editBatchModel() {
        if (this.currentRow.orderType === '采购入库' || this.currentRow.orderType === '销售退货') {
          this.$message.warning('该类型单据不能编辑！')
          return
        }
        if (this.editBatchVisible) {
          this.editBatchVisible = false
        } else {
          this.editBatchVisible = true
        }
      },

      // 批量保存
      batchModel() {
        let params = []
        params = this.detailList
        this.saveLoading = true
        updateInboundDetail(params).then(({data}) => {
          if (data && data.code === 0) {
            this.getInboundDetail()
            this.$message.success(data.msg)
            this.editBatchVisible = false
          } else {
            this.$message.error(data.msg)
          }
        }).finally(() => {
          this.saveLoading = false
        })
      },

      // 入库明细
      inboundDetailModal (row) {
        let tempData = {
          ...row,
          orderType: this.currentRow.orderType
        }
        getInboundDetail2(tempData).then(({data}) => {
          if (data && data.code === 0) {
            this.detailList2 = data.rows
          } else {
            this.detailList2 = []
          }
        })
        this.detailModal2 = true
      },

      // 库位输入校验
      supplierBlur (tagNo) {
        let tempData = {
          tagno: tagNo,
          conditionSql: " and SupplierID = '" + this.modalData.supplierId + "'" + " and site = '" + this.modalData.site + "'"
        }
        verifyData(tempData).then(({data}) => {
          if (data && data.code === 0) {
            if (data.baseListData.length > 0) {
              this.modalData.supplierId = data.baseListData[0].SupplierID
              this.modalData.supplierName = data.baseListData[0].SupplierName
            } else {
              this.modalData.supplierName = ''
            }
          }
        })
      },

      chooseWareHouse (row) {
        this.isChangeWarehouseBatch = false
        this.tempWareHouseRow = row
        this.getBaseList(20)
      },

      // 批量更换仓库
      changeWarehouseBatch () {
        if (this.currentRow.orderType === '采购入库' || this.currentRow.orderType === '销售退货') {
          this.$message.warning('该类型单据不能编辑！')
          return
        }
        if (this.inboundDetailSelection.length === 0) {
          this.$message.warning('请先勾选需要更换仓库的明细行！')
          return
        }
        this.isChangeWarehouseBatch = true
        this.getBaseList(20)
      },

      // 获取基础数据列表S
      getBaseList (val, type) {
        this.tagNo = val
        this.tagType = type
        this.$nextTick(() => {
          let strVal = ''
          if (val === 506) {
            strVal = this.modalData.supplierId
            this.$refs.baseList.init(val, strVal)
          }
          if (val === 20) {
            strVal = this.tempWareHouseRow.inWarehouse
            this.$refs.baseList.init(val, strVal)
          }
        })
      },

      // 列表方法的回调
      getBaseData (val) {
        if (this.tagNo === 506) {
          this.modalData.supplierId = val.SupplierID
          this.modalData.supplierName = val.SupplierName
        }
        if (this.tagNo === 20) {
          if (this.isChangeWarehouseBatch) {
            // 批量更换仓库
            this.inboundDetailSelection.forEach(row => {
              row.inWarehouse = val.WareHouseID
              row.inWarehouseName = val.WareHouseName
            })
            // 批量保存更新
            this.saveLoading = true
            updateInboundDetail(this.detailList).then(({data}) => {
              if (data && data.code === 0) {
                this.getInboundDetail()
                this.$message.success('更换仓库成功')
              } else {
                this.$message.error(data.msg)
              }
            }).finally(() => {
              this.saveLoading = false
              this.isChangeWarehouseBatch = false
            })
          } else {
            // 单行编辑仓库
            this.tempWareHouseRow.inWarehouse = val.WareHouseID
            this.tempWareHouseRow.inWarehouseName = val.WareHouseName
          }
        }
      },

      // 校验用户是否收藏
      favoriteIsOk () {
        let userFavorite = {
          userId: this.$store.state.user.id,
          languageCode: this.$i18n.locale
        }
        userFavoriteList(userFavorite).then(({data}) => {
          for (let i = 0; i < data.list.length; i++) {
            if (this.$route.meta.menuId === data.list[i].menuId) {
              this.favorite = true
            }
          }
        })
      },

      // 收藏 OR 取消收藏
      favoriteFunction () {
        let userFavorite = {
          userId: this.$store.state.user.id,
          functionId: this.$route.meta.menuId,
        }
        if (this.favorite) {
          removeUserFavorite(userFavorite).then(({data}) => {
            this.$message.success(data.msg)
            this.favorite = false
          })
        } else {
          // 收藏
          saveUserFavorite(userFavorite).then(({data}) => {
            this.$message.success(data.msg)
            this.favorite = true
          })
        }
      },

      async exportExcel() {
        this.searchData.limit = -1
        this.searchData.page = 1
        excel.exportTable({
          url: "/inbound/searchInboundNotification",
          columnMapping: this.columnList, //可以直接用table，不需要的列就剔除
          mergeSetting: [],//需要合并的列
          params: this.searchData,
          fileName: this.exportName+".xlsx",
          rowFetcher: res => res.data,
          columnFormatter: [],
          dropColumns: [],
        })
      },

      // 动态列开始 获取 用户保存的 格式列
      async getTableUserColumn (tableId, columnId) {
        let queryTableUser = {
          userId: this.$store.state.user.name,
          functionId: this.$route.meta.menuId,
          tableId: tableId,
          status: true,
          languageCode: this.$i18n.locale
        }
        await getTableUserListLanguage(queryTableUser).then(({data}) => {
          if (data.rows.length > 0) {
            switch (columnId) {
              case 1:
                this.columnList = data.rows
                break;
            }
          } else {
            this.getColumnList(tableId, columnId)
          }
        })
      },

      // 获取 tableDefault 列
      async getColumnList (tableId, columnId) {
        let queryTable = {
          functionId: this.$route.meta.menuId,
          tableId: tableId,
          languageCode: this.$i18n.locale
        }
        await getTableDefaultListLanguage(queryTable).then(({data}) => {
          if (data.rows.length !== 0) {
            switch (columnId) {
              case 1:
                this.columnList = data.rows
                break;
            }
          }
        })
      },

      //获取按钮的权限数据
      getButtonAuthData () {
        let searchFlag = this.isAuth(this.menuId + ":search")
        let saveFlag = this.isAuth(this.menuId + ":save")
        let updateFlag = this.isAuth(this.menuId + ":update")
        let deleteFlag = this.isAuth(this.menuId + ":delete")
        let archiveFlag = this.isAuth(this.menuId + ":archive")
        let closeFlag = this.isAuth(this.menuId + ":close")
        let issueFlag = this.isAuth(this.menuId + ":issue")
        //处理页面的权限数据
        this.authSearch = !searchFlag
        this.authSave = !saveFlag
        this.authUpdate = !updateFlag
        this.authDelete = !deleteFlag
        this.authArchive = !archiveFlag
        this.authClose = !closeFlag
        this.authIssue = !issueFlag
      },

      // 加载入库类别列表
      loadCategoryList () {
        getInboundCategoryList({}).then(({data}) => {
          if (data && data.code === 0) {
            this.categoryList = (data.rows || []).sort((a, b) => (a.crdcode || '').localeCompare(b.crdcode || ''))
          }
        })
      },

      // 加载部门列表
      loadDepartmentList () {
        getDepartmentList({}).then(({data}) => {
          if (data && data.code === 0) {
            this.departmentList = data.rows || []
          }
        })
      },

      // 标签导入
      labelImportModal (row) {
        // 权限检查：与批量编辑按钮相同的权限控制
        // if (this.currentRow.orderStatus !== '草稿' && this.currentRow.orderStatus !== '编辑中') {
        //   this.$message.warning('只有草稿或编辑中状态的单据才能导入标签！')
        //   return
        // }
        // 准备传递给组件的数据
        let currentData = {
          site: this.currentRow.site,
          buNo: this.currentRow.buNo,
          orderNo: this.currentRow.orderNo,
          orderType: this.currentRow.orderType,
          orderStatus: this.currentRow.orderStatus,
          relatedOrderNo: row.relatedOrderNo,
          relatedOrderLineNo: row.relatedOrderLineNo,
          partNo: row.partNo
        }
        // 打开标签导入组件
        this.$nextTick(() => {
          this.$refs.labelImportUpload.init(currentData)
        })
      },
    }
  }
</script>
<style scoped>
/deep/ .customer-tab .el-tabs__content {
  padding: 5px !important;
}

.el-table /deep/ .cell{
  height: auto;
  line-height: 1.5;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 16px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.search-card /deep/ .el-card__header {
  padding: 5px 20px;
  background: linear-gradient(135deg, #9ac3d0 20%, #b6c7dd 80%);
  border-bottom: none;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  color: #fff;
}

.header-left i {
  font-size: 16px;
  margin-right: 8px;
}

.header-title {
  font-size: 14px;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.header-right {
  color: #fff;
}

.collapse-btn {
  color: #fff;
  font-weight: 500;
  transition: all 0.3s ease;
}

.collapse-btn:hover {
  color: #f0f0f0;
  transform: translateY(-1px);
}

.collapse-btn i {
  transition: transform 0.3s ease;
}

/* 搜索表单样式 */
.search-form {
  padding: 6px 0;
  min-height: 0;
}

/* 卡片主体样式 */
.search-card /deep/ .el-card__body {
  padding: 10px;
  transition: all 0.3s ease;
}

/* 收起时的样式 */
.search-card.collapsed /deep/ .el-card__body {
  padding: 10px 20px;
}

.search-form /deep/ .el-form-item {
  margin-bottom: 12px;
}

.search-form /deep/ .el-form-item__label {
  font-weight: 500;
  color: #606266;
  padding-bottom: 4px;
}

.search-form /deep/ .el-input__inner,
.search-form /deep/ .el-textarea__inner {
  border-radius: 6px;
  border: 1px solid #DCDFE6;
  transition: all 0.3s ease;
}

.search-form /deep/ .el-input__inner:focus,
.search-form /deep/ .el-textarea__inner:focus {
  border-color: #9ac3d0;
  box-shadow: 0 0 0 2px rgba(154, 195, 208, 0.1);
}

.search-form /deep/ .el-select {
  width: 100%;
}

/* 操作按钮区域 */
.search-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0 2px 0;
}

/* 展开时显示上边框 */
.search-card:not(.collapsed) .search-actions {
  border-top: 1px solid #f0f0f0;
  margin-top: 6px;
}

/* 收起时不显示上边框和上边距 */
.search-card.collapsed .search-actions {
  border-top: none;
  margin-top: 0;
  padding-top: 0;
}

.action-left {
  display: flex;
  gap: 8px;
  align-items: center;
}

.search-actions .el-button {
  border-radius: 4px;
  padding: 5px 10px;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.search-actions .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.search-actions .el-button--primary {
  background: #60aeff;
  border-color: #60aeff;
}

.search-actions .el-button--primary:hover {
  background: #7dbdff;
  border-color: #7dbdff;
}

.search-actions .el-button--success {
  background: #67C23A;
  border-color: #67C23A;
}

.search-actions .el-button--success:hover {
  background: #85ce61;
  border-color: #85ce61;
}

.search-actions .el-button--danger {
  background: #F56C6C;
  border-color: #F56C6C;
}

.search-actions .el-button--danger:hover {
  background: #f78989;
  border-color: #f78989;
}

.search-actions .el-button--warning {
  background: #E6A23C;
  border-color: #E6A23C;
}

.search-actions .el-button--warning:hover {
  background: #ebb563;
  border-color: #ebb563;
}

/* 表格样式 */
/deep/ .el-table th {
  background-color: #f5f7fa;
  color: #303133;
  font-weight: 600;
}

/deep/ .el-table tr:hover > td {
  background-color: #f5f7fa !important;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-actions {
    flex-direction: column;
    gap: 10px;
  }

  .action-left {
    width: 100%;
    justify-content: center;
  }
}
</style>
