<template>
  <div class="customer-css">
    <!-- 查询条件 -->
    <el-form :inline="true" label-position="top" class="search-form-inline">
      <div class="search-row">
        <el-form-item v-if="!isSupplierPageMode" class="search-item">
          <span style="cursor: pointer" slot="label" @click="getBaseList(520)"><a href="#">供应商编码</a></span>
          <el-input v-model="searchData.supplierNo" style="width: 120px" @keyup.enter.native="getMainData"/>
        </el-form-item>
        <el-form-item v-if="!isSupplierPageMode" label="供应商名称" class="search-item">
          <el-input v-model="searchData.supplierName" style="width: 250px" @keyup.enter.native="getMainData"/>
        </el-form-item>
        <el-form-item v-if="!isSupplierPageMode" class="search-item">
          <span style="cursor: pointer" slot="label" @click="getBaseList(530, 'mainPlanner')"><a href="#">Planner</a></span>
          <el-input v-model="searchData.planner" clearable style="width: 120px" @keyup.enter.native="getMainData"/>
        </el-form-item>
        <el-form-item label="申请日期" class="search-item">
          <div class="date-range">
            <el-date-picker v-model="searchData.requestDateStart" type="date" value-format="yyyy-MM-dd" placeholder="开始" style="width: 150px"/>
            <span class="split">-</span>
            <el-date-picker v-model="searchData.requestDateEnd" type="date" value-format="yyyy-MM-dd" placeholder="结束" style="width: 150px"/>
          </div>
        </el-form-item>
        <el-form-item label="状态" class="search-item">
          <el-select v-model="searchData.status" clearable placeholder="全部" style="width: 60%">
            <el-option label="全部" value="" />
            <el-option label="草稿" value="Draft" />
            <el-option label="待审核" value="Confirmed" />
            <el-option label="已下达" value="Audited" />
            <el-option label="已排程" value="Scheduled" />
            <el-option label="申请变更中" value="ChangeApplying" />
            <el-option label="验货中" value="Inspecting" />
            <el-option label="验货完成" value="InspectionCompleted" />

            <el-option label="已完成" value="Completed" />
            <el-option label="已取消" value="Cancelled" />
          </el-select>
        </el-form-item>

      </div>

      <div class="search-row">
        <el-form-item v-if="!isSupplierPageMode" class="search-item">
          <span style="cursor: pointer" slot="label" @click="getBaseList(2016, 'createBy')"><a href="#">申请人员</a></span>
          <el-input v-model="searchData.createBy" clearable style="width: 120px" @keyup.enter.native="getMainData"/>
        </el-form-item>
        <el-form-item v-if="!isSupplierPageMode" class="search-item">
          <span style="cursor: pointer" slot="label" @click="getBaseList(2016, 'qcOperator')"><a href="#">QC人员</a></span>
          <el-input v-model="searchData.qcOperator" clearable style="width: 120px" @keyup.enter.native="getMainData"/>
        </el-form-item>
        <el-form-item label="申请单号" class="search-item">
          <el-input v-model="searchData.requestNo" style="width: 120px" @keyup.enter.native="getMainData"/>
        </el-form-item>
        <el-form-item label="建议验货日期" class="search-item">
          <div class="date-range">
            <el-date-picker v-model="searchData.needInspectDateStart" type="date" value-format="yyyy-MM-dd" placeholder="开始" style="width: 150px"/>
            <span class="split">-</span>
            <el-date-picker v-model="searchData.needInspectDateEnd" type="date" value-format="yyyy-MM-dd" placeholder="结束" style="width: 150px"/>
          </div>
        </el-form-item>
        <el-form-item v-if="!isSupplierPageMode" label="计划验货日期" class="search-item">
          <div class="date-range">
            <el-date-picker v-model="searchData.planStartDate" type="date" value-format="yyyy-MM-dd" placeholder="开始" style="width: 150px"/>
            <span class="split">-</span>
            <el-date-picker v-model="searchData.planEndDate" type="date" value-format="yyyy-MM-dd" placeholder="结束" style="width: 150px"/>
          </div>
        </el-form-item>
        <el-form-item label=" " class="search-item search-btn-item">
          <el-button type="primary" @click="getMainData" style="">查询</el-button>
          <el-button type="primary" @click="addInspectionRequest" style="margin-left: 2px">新增</el-button>
          <el-button type="primary" @click="importExcel" style="margin-left: 2px">Excel导入</el-button>
          <el-button type="primary" @click="exportExcel" style="margin-left: 2px">导出</el-button>
        </el-form-item>
      </div>
    </el-form>

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

    <el-table
      :height="height"
      :data="mainDataList"
      border
      ref="mainTable"
      highlight-current-row
      @row-click="changeData"
      v-loading="dataListLoading"
      style="margin-top: 0px; width: 100%;">
      <el-table-column
        v-for="(item,index) in columnArray1" :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: 100px"/></span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="120" label="操作">
        <template slot-scope="scope">
          <a v-if="isRowStatus(scope.row, ['Draft'])"
             class="customer-a" @click="confirmInspection(scope.row)">确认</a>
          <a v-if="isRowStatus(scope.row, ['Draft', 'Confirmed'])"
             class="customer-a"
             :style="isRowStatus(scope.row, ['Draft']) ? 'margin-left: 3px;' : ''"
             @click="deleteInspectionRequest(scope.row)">删除</a>
          <a v-if="isRowStatus(scope.row, ['Draft'])"
             class="customer-a"
             :style="(isRowStatus(scope.row, ['Draft']) || isRowStatus(scope.row, ['Confirmed'])) ? 'margin-left: 3px;' : ''"
             @click="editInspectionRequest(scope.row)">编辑</a>
          <a v-if="isRowStatus(scope.row, ['Audited', 'Scheduled'])"
             class="customer-a"
             :style="(isRowStatus(scope.row, ['Draft']) || isRowStatus(scope.row, ['Confirmed'])) ? 'margin-left: 3px;' : ''"
             @click="applyChangeRequest(scope.row)">申请变更</a>
          <span v-if="!isRowStatus(scope.row, ['Draft', 'Confirmed', 'Audited', 'Scheduled'])"
                class="customer-a"
                style="color: #909399; cursor: default;">{{ scope.row.status }}</span>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="申请变更"
      :visible.sync="applyChangeDialogVisible"
      width="480px"
      v-drag
      append-to-body
      :close-on-click-modal="false">
      <el-form label-position="top">
        <el-form-item label="申请单号">
          <el-input v-model="applyChangeForm.requestNo" readonly />
        </el-form-item>
        <el-form-item label="变更备注">
          <el-input
            v-model="applyChangeForm.changeRemark"
            type="textarea"
            resize="none"
            :autosize="{ minRows: 3, maxRows: 3 }"
            placeholder="请填写变更备注" />
        </el-form-item>
      </el-form>

      <el-footer style="height:25px;margin-top: 45px;text-align:center">
        <el-button type="primary" :loading="applyChangeLoading" @click="submitApplyChangeRequest">保存</el-button>
        <el-button :disabled="applyChangeLoading" @click="applyChangeDialogVisible = false">取消</el-button>
      </el-footer>
    </el-dialog>

    <!-- 分页插件 -->
    <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-tabs v-model="activeTab" style="margin-top: 0px; width: 99%;" @tab-click="handleTabClick" class="customer-tab" type="border-card">
      <!-- 基本信息 -->
      <el-tab-pane label="基本信息" name="base">
        <div class="tab-pane-content" :style="tabPaneContentStyle">
          <inspection-request-detail ref="inspectionRequestDetail" :detail-data="currentRow" @update-success="getMainData"/>
        </div>
      </el-tab-pane>
      <!-- 验货明细 -->
      <el-tab-pane label="验货明细" name="detail">
        <div class="tab-pane-content" :style="tabPaneContentStyle">
          <inspection-request-detail-tab ref="inspectionDetailTab" :detail-data="currentRow" :table-height="tabTableHeight" />
        </div>
      </el-tab-pane>
      <!-- 验货关联PO明细 -->
      <el-tab-pane label="验货关联PO明细" name="poDetail">
        <div class="tab-pane-content" :style="tabPaneContentStyle">
          <inspection-request-po-detail-tab ref="poDetailTab" :detail-data="currentRow" :table-height="tabTableHeight" />
        </div>
      </el-tab-pane>
      <!-- 验货结果 -->
      <el-tab-pane label="验货结果" name="result">
        <div class="tab-pane-content" :style="tabPaneContentStyle">
          <inspection-result-tab ref="resultTab" :detail-data="currentRow" :table-height="tabTableHeight" />
        </div>
      </el-tab-pane>
      <!-- 费用明细（供应商专用页不展示） -->
      <el-tab-pane v-if="!isSupplierPageMode" label="费用明细" name="fee">
        <div class="tab-pane-content" :style="tabPaneContentStyle">
          <inspection-request-fee-tab ref="feeTab" :detail-data="currentRow" :table-height="tabTableHeight" />
        </div>
      </el-tab-pane>
      <!-- 附件管理（供应商专用页不展示） -->
      <el-tab-pane v-if="!isSupplierPageMode" label="附件管理" name="attachment">
        <div class="tab-pane-content" :style="tabPaneContentStyle">
          <inspection-request-attachment-tab ref="attachmentTab" :detail-data="currentRow" :table-height="tabTableHeight" />
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 新增弹窗 -->
    <el-dialog
      :title="isEditDialogMode ? '编辑验货申请' : '新增验货申请'"
      v-drag
      :visible.sync="addDialogVisible"
      width="1050px"
      top="5vh"
      :close-on-click-modal="false"
      @close="handleCloseAddDialog">

      <el-form :model="addFormData" :rules="addRules" ref="addFormData" label-width="90px" size="mini" class="add-dialog-form">
        <div class="form-section">
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="申请单号" prop="requestNo">
                <el-input v-model="addFormData.requestNo" :placeholder="isEditDialogMode ? '' : '自动生成'" disabled size="mini"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="申请日期" prop="requestDate">
                <el-date-picker
                  v-model="addFormData.requestDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  :disabled="isEditDialogMode"
                  size="mini"
                  style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label=" " >
                <div style="height: 28px;"></div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item prop="supplierNo"><span slot="label" :class="{ 'choose-label': !isEditDialogMode && !isSupplierPageMode }" @click="!isEditDialogMode && !isSupplierPageMode && openPoSupplierDialog()">供应商编码</span>
                <el-input
                  v-model="addFormData.supplierNo"
                  readonly
                  size="mini">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="供应商名称" prop="supplierName">
                <el-input v-model="addFormData.supplierName" disabled size="mini"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="  " >
                <el-button v-if="!isEditDialogMode && !isSupplierPageMode" type="primary" size="medium" style="margin-top:13px;" @click="openOrderSupplierDialog">从订单选择供应商</el-button>

              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="建议验货日期" prop="needInspectDate">
                <el-date-picker
                  v-model="addFormData.needInspectDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  size="mini"
                  style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="inspectAddress">
                <span slot="label" class="choose-label" @click="openAddressDialog">验货地址</span>
                <el-input
                  v-model="addFormData.inspectAddress"
                  readonly
                  @click.native="openAddressDialog"
                  placeholder="点击标签选择验货地址"
                  size="mini">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="城市简称">
                <el-input v-model="addFormData.inspectCityShort" readonly size="mini"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系人" prop="contact">
                <el-input v-model="addFormData.contact" placeholder="请输入联系人及电话" size="mini"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 步骤2：批量选择PO / 编辑态PO明细 -->
        <div class="po-section">
          <div class="section-title">{{ isEditDialogMode ? 'PO明细' : '批量选择PO' }}</div>

          <!-- PO号筛选和排序工具栏 -->
          <div v-if="!isEditDialogMode" class="po-toolbar">
            <el-form :inline="true" label-width="70px" size="mini" class="add-po-search-form">
              <el-form-item label="PO">
                <el-input
                  v-model="addPoFilter.orderNo"
                  clearable
                  style="width: 80px"
                  @keyup.enter.native="filterAddPoList"/>
              </el-form-item>
<!--              <el-form-item label="产品编码">-->
<!--                <el-input-->
<!--                  v-model="addPoFilter.partNo"-->
<!--                  clearable-->
<!--                  style="width: 80px"-->
<!--                  @keyup.enter.native="filterAddPoList"/>-->
<!--              </el-form-item>-->
<!--              <el-form-item label="Item">-->
<!--                <el-input-->
<!--                  v-model="addPoFilter.item"-->
<!--                  clearable-->
<!--                  style="width: 80px"-->
<!--                  @keyup.enter.native="filterAddPoList"/>-->
<!--              </el-form-item>-->
              <el-form-item label="SKU">
                <el-input
                  v-model="addPoFilter.sku"
                  clearable
                  style="width: 80px"
                  @keyup.enter.native="filterAddPoList"/>
              </el-form-item>
              <el-form-item label="物料名称">
                <el-input
                  v-model="addPoFilter.partDesc"
                  clearable
                  style="width: 80px"
                  @keyup.enter.native="filterAddPoList"/>
              </el-form-item>
              <el-form-item v-if="!isSupplierPageMode" label="供应商名称">
                <el-input
                  v-model="addPoFilter.supplierName"
                  clearable
                  style="width: 100px"
                  @keyup.enter.native="filterAddPoList"/>
              </el-form-item>
              <el-form-item v-if="!isSupplierPageMode">
                <span style="cursor: pointer" slot="label" @click="getBaseList(530, 'addPoPlanner')"><a href="#">Planner</a></span>
                <el-input
                  v-model="addPoFilter.planner"
                  clearable
                  style="width: 100px"
                  @input="handleAddPoPlannerInput"
                  @keyup.enter.native="filterAddPoList"
                />
              </el-form-item>
              <el-form-item label=" ">
                <el-button type="primary"  size="medium" style="margin-top:13px;" @click="filterAddPoList">查询</el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table
            v-if="!isEditDialogMode"
            key="create-po-table"
            ref="addPoTable"
            :data="filteredPoList"
            border
            size="small"
            table-layout="fixed"
            height="350px"
            style="width: 100%; margin-top: -10px;"
            @selection-change="handleSelectionChange">
            <el-table-column v-if="!isEditDialogMode" type="selection" width="30" align="center" fixed="left" />
            <el-table-column prop="orderRef1" label="PO号" header-align="center" align="center" width="120"/>
            <el-table-column prop="orderRef2" label="PO行号" header-align="center" align="center" width="60"/>
            <el-table-column prop="partNo" label="产品编码" header-align="center" align="left" min-width="120" show-overflow-tooltip/>
            <el-table-column prop="item" label="Item" header-align="center" align="left" min-width="100" show-overflow-tooltip/>
            <el-table-column prop="sku" label="SKU" header-align="center" align="left" min-width="120" show-overflow-tooltip/>
            <el-table-column prop="partDesc" label="物料名称" header-align="center" align="left" min-width="150" show-overflow-tooltip/>
            <el-table-column prop="planner" label="Planner" header-align="center" align="left" min-width="120" show-overflow-tooltip/>
            <el-table-column prop="qty" label="订单数量" header-align="center" align="right" width="80"/>
            <el-table-column prop="waitInspectQty" label="未验货数量" header-align="center" align="right" width="80"/>
            <el-table-column label="此次验货数量" header-align="center" align="center" width="150">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.inspectQty"
                  :min="0"
                  :max="scope.row.waitInspectQty || 999999"
                  size="mini"
                  :controls="false"
                  style="width: 100%; box-sizing: border-box;">
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="shipMethod" label="运输方式" header-align="center" align="center" width="100">
              <template slot-scope="scope">
                <el-select v-model="scope.row.shipMethod" placeholder="请选择" size="mini" style="width: 100%; box-sizing: border-box;">
                  <el-option label="空运" value="空运"></el-option>
                  <el-option label="海运" value="海运"></el-option>
                  <el-option label="陆运" value="陆运"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="crd"
              label="CRD日期"
              header-align="center"
              align="center"
              width="160"
              sortable
              :sort-method="(a, b) => sortCrdDate(a, b)">
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.crd"
                  type="date"
                  value-format="yyyy-MM-dd"
                  format="yyyy-MM-dd"
                  placeholder="选择日期"
                  size="mini"
                  style="width: 100%;"
                />
              </template>
            </el-table-column>
          </el-table>

          <el-table
            v-else
            key="edit-po-table"
            :data="editPoDetailList"
            border
            size="small"
            table-layout="fixed"
            height="350px"
            v-loading="editPoDetailLoading"
            style="width: 100%; margin-top: -10px;">
            <el-table-column prop="orderRef1" label="PO号" header-align="center" align="center" width="120"/>
            <el-table-column prop="orderRef2" label="PO行号" header-align="center" align="center" width="80"/>
            <el-table-column prop="partNo" label="产品编码" header-align="center" align="left" min-width="120" show-overflow-tooltip/>
            <el-table-column prop="item" label="Item" header-align="center" align="left" min-width="100" show-overflow-tooltip/>
            <el-table-column prop="sku" label="SKU" header-align="center" align="left" min-width="120" show-overflow-tooltip/>
            <el-table-column prop="partDesc" label="物料名称" header-align="center" align="left" min-width="150" show-overflow-tooltip/>
            <el-table-column prop="qty" label="验货数量" header-align="center" align="right" width="110"/>
            <el-table-column prop="shipMothod" label="运输方式" header-align="center" align="center" width="100"/>
            <el-table-column prop="crd" label="CRD日期" header-align="center" align="center" width="120"/>
          </el-table>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSaveAdd">保存</el-button>
        <el-button @click="handleCloseAddDialog">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="选择供应商"
      :visible.sync="poSupplierDialogVisible"
      width="760px"
      append-to-body
      :close-on-click-modal="false">
      <el-form :inline="true" label-width="80px" size="mini" class="po-supplier-search-form">
        <el-form-item label="供应商编码">
          <el-input
            v-model="poSupplierSearch.supplierNo"
            clearable
            style="width: 120px"
            @keyup.enter.native="searchPoSupplierList"/>
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input
            v-model="poSupplierSearch.supplierName"
            clearable
            style="width: 200px"
            @keyup.enter.native="searchPoSupplierList"/>
        </el-form-item>
        <el-form-item label=" ">
          <el-button type="primary" size="medium"  @click="searchPoSupplierList">查询</el-button>
          <el-button size="medium"  @click="resetPoSupplierSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        ref="poSupplierTable"
        :data="poSupplierList"
        border
        height="360px"
        v-loading="poSupplierLoading"
        highlight-current-row
        @current-change="onPoSupplierCurrentChange"
        @row-dblclick="onPoSupplierRowDblClick">
        <el-table-column prop="supplierNo" label="供应商编码" header-align="center" align="left" min-width="140" show-overflow-tooltip />
        <el-table-column prop="supplierName" label="供应商名称" header-align="center" align="left" min-width="220" show-overflow-tooltip />
        <el-table-column prop="poDetailCount" label="PO明细数" header-align="center" align="right" min-width="120" />
        <el-table-column prop="planner" label="Planner" header-align="center" align="left" min-width="120" show-overflow-tooltip />
      </el-table>

      <el-pagination
        style="margin-top: 10px; text-align: right"
        @size-change="onPoSupplierPageSizeChange"
        @current-change="onPoSupplierPageCurrentChange"
        :current-page="poSupplierPageIndex"
        :page-sizes="[20, 50, 100, 200]"
        :page-size="poSupplierPageSize"
        :total="poSupplierTotal"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmPoSupplierSelect">确认</el-button>
        <el-button @click="poSupplierDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="选择验货地址"
      :visible.sync="addressDialogVisible"
      width="980px"
      append-to-body
      :close-on-click-modal="false">
      <el-form :inline="true" label-width="80px" label-position="top" size="mini" class="po-supplier-search-form">
        <el-form-item label="供应商编码">
          <el-input v-model="addFormData.supplierNo" readonly style="width: 140px" />
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input v-model="addFormData.supplierName" readonly style="width: 220px" />
        </el-form-item>
        <el-form-item label=" ">
          <el-button
            type="primary"
            size="medium"
            style="margin-top: 0px"
            @click="openAddressCreateDialog">新增地址</el-button>
        </el-form-item>
<!--        <el-form-item label="地址关键词">-->
<!--          <el-input-->
<!--            v-model="addressSearch.keyword"-->
<!--            clearable-->
<!--            style="width: 260px"-->
<!--            @keyup.enter.native="searchAddressList" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label=" ">-->
<!--          <el-button type="primary" size="medium" @click="searchAddressList">查询</el-button>-->
<!--          <el-button size="medium" @click="resetAddressSearch">重置</el-button>-->
<!--        </el-form-item>-->
      </el-form>

      <el-table
        ref="addressTable"
        :data="addressList"
        border
        height="360px"
        v-loading="addressLoading"
        highlight-current-row
        @current-change="onAddressCurrentChange"
        @row-dblclick="onAddressRowDblClick">
        <el-table-column prop="addressId" label="地址ID" header-align="center" align="left" min-width="120" show-overflow-tooltip />
        <el-table-column prop="companyName" label="公司名称" header-align="center" align="left" min-width="180" show-overflow-tooltip />
        <el-table-column prop="cityShort" label="城市简称" header-align="center" align="left" min-width="120" show-overflow-tooltip />
        <el-table-column prop="address" label="验货地址" header-align="center" align="left" min-width="280" show-overflow-tooltip />
        <el-table-column prop="contact" label="联系人" header-align="center" align="left" min-width="120" show-overflow-tooltip />
        <el-table-column prop="phoneNo" label="联系电话" header-align="center" align="left" min-width="140" show-overflow-tooltip />
        <el-table-column prop="email" label="邮箱" header-align="center" align="left" min-width="180" show-overflow-tooltip />
      </el-table>

      <el-pagination
        style="margin-top: 10px; text-align: right"
        @size-change="onAddressPageSizeChange"
        @current-change="onAddressPageCurrentChange"
        :current-page="addressPageIndex"
        :page-sizes="[20, 50, 100, 200]"
        :page-size="addressPageSize"
        :total="addressTotal"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmAddressSelect">确认</el-button>
        <el-button @click="addressDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 新增供应商地址（与供应商主数据地址页签新增弹窗保持一致） -->
    <el-dialog
      title="供应商地址"
      :close-on-click-modal="false"
      v-drag
      :visible.sync="addressCreateDialogVisible"
      @closed="handleAddressCreateDialogClosed"
      width="600px"
      append-to-body>
      <el-form
        ref="addressCreateFormRef"
        :model="addressCreateForm"
        :rules="addressCreateRules"
        label-position="top"
        label-width="100px">
        <!-- 供应商ID / 城市简称 / 是否在用 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="供应商ID" prop="supplierId">
              <el-input v-model="addressCreateForm.supplierId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所在城市简称" prop="cityShort">
              <el-input v-model="addressCreateForm.cityShort" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否在用" prop="active">
              <el-select v-model="addressCreateForm.active" style="width: 100%">
                <el-option label="Y" value="Y" />
                <el-option label="N" value="N" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 公司名称 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="公司名称" prop="companyName">
              <el-input v-model="addressCreateForm.companyName" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 联系人 / 电话 / 地址类型 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="addressCreateForm.contact" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="phoneNo">
              <el-input v-model="addressCreateForm.phoneNo" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地址类型" prop="addressType">
              <sys-dict-select
                v-model="addressCreateForm.addressType"
                dict-type="address_type"
                placeholder="请选择地址类型"
                width="100%"
                filterable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 邮箱 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addressCreateForm.email" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 原产国 / 装运港 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="原产国" prop="originCountry">
              <el-input v-model="addressCreateForm.originCountry" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="portOfLoading">
              <span slot="label" style="cursor: pointer" @click="getBaseList(2018, 'addressPortOfLoading')"><a href="#">装运港</a></span>
              <el-input v-model="addressCreateForm.portOfLoading" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 地址 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="地址" prop="address">
              <el-input v-model="addressCreateForm.address" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="memo">
              <el-input v-model="addressCreateForm.memo" type="textarea" :rows="1" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer" style="margin-top: 10px; display: block">
        <el-button type="primary" :loading="addressCreateSaving" @click="saveCreatedAddress">保存</el-button>
        <el-button :disabled="addressCreateSaving" @click="addressCreateDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="从订单选择供应商"
      :visible.sync="orderSupplierDialogVisible"
      width="1260px"
      append-to-body
      :close-on-click-modal="false">
      <el-form :inline="true" label-position="top" class="search-form-inline">
        <el-form-item label="PO">
          <el-input
            v-model="orderSupplierSearch.orderNo"
            clearable
            style="width: 150px"
            @keyup.enter.native="searchOrderSupplierByPo"/>
        </el-form-item>
        <el-form-item label="产品编码">
          <el-input
            v-model="orderSupplierSearch.partNo"
            clearable
            style="width: 150px"
            @keyup.enter.native="searchOrderSupplierByPo"/>
        </el-form-item>
        <el-form-item label="Item">
          <el-input
            v-model="orderSupplierSearch.item"
            clearable
            style="width: 140px"
            @keyup.enter.native="searchOrderSupplierByPo"/>
        </el-form-item>
        <el-form-item label="SKU">
          <el-input
            v-model="orderSupplierSearch.sku"
            clearable
            style="width: 140px"
            @keyup.enter.native="searchOrderSupplierByPo"/>
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input
            v-model="orderSupplierSearch.partDesc"
            clearable
            style="width: 200px"
            @keyup.enter.native="searchOrderSupplierByPo"/>
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input
            v-model="orderSupplierSearch.supplierName"
            clearable
            style="width: 200px"
            @keyup.enter.native="searchOrderSupplierByPo"/>
        </el-form-item>
        <el-form-item>
          <span style="cursor: pointer" slot="label" @click="getBaseList(530, 'orderSupplierPlanner')"><a href="#">Planner</a></span>
          <el-input
            v-model="orderSupplierSearch.planner"
            clearable
            style="width: 140px"
            @keyup.enter.native="searchOrderSupplierByPo"
          />
        </el-form-item>
        <el-form-item label=" ">
          <el-button type="primary" @click="searchOrderSupplierByPo">查询</el-button>
          <el-button @click="resetOrderSupplierSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        ref="orderSupplierTable"
        :data="orderSupplierList"
        border
        height="430px"
        v-loading="orderSupplierLoading"
        highlight-current-row
        @current-change="onOrderSupplierCurrentChange"
        @row-dblclick="onOrderSupplierRowDblClick"
        :default-sort="{ prop: 'crd', order: 'descending' }">
        <el-table-column prop="supplierNo" label="供应商编码" header-align="center" align="left" min-width="120" fixed="left" show-overflow-tooltip />
        <el-table-column prop="supplierName" label="供应商名称" header-align="center" align="left" min-width="180" fixed="left" show-overflow-tooltip />
        <el-table-column prop="planner" label="Planner" header-align="center" align="left" min-width="120" show-overflow-tooltip />
        <el-table-column prop="orderRef1" label="PO号" header-align="center" align="center" min-width="120" show-overflow-tooltip />
        <el-table-column prop="orderRef2" label="PO行号" header-align="center" align="center" min-width="80" show-overflow-tooltip />
        <el-table-column prop="partNo" label="产品编码" header-align="center" align="left" min-width="140" show-overflow-tooltip />
        <el-table-column prop="item" label="Item" header-align="center" align="left" min-width="120" show-overflow-tooltip />
        <el-table-column prop="sku" label="SKU" header-align="center" align="left" min-width="140" show-overflow-tooltip />
        <el-table-column prop="partDesc" label="物料名称" header-align="center" align="left" min-width="170" show-overflow-tooltip />
        <el-table-column prop="waitInspectQty" label="未验货数量" header-align="center" align="right" min-width="100" />
        <el-table-column
          prop="crd"
          label="CRD日期"
          header-align="center"
          align="center"
          min-width="120"
          sortable
          :sort-method="(a, b) => sortCrdDate(a, b)" />
      </el-table>

      <el-pagination
        style="margin-top: 10px; text-align: right"
        @size-change="onOrderSupplierPageSizeChange"
        @current-change="onOrderSupplierPageCurrentChange"
        :current-page="orderSupplierPageIndex"
        :page-sizes="[20, 50, 100, 200]"
        :page-size="orderSupplierPageSize"
        :total="orderSupplierTotal"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmOrderSupplierSelect">确认</el-button>
        <el-button @click="orderSupplierDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 导入弹窗 -->
    <el-dialog title="验货申请数据导入" :visible.sync="uploadDialogVisible" width="800px">
      <!-- 选择文件 -->
      <div style="margin-bottom:15px;display:flex;align-items:center">
        <span style="margin-right:10px">请选择文件</span>
        <el-input v-model="uploadFileName" style="width:400px;margin-right:10px" readonly></el-input>
        <el-upload ref="upload" action="/api/inspection/upload"
                   :show-file-list="false" :on-change="handleFileChange"
                   :auto-upload="false">
          <el-button type="primary">选择文件</el-button>
        </el-upload>
        <el-button type="success" style="margin-left:10px" @click="previewUpload">上传</el-button>
        <el-button type="primary" @click="downloadTemplate" style="margin-left:10px">
          <i class="el-icon-download"></i> 下载模板
        </el-button>
      </div>
      <!-- 预览表格 -->
      <el-table
        :data="uploadPreviewList"
        border
        height="250"
        style="width:100%;margin-top:10px"
      >
        <el-table-column prop="poNo" label="PO号" align="center" width="auto"></el-table-column>
        <el-table-column prop="poItemNo" label="PO行号" align="center" width="auto"></el-table-column>
        <el-table-column prop="partNo" label="产品编码" align="center" width="auto"></el-table-column>
        <el-table-column prop="qty" label="验货数量" align="center" width="auto"></el-table-column>
        <el-table-column prop="shipMethod" label="运输方式" align="center" width="auto"></el-table-column>
        <el-table-column prop="crd" label="CRD" align="center" width="auto"></el-table-column>
        <el-table-column prop="suggestInspectDate" label="建议验货日期" align="center" width="auto"></el-table-column>
        <el-table-column prop="inspectAddress" label="验货地址" align="center" width="auto"></el-table-column>
        <el-table-column prop="inspectContract" label="联系人" align="center" width="auto"></el-table-column>
      </el-table>
      <!-- 按钮 -->
      <div style="margin-top:20px;text-align:center">
        <el-button type="primary" @click="confirmUpload">保存</el-button>
        <el-button @click="uploadDialogVisible=false" style="margin-right:30px">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { searchInspectionRequestHeaderList, queryPoPage, queryPoSupplierPage, queryPoSupplierOrderPage, saveInspectionRequest, deleteInspectionRequest, confirmInspectionRequest, applyChangeInspectionRequest, getInspectionRequestDetailSubList, updateInspectionRequest, downloadTemplate, previewUpload, batchSave } from '@/api/inspection/inspectionRequestHeader.js'
import { searchSrmSupplierAddressList, createSrmSupplierAddress, searchSrmSupplierList } from '@/api/srm/srmSupplier.js'
import Chooselist from '@/views/modules/common/Chooselist_eam'
import SysDictSelect from '@/components/dict/SysDictSelect.vue'
import ComInspectionRequestDetail from './com_inspectionRequestDetail.vue'
import ComInspectionRequestDetailTab from './com_inspectionRequestDetailTab.vue'
import ComInspectionRequestPoDetailTab from './com_inspectionRequestPoDetailTab.vue'
import ComInspectionResultTab from './com_inspectionResultTab.vue'
import ComInspectionRequestAttachmentTab from './com_inspectionRequestAttachmentTab.vue'
import ComInspectionRequestFeeTab from './com_inspectionRequestFeeTab.vue'
import { fetchSupplierDetail } from '@/utils/supplierChooselistHelper'
import excel from '@/utils/excel-util.js'

export default {
  props: {
    /**
     * 供应商专用模式开关
     * - false：通用验货申请页（默认，内部人员场景）
     * - true ：供应商专用页（由 inspectionRequestListSupplier.vue 传入）
     *
     * 打开后会触发：
     * 1) 查询条件精简；
     * 2) 查询强制按当前登录用户绑定供应商编码过滤；
     * 3) 新增时供应商固定为当前登录用户供应商；
     * 4) 隐藏从订单选择供应商入口及部分PO筛选项。
     */
    supplierMode: {
      type: Boolean,
      default: false
    }
  },
  components: {
    Chooselist,
    SysDictSelect,
    InspectionRequestDetail: ComInspectionRequestDetail,
    InspectionRequestDetailTab: ComInspectionRequestDetailTab,
    InspectionRequestPoDetailTab: ComInspectionRequestPoDetailTab,
    InspectionResultTab: ComInspectionResultTab,
    InspectionRequestAttachmentTab: ComInspectionRequestAttachmentTab,
    InspectionRequestFeeTab: ComInspectionRequestFeeTab
  },
  data () {
    return {
      functionId: this.$route.meta.menuId,
      height: 400,
      detailHeight: 400,
      currentRow: {},
      tagNo: '',
      searchType: '',
      // 供应商模式上下文：来自 /sys/user/info（user.supplierNo / user.supplierName）
      currentSupplierNo: '',
      currentSupplierName: '',
      activeTab: 'base',
      // 新增弹窗相关数据
      addDialogVisible: false,
      addDialogMode: 'create',
      addFormData: {
        requestNo: '',
        requestDate: '',
        supplierNo: '',
        supplierName: '',
        inspectAddressId: '',
        inspectAddress: '',
        inspectCityShort: '',
        contact: '',
        needInspectDate: ''
      },
      addRules: {
        requestDate: [
          { required: true, message: '请选择申请日期', trigger: 'change' }
        ],
        supplierNo: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        inspectAddress: [
          { required: true, message: '请选择验货地址', trigger: 'change' }
        ],
        needInspectDate: [
          { required: true, message: '请选择建议验货日期', trigger: 'change' }
        ]
      },
      poList: [],
      filteredPoList: [],
      editPoDetailList: [],
      editPoDetailLoading: false,
      addPoFilter: {
        orderNo: '',
        partNo: '',
        item: '',
        sku: '',
        partDesc: '',
        supplierName: '',
        planner: ''
      },
      addPoPlannerCodeFromChooser: '',
      addPoPlannerDisplayFromChooser: '',
      selectedPoList: [],
      poSupplierDialogVisible: false,
      poSupplierLoading: false,
      poSupplierList: [],
      poSupplierCurrentRow: null,
      poSupplierPageIndex: 1,
      poSupplierPageSize: 20,
      poSupplierTotal: 0,
      poSupplierSearch: {
        supplierNo: '',
        supplierName: ''
      },
      addressDialogVisible: false,
      addressLoading: false,
      addressList: [],
      addressCurrentRow: null,
      addressPageIndex: 1,
      addressPageSize: 20,
      addressTotal: 0,
      addressSearch: {
        keyword: ''
      },
      // 新增供应商地址弹窗（用于验货地址弹窗内快速维护地址）
      addressCreateDialogVisible: false,
      addressCreateSaving: false,
      addressCreateForm: {
        supplierId: '',
        site: this.$store.state.user.site || this.$store.state.user.currentSite || '',
        addressId: '',
        companyName: '',
        cityShort: '',
        contact: '',
        phoneNo: '',
        address: '',
        addressType: '验货地址',
        active: 'Y',
        email: '',
        originCountry: '',
        portOfLoading: '',
        memo: '',
        createBy: this.$store.state.user.name,
        updateBy: this.$store.state.user.name
      },
      addressCreateRules: {
        supplierId: [
          { required: true, validator: this.validateAddressCreateField, trigger: 'blur' }
        ],
        site: [
          { required: true, validator: this.validateAddressCreateField, trigger: 'blur' }
        ],
        cityShort: [
          { required: true, validator: this.validateAddressCreateField, message: ' ', trigger: 'blur' }
        ],
        address: [
          { required: true, validator: this.validateAddressCreateField, message: ' ', trigger: 'blur' }
        ],
        companyName: [
          { required: true, validator: this.validateAddressCreateField, message: ' ', trigger: 'blur' }
        ],
        contact: [
          { required: true, validator: this.validateAddressCreateField, message: ' ', trigger: 'blur' }
        ],
        phoneNo: [
          { required: true, validator: this.validateAddressCreateField, message: ' ', trigger: 'blur' }
        ],
        addressType: [
          { required: true, validator: this.validateAddressCreateField, message: ' ', trigger: 'change' }
        ]
      },
      applyChangeDialogVisible: false,
      applyChangeLoading: false,
      applyChangeForm: {
        requestNo: '',
        statusDb: '',
        changeRemark: ''
      },
      orderSupplierDialogVisible: false,
      orderSupplierLoading: false,
      orderSupplierList: [],
      orderSupplierCurrentRow: null,
      orderSupplierPageIndex: 1,
      orderSupplierPageSize: 50,
      orderSupplierTotal: 0,
      orderSupplierSearch: {
        orderNo: '',
        partNo: '',
        item: '',
        sku: '',
        partDesc: '',
        supplierName: '',
        planner: ''
      },
      pendingAutoSelectPoRow: null,
      // 上传相关
      uploadDialogVisible: false,
      uploadFileName: '',
      uploadFile: null,
      uploadPreviewList: [],
      searchData: {
        requestNo: '',
        supplierNo: '',
        supplierName: '',
        planner: '',
        status: '',
        qcOperator: '',
        createBy: '',
        requestDateStart: '',
        requestDateEnd: '',
        needInspectDateStart: '',
        needInspectDateEnd: '',
        planStartDate: '',
        planEndDate: '',
        planStartDateStr: '',
        planEndDateStr: '',
        page: 1,
        limit: 50
      },
      pageIndex: 1,
      pageSize: 50,
      totalPage: 0,
      mainDataList: [],
      dataListLoading: false,
      columnArray1: [
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'InspectionTable1RequestNo',
          tableId: 'InspectionTable1',
          tableName: '检验申请单',
          columnProp: 'requestNo',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '申请单号',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'InspectionTable1RequestDate',
          tableId: 'InspectionTable1',
          tableName: '检验申请单',
          columnProp: 'requestDate',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '申请日期',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'InspectionTable1PlanStartDate',
          tableId: 'InspectionTable1',
          tableName: '检验申请单',
          columnProp: 'planStartDate',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '计划验货日期',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'InspectionTable1SupplierNo',
          tableId: 'InspectionTable1',
          tableName: '检验申请单',
          columnProp: 'supplierNo',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '供应商编码',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'InspectionTable1SupplierName',
          tableId: 'InspectionTable1',
          tableName: '检验申请单',
          columnProp: 'supplierName',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '供应商名称',
          columnWidth: '150',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'InspectionTable1Planner',
          tableId: 'InspectionTable1',
          tableName: '检验申请单',
          columnProp: 'planner',
          headerAlign: 'center',
          align: 'left',
          columnLabel: 'Planner',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'InspectionTable1CreateBy',
          tableId: 'InspectionTable1',
          tableName: '检验申请单',
          columnProp: 'createBy',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '申请人员',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'InspectionTable1NeedInspectDate',
          tableId: 'InspectionTable1',
          tableName: '检验申请单',
          columnProp: 'needInspectDate',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '建议验货日期',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'InspectionTable1InspectAddress',
          tableId: 'InspectionTable1',
          tableName: '检验申请单',
          columnProp: 'inspectAddress',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '验货地址',
          columnWidth: '200',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'InspectionTable1InspectCityShort',
          tableId: 'InspectionTable1',
          tableName: '检验申请单',
          columnProp: 'inspectCityShort',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '城市简称',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'InspectionTable1Contact',
          tableId: 'InspectionTable1',
          tableName: '检验申请单',
          columnProp: 'inspectContract',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '联系人',
          columnWidth: '150',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'InspectionTable1Remark',
          tableId: 'InspectionTable1',
          tableName: '检验申请单',
          columnProp: 'remark',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '备注',
          columnWidth: '150',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'InspectionTable1Status',
          tableId: 'InspectionTable1',
          tableName: '检验申请单',
          columnProp: 'status',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '状态',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },

        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'InspectionTable1QcOperator',
          tableId: 'InspectionTable1',
          tableName: '检验申请单',
          columnProp: 'qcOperator',
          headerAlign: 'center',
          align: 'left',
          columnLabel: 'QC人员',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        }
      ]
    }
  },
  computed: {
    isEditDialogMode () {
      return this.addDialogMode === 'edit'
    },
    // 统一封装模式判断，避免模板与方法里反复写 this.supplierMode === true
    isSupplierPageMode () {
      return this.supplierMode === true
    },
    /**
     * 统一页签内容容器高度（单位：px）。
     * 业务意图：
     * - 验货申请各页签切换时保持同一视觉高度，避免忽高忽低导致页面跳动；
     * - 当窗口高度异常或未初始化时提供安全兜底，避免出现 0 高度导致内容不可见。
     */
    normalizedTabPaneHeight () {
      const rawHeight = Number(this.detailHeight)
      if (!rawHeight || rawHeight <= 0) {
        return 300
      }
      return Math.floor(rawHeight)
    },
    /**
     * 页签内容区内联样式（供所有 tab pane 复用）。
     * 关键输出：
     * - 固定高度：所有页签保持一致；
     * - 自动滚动：当单个页签内容超出时在页签内部滚动，不撑高外层布局。
     */
    tabPaneContentStyle () {
      return {
        height: `${this.normalizedTabPaneHeight}px`
      }
    },
    /**
     * 表格类页签统一高度（单位：px）。
     * 设计说明：
     * - 预留少量内边距，避免表格底部与容器边框贴边；
     * - 设置最小值，防止极端窗口尺寸下表格渲染异常。
     */
    tabTableHeight () {
      return Math.max(this.normalizedTabPaneHeight - 10, 120)
    }
  },
  mounted () {
    this.$nextTick(() => {
      // 统一计算主表格和详情页签的高度，确保一致
      const calculatedHeight = (window.innerHeight - 250) / 2
      this.height = calculatedHeight
      this.detailHeight = calculatedHeight
      this.initPageData()
    })
  },
  methods: {
    /**
     * 页面初始化入口：
     * - 通用模式：直接查询；
     * - 供应商模式：先加载当前用户供应商信息，再按供应商过滤查询。
     */
    async initPageData () {
      if (!this.isSupplierPageMode) {
        this.getMainData()
        return
      }
      const loaded = await this.loadCurrentUserSupplierContext()
      if (!loaded) {
        this.mainDataList = []
        this.changeData(null)
        return
      }
      this.pageIndex = 1
      this.getMainData()
    },
    /**
     * 读取当前登录用户绑定的供应商信息。
     * 数据来源：GET /sys/user/info
     * 结果用途：
     * - currentSupplierNo：查询强制过滤 + 新增固定回填
     * - currentSupplierName：新增供应商名称展示
     */
    async loadCurrentUserSupplierContext () {
      try {
        const { data } = await this.$http({
          url: this.$http.adornUrl('/sys/user/info'),
          method: 'get',
          params: this.$http.adornParams()
        })
        if (!data || data.code !== 0 || !data.user) {
          this.$message.error((data && data.msg) || '获取当前用户信息失败')
          return false
        }
        const supplierNo = String(data.user.supplierNo || '').trim()
        if (!supplierNo) {
          this.$message.warning('当前账号未维护供应商编码，请先在用户维护中配置')
          return false
        }
        this.currentSupplierNo = supplierNo
        this.currentSupplierName = String(data.user.supplierName || '').trim()
        if (!this.currentSupplierName) {
          const detail = await fetchSupplierDetail(supplierNo, this.$store.state.user.site)
          this.currentSupplierName = detail
            ? String(detail.supplierName || detail.supplier_name || '').trim()
            : ''
        }
        this.applyCurrentSupplierToSearchFilters()
        return true
      } catch (error) {
        console.error('获取当前用户供应商信息失败：', error)
        this.$message.error('获取当前用户供应商信息失败')
        return false
      }
    },
    /**
     * 将当前用户供应商写入查询条件。
     * 说明：supplierName 这里清空，避免名称模糊匹配干扰 supplierNo 精准过滤。
     */
    applyCurrentSupplierToSearchFilters () {
      if (!this.currentSupplierNo) {
        return false
      }
      this.searchData.supplierNo = this.currentSupplierNo
      this.searchData.supplierName = ''
      return true
    },
    /**
     * 将当前用户供应商写入新增表单（只读展示）。
     */
    applyCurrentSupplierToAddForm () {
      if (!this.currentSupplierNo) {
        return false
      }
      this.$set(this.addFormData, 'supplierNo', this.currentSupplierNo)
      this.$set(this.addFormData, 'supplierName', this.currentSupplierName || '')
      return true
    },
    // 统一状态判断，兼容中文和英文状态值 - rqrq
    isRowStatus (row, statusDbList) {
      if (!row || !Array.isArray(statusDbList) || statusDbList.length === 0) {
        return false
      }
      const rowStatusDb = row.statusDb ? String(row.statusDb).trim() : ''
      if (statusDbList.indexOf(rowStatusDb) !== -1) {
        return true
      }
      const statusLabelMap = {
        Draft: '草稿',
        Confirmed: '待审核',
        Audited: '已下达',
        Scheduled: '已排程',
        ChangeApplying: '申请变更中'
      }
      const rowStatusLabel = row.status ? String(row.status).trim() : ''
      return statusDbList.some(item => statusLabelMap[item] === rowStatusLabel)
    },
    resolveUserCode (val, tagNo) {
      if (!val) return ''
      if (tagNo === 2016) {
        // ChooseList 2016: username, user_display
        return val.username || ''
      }
      if (tagNo === 528 || tagNo === 529 || tagNo === 530) {
        // ChooseList 528/529/530: UserName, User_display
        return val.UserName || ''
      }
      return ''
    },
    resolveUserDisplay (val, tagNo) {
      if (!val) return ''
      if (tagNo === 2016) {
        return val.user_display || ''
      }
      if (tagNo === 528 || tagNo === 529 || tagNo === 530) {
        return val.User_display || ''
      }
      return ''
    },
    // 获取基础数据列表
    getBaseList (val, type) {
      this.tagNo = val
      this.searchType = type || ''
      this.$nextTick(() => {
        let strVal = ''
        let conSql = ''
        if (val === 520) {
          // 判断是搜索条件还是新增弹窗
          if (this.addDialogVisible) {
            strVal = this.addFormData.supplierNo || ''
          } else {
            strVal = this.searchData.supplierNo || ''
          }
          conSql = " and site = '" + this.$store.state.user.site + "'"
        }
        if (val === 530) {
          if (type === 'mainPlanner') {
            strVal = this.searchData.planner || ''
          } else if (type === 'addPoPlanner') {
            strVal = this.addPoFilter.planner || ''
          } else if (type === 'orderSupplierPlanner') {
            strVal = this.orderSupplierSearch.planner || ''
          }
          // 530 已在 ChooseList 中限定 PLANNER，这里仅做空值防御
          conSql = " and username <> '' "
        }
        if (val === 2016) {
          if (type === 'createBy') {
            strVal = this.searchData.createBy || ''
          } else if (type === 'qcOperator') {
            strVal = this.searchData.qcOperator || ''
          }

          // 防止 Druid 拦截 where 1=1
          conSql = " and username <> '' "
        }
        if (val === 2018) {
          if (type === 'addressPortOfLoading') {
            strVal = this.addressCreateForm.portOfLoading || ''
          }
          conSql = " and port_name <> '' "
        }
        this.$refs.baseList.init(val, strVal, conSql)
      })
    },

    /* 列表方法的回调 */
    getBaseData (val) {
      if (this.tagNo === 520) {
        // 判断是搜索条件还是新增弹窗
        if (this.addDialogVisible) {
          // 新增弹窗：SQL返回: supplier_no, supplier_name
          const supplierNoVal = val.supplier_no || ''
          const supplierNameVal = val.supplier_name || ''
          this.$set(this.addFormData, 'supplierNo', supplierNoVal)
          this.$set(this.addFormData, 'supplierName', supplierNameVal)
          this.$set(this.addFormData, 'inspectAddressId', '')
          this.$set(this.addFormData, 'inspectAddress', '')
          this.$set(this.addFormData, 'inspectCityShort', '')
          this.$set(this.addFormData, 'contact', '')
          console.log('供应商编码赋值:', supplierNoVal, '供应商名称赋值:', supplierNameVal)
          this.loadPoList()
          // 查询供应商地址获取验货地址和联系人
          if (supplierNoVal) {
            this.fetchSupplierAddress(supplierNoVal)
          }
        } else {
          // 搜索条件：SQL返回: supplier_no, supplier_name
          const supplierNoVal = val.supplier_no || ''
          this.searchData.supplierNo = supplierNoVal
          console.log('供应商编码赋值:', supplierNoVal)
        }
      }
      if (this.tagNo === 2016) {
        const userCode = this.resolveUserCode(val, 2016)
        if (this.searchType === 'createBy') {
          this.searchData.createBy = userCode
        } else if (this.searchType === 'qcOperator') {
          this.searchData.qcOperator = userCode
        }
      }
      if (this.tagNo === 530) {
        const plannerVal = this.resolveUserCode(val, 530)
        const plannerDisplay = this.resolveUserDisplay(val, 530) || plannerVal
        if (this.searchType === 'mainPlanner') {
          this.searchData.planner = plannerVal
        } else if (this.searchType === 'addPoPlanner') {
          this.addPoFilter.planner = plannerVal
          this.addPoPlannerCodeFromChooser = plannerVal
          this.addPoPlannerDisplayFromChooser = plannerDisplay
          this.filterAddPoList()
        } else if (this.searchType === 'orderSupplierPlanner') {
          this.orderSupplierSearch.planner = plannerVal
        }
      }
      if (this.tagNo === 2018) {
        if (this.searchType === 'addressPortOfLoading') {
          this.addressCreateForm.portOfLoading = val.port_name || val.code || ''
        }
      }
    },

    // 查询数据
    getMainData () {
      if (this.isSupplierPageMode) {
        if (!this.currentSupplierNo && !this.applyCurrentSupplierToSearchFilters()) {
          this.mainDataList = []
          this.totalPage = 0
          this.changeData(null)
          return
        }
        this.applyCurrentSupplierToSearchFilters()
      }
      this.searchData.limit = this.pageSize
      this.searchData.page = this.pageIndex
      // 后端查询字段使用 planStartDateStr/planEndDateStr - rqrq
      this.searchData.planStartDateStr = this.searchData.planStartDate || ''
      this.searchData.planEndDateStr = this.searchData.planEndDate || ''
      this.dataListLoading = true

      searchInspectionRequestHeaderList(this.searchData).then(({ data }) => {
        if (data.code === 0) {
          this.mainDataList = data.page.list

          // 调试信息：打印第一条数据的 hasModifiedQty 字段
          if (this.mainDataList.length > 0) {
            console.log('=== 主表格数据调试 ===')
            console.log('第一条数据:', this.mainDataList[0])
            console.log('hasModifiedQty 值:', this.mainDataList[0].hasModifiedQty)
            console.log('=====================')
          }

          this.pageIndex = data.page.currPage
          this.pageSize = data.page.pageSize
          this.totalPage = data.page.totalCount

          this.$nextTick(() => {
            if (this.$refs.mainTable) {
              this.$refs.mainTable.clearSelection()
            }
          })

          // 判断是否有数据
          if (this.mainDataList.length > 0) {
            this.$refs.mainTable.setCurrentRow(this.mainDataList[0])
            this.changeData(this.mainDataList[0])
          } else {
            this.changeData(null)
          }
        }
        this.dataListLoading = false
      }).catch(() => {
        this.dataListLoading = false
      })
    },

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

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

    // 页签点击事件
    handleTabClick (tab) {
      // 每次点击页签都触发对应页签的查询
      if (tab.name === 'detail') {
        // 验货明细页签 - 组件内部 watch 会自动触发
        this.$nextTick(() => {
          if (this.$refs.inspectionDetailTab) {
            this.$refs.inspectionDetailTab.loadDetailList()
          }
        })
      } else if (tab.name === 'poDetail') {
        // 验货关联PO明细页签
        this.$nextTick(() => {
          if (this.$refs.poDetailTab) {
            this.$refs.poDetailTab.loadDetailList()
          }
        })
      } else if (tab.name === 'result') {
        // 验货结果页签
        this.$nextTick(() => {
          if (this.$refs.resultTab) {
            this.$refs.resultTab.loadDetailList()
          }
        })
      } else if (tab.name === 'attachment') {
        // 附件管理页签 - 组件内部 watch 会自动触发
        this.$nextTick(() => {
          if (this.$refs.attachmentTab) {
            this.$refs.attachmentTab.loadAttachmentTypeList()
          }
        })
      } else if (tab.name === 'fee') {
        // 费用明细页签 - 组件内部 watch 会自动触发
        this.$nextTick(() => {
          if (this.$refs.feeTab) {
            this.$refs.feeTab.loadFeeDetailList()
          }
        })
      }
    },

    // 行点击事件
    changeData (row) {
      this.currentRow = row ? JSON.parse(JSON.stringify(row)) : {}
    },

    // 新增验货申请
    addInspectionRequest () {
      this.addDialogMode = 'create'
      this.resetAddForm()
      if (this.isSupplierPageMode) {
        if (!this.applyCurrentSupplierToAddForm()) {
          this.$message.warning('当前账号未维护供应商编码，请先在用户维护中配置')
          return
        }
        this.loadPoList()
        this.fetchSupplierAddress(this.addFormData.supplierNo)
      }
      this.addDialogVisible = true
    },

    // 关闭新增弹窗
    handleCloseAddDialog () {
      this.addDialogVisible = false
      this.resetAddForm()
      this.addDialogMode = 'create'
    },

    // 重置表单
    resetAddForm () {
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      const todayStr = `${year}-${month}-${day}`

      this.addFormData = {
        requestNo: '',
        requestDate: todayStr,
        supplierNo: '',
        supplierName: '',
        inspectAddressId: '',
        inspectAddress: '',
        inspectCityShort: '',
        contact: '',
        needInspectDate: ''
      }
      this.poList = []
      this.filteredPoList = []
      this.editPoDetailList = []
      this.editPoDetailLoading = false
      this.selectedPoList = []
      this.addPoFilter = {
        orderNo: '',
        partNo: '',
        item: '',
        sku: '',
        partDesc: '',
        supplierName: '',
        planner: ''
      }
      this.addPoPlannerCodeFromChooser = ''
      this.addPoPlannerDisplayFromChooser = ''
      this.poSupplierDialogVisible = false
      this.poSupplierLoading = false
      this.poSupplierList = []
      this.poSupplierCurrentRow = null
      this.poSupplierPageIndex = 1
      this.poSupplierPageSize = 20
      this.poSupplierTotal = 0
      this.poSupplierSearch = {
        supplierNo: '',
        supplierName: ''
      }
      this.addressDialogVisible = false
      this.addressLoading = false
      this.addressList = []
      this.addressCurrentRow = null
      this.addressPageIndex = 1
      this.addressPageSize = 20
      this.addressTotal = 0
      this.addressSearch = {
        keyword: ''
      }
      this.addressCreateDialogVisible = false
      this.addressCreateSaving = false
      this.addressCreateForm = this.buildAddressCreateFormBySupplier('')
      this.orderSupplierDialogVisible = false
      this.orderSupplierLoading = false
      this.orderSupplierList = []
      this.orderSupplierCurrentRow = null
      this.orderSupplierPageIndex = 1
      this.orderSupplierPageSize = 50
      this.orderSupplierTotal = 0
      this.orderSupplierSearch = {
        orderNo: '',
        partNo: '',
        item: '',
        sku: '',
        partDesc: '',
        supplierName: '',
        planner: ''
      }
      if (this.isSupplierPageMode) {
        this.applyCurrentSupplierToAddForm()
      }
      this.pendingAutoSelectPoRow = null
      if (this.$refs.addFormData) {
        this.$refs.addFormData.clearValidate()
      }
    },

    // 仅格式化到 yyyy-MM-dd，兼容 Date / 字符串 - rqrq
    formatToDateOnly (value) {
      if (!value) {
        return ''
      }
      if (value instanceof Date) {
        const year = value.getFullYear()
        const month = String(value.getMonth() + 1).padStart(2, '0')
        const day = String(value.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
      }
      const text = String(value).trim()
      return text ? text.split(' ')[0] : ''
    },

    // 打开草稿编辑弹窗：仅允许修改建议验货日期/验货地址/联系人 - rqrq
    async openEditInspectionDialog (row) {
      this.resetAddForm()
      this.addDialogMode = 'edit'
      this.addDialogVisible = true
      this.addFormData = {
        requestNo: row.requestNo || '',
        requestDate: this.formatToDateOnly(row.requestDate),
        supplierNo: row.supplierNo || '',
        supplierName: row.supplierName || '',
        inspectAddressId: row.inspectAddressId || '',
        inspectAddress: row.inspectAddress || '',
        inspectCityShort: row.inspectCityShort || '',
        contact: row.inspectContract || '',
        needInspectDate: this.formatToDateOnly(row.needInspectDate)
      }
      await this.loadEditPoDetailList(row.requestNo, row.site || this.$store.state.user.site)
    },

    // 加载编辑弹窗PO明细（只读展示）
    async loadEditPoDetailList (requestNo, site) {
      if (!requestNo) {
        this.editPoDetailList = []
        return
      }
      this.editPoDetailLoading = true
      try {
        const { data } = await getInspectionRequestDetailSubList({
          requestNo,
          site: site || this.$store.state.user.site,
          page: 1,
          limit: 1000
        })
        if (data && data.code === 0) {
          const rawList = (data.page && data.page.list) || []
          const exactList = rawList.filter(item => {
            const itemRequestNo = item.requestNo || item.request_no || ''
            return !itemRequestNo || String(itemRequestNo) === String(requestNo)
          })
          this.editPoDetailList = exactList.map(item => ({
            ...item,
            crd: this.formatToDateOnly(item.crd)
          }))
        } else {
          this.editPoDetailList = []
          this.$message.warning(data.msg || '加载PO明细失败')
        }
      } catch (error) {
        this.editPoDetailList = []
        console.error('加载编辑PO明细失败：', error)
        this.$message.error('加载PO明细失败，请稍后重试')
      } finally {
        this.editPoDetailLoading = false
      }
    },

    // 选择供应商
    selectSupplier () {
      this.tagNo = 520  // 设置tagNo，确保回调时能正确识别
      this.$nextTick(() => {
        const conSql = " and site = '" + this.$store.state.user.site + "'"
        this.$refs.baseList.init(520, this.addFormData.supplierNo || '', conSql)
      })
    },
    /**
     * 新增供应商地址弹窗字段校验（与供应商地址页签新增逻辑保持一致）。
     * 规则：必填字段不能为空字符串（仅空格也视为无效）。
     */
    validateAddressCreateField (rule, value, callback) {
      const normalizedValue = value === null || value === undefined ? '' : String(value).trim()
      if (!normalizedValue) {
        callback(new Error())
        return
      }
      callback()
    },
    /**
     * 构建“新增供应商地址”弹窗的默认表单对象。
     * supplierId 固定使用当前验货申请选中的供应商编码，避免录错供应商。
     */
    buildAddressCreateFormBySupplier (supplierId) {
      const currentSite = String(this.$store.state.user.site || this.$store.state.user.currentSite || '').trim()
      return {
        supplierId: supplierId || '',
        site: currentSite,
        addressId: '',
        companyName: '',
        cityShort: '',
        contact: '',
        phoneNo: '',
        address: '',
        addressType: '验货地址',
        active: 'Y',
        email: '',
        originCountry: '',
        portOfLoading: '',
        memo: '',
        createBy: this.$store.state.user.name,
        updateBy: this.$store.state.user.name
      }
    },
    /**
     * 在“选择验货地址”弹窗内快速新增供应商地址。
     * 界面字段与 /srmSupplier-supplierList 地址页签新增弹窗保持一致。
     */
    openAddressCreateDialog () {
      const supplierNo = (this.addFormData.supplierNo || '').trim()
      if (!supplierNo) {
        this.$message.warning('请先选择供应商')
        return
      }
      this.addressCreateForm = this.buildAddressCreateFormBySupplier(supplierNo)
      this.addressCreateDialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.addressCreateFormRef) {
          this.$refs.addressCreateFormRef.clearValidate()
        }
      })
      this.fetchSupplierInfoForAddressCreate(supplierNo)
    },
    /**
     * 根据供应商编码回填默认信息（公司名称/联系人/电话/邮箱/地址）。
     * 仅在新增地址弹窗中用于提高录入效率，不覆盖用户已输入内容。
     */
    fetchSupplierInfoForAddressCreate (supplierNo) {
      const normalizedSupplierNo = String(supplierNo || '').trim()
      const currentSite = String(this.$store.state.user.site || this.$store.state.user.currentSite || '').trim()
      if (!normalizedSupplierNo || !currentSite) {
        return
      }
      searchSrmSupplierList({
        site: currentSite,
        supplierNo: normalizedSupplierNo,
        page: 1,
        limit: 1
      }).then(({ data }) => {
        if (!(data && data.code === 0)) {
          return
        }
        const pageData = data.data || data.page
        const supplierList = pageData && pageData.list ? pageData.list : (Array.isArray(pageData) ? pageData : [])
        if (!supplierList || supplierList.length === 0) {
          return
        }
        const supplierData = supplierList[0] || {}
        this.addressCreateForm.companyName = supplierData.supplierName || supplierData.companyName || this.addressCreateForm.companyName || ''
        if (!this.addressCreateForm.contact) {
          this.addressCreateForm.contact = supplierData.contact || ''
        }
        if (!this.addressCreateForm.phoneNo) {
          this.addressCreateForm.phoneNo = supplierData.phoneNo || supplierData.phoneNo1 || ''
        }
        if (!this.addressCreateForm.email) {
          this.addressCreateForm.email = supplierData.email || supplierData.email1 || ''
        }
        if (!this.addressCreateForm.address) {
          this.addressCreateForm.address = supplierData.address || ''
        }
      }).catch((error) => {
        console.error('查询供应商信息失败:', error)
      })
    },
    /**
     * 保存新增供应商地址并刷新地址列表。
     * 保存成功后不关闭“选择验货地址”弹窗，便于用户立即选择新地址。
     */
    saveCreatedAddress () {
      if (!this.$refs.addressCreateFormRef) {
        return
      }
      this.$refs.addressCreateFormRef.validate((valid) => {
        if (!valid) {
          return
        }
        this.addressCreateSaving = true
        this.addressCreateForm.createBy = this.$store.state.user.name
        this.addressCreateForm.updateBy = this.$store.state.user.name
        createSrmSupplierAddress(this.addressCreateForm).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message.success('新增供应商地址成功')
            this.addressCreateDialogVisible = false
            this.loadAddressList()
          } else {
            this.$alert(data.msg || '新增供应商地址失败', '错误', { confirmButtonText: '确定' })
          }
        }).catch((error) => {
          console.error('保存供应商地址失败:', error)
          this.$message.error('保存失败: ' + (error.message || '网络错误'))
        }).finally(() => {
          this.addressCreateSaving = false
        })
      })
    },
    /**
     * 新增地址弹窗关闭后的收尾动作：
     * - 清理校验状态
     * - 重置为当前供应商默认表单，避免残留上次输入
     */
    handleAddressCreateDialogClosed () {
      if (this.$refs.addressCreateFormRef) {
        this.$refs.addressCreateFormRef.clearValidate()
      }
      this.addressCreateForm = this.buildAddressCreateFormBySupplier(this.addFormData.supplierNo || '')
      this.addressCreateSaving = false
    },

    // 打开验货地址选择弹窗（仅查询当前供应商的验货地址）
    openAddressDialog () {
      if (!this.addFormData.supplierNo) {
        this.$message.warning('请先选择供应商')
        return
      }
      this.addressDialogVisible = true
      this.addressPageIndex = 1
      this.addressSearch.keyword = ''
      this.addressCurrentRow = null
      this.addressCreateForm = this.buildAddressCreateFormBySupplier(this.addFormData.supplierNo || '')
      this.loadAddressList()
    },

    // 标准化地址列表字段，兼容下划线和驼峰返回
    normalizeAddressRows (list) {
      return (list || []).map(item => ({
        ...item,
        supplierId: item.supplierId || item.supplier_id || '',
        addressId: item.addressId || item.address_id || '',
        cityShort: item.cityShort || item.city_short || '',
        companyName: item.companyName || item.company_name || '',
        contact: item.contact || '',
        phoneNo: item.phoneNo || item.phone_no || '',
        email: item.email || '',
        address: item.address || '',
        addressType: item.addressType || item.address_type || ''
      }))
    },

    // 根据供应商加载验货地址列表
    loadAddressList () {
      if (!this.addFormData.supplierNo) {
        this.addressList = []
        this.addressTotal = 0
        return
      }
      const params = {
        site: this.$store.state.user.site,
        supplierId: this.addFormData.supplierNo,
        addressType: '验货地址',
        page: this.addressPageIndex,
        limit: this.addressPageSize
      }
      if (this.addressSearch.keyword) {
        params.address = this.addressSearch.keyword
      }
      this.addressLoading = true
      searchSrmSupplierAddressList(params).then(({ data }) => {
        if (data && data.code === 0) {
          const pageData = data.page || data.data || {}
          const rawList = Array.isArray(pageData.list) ? pageData.list : (Array.isArray(pageData) ? pageData : [])
          this.addressList = this.normalizeAddressRows(rawList)
          this.addressTotal = pageData.totalCount || this.addressList.length
          this.addressPageIndex = pageData.currPage || this.addressPageIndex
          this.addressPageSize = pageData.pageSize || this.addressPageSize
          this.$nextTick(() => {
            if (this.addressList.length > 0) {
              this.addressCurrentRow = this.addressList[0]
              if (this.$refs.addressTable) {
                this.$refs.addressTable.setCurrentRow(this.addressCurrentRow)
              }
            } else {
              this.addressCurrentRow = null
              if (this.$refs.addressTable) {
                this.$refs.addressTable.setCurrentRow()
              }
            }
          })
        } else {
          this.addressList = []
          this.addressCurrentRow = null
          this.addressTotal = 0
        }
      }).catch(error => {
        this.addressList = []
        this.addressCurrentRow = null
        this.addressTotal = 0
        console.error('查询供应商地址失败:', error)
        this.$message.error('查询验货地址失败')
      }).finally(() => {
        this.addressLoading = false
      })
    },

    searchAddressList () {
      this.addressPageIndex = 1
      this.loadAddressList()
    },

    resetAddressSearch () {
      this.addressSearch.keyword = ''
      this.addressPageIndex = 1
      this.loadAddressList()
    },

    onAddressPageSizeChange (val) {
      this.addressPageSize = val
      this.addressPageIndex = 1
      this.loadAddressList()
    },

    onAddressPageCurrentChange (val) {
      this.addressPageIndex = val
      this.loadAddressList()
    },

    onAddressCurrentChange (row) {
      this.addressCurrentRow = row || null
    },

    onAddressRowDblClick (row) {
      this.selectAddressRow(row)
    },

    confirmAddressSelect () {
      this.selectAddressRow(this.addressCurrentRow)
    },

    selectAddressRow (row, overwriteContact = true) {
      if (!row || !row.addressId) {
        this.$message.warning('请选择验货地址')
        return
      }
      this.$set(this.addFormData, 'inspectAddressId', row.addressId || '')
      this.$set(this.addFormData, 'inspectAddress', row.address || '')
      this.$set(this.addFormData, 'inspectCityShort', row.cityShort || '')
      if (overwriteContact || !this.addFormData.contact) {
        this.$set(this.addFormData, 'contact', row.contact || '')
      }
      this.addressDialogVisible = false
    },

    // 根据供应商ID预带默认验货地址（若存在）
    fetchSupplierAddress (supplierId) {
      if (!supplierId) {
        return
      }
      const params = {
        site: this.$store.state.user.site,
        supplierId: supplierId,
        addressType: '验货地址',
        page: 1,
        limit: 1
      }

      searchSrmSupplierAddressList(params).then(({ data }) => {
        if (data && data.code === 0) {
          const pageData = data.page || data.data || {}
          const rawList = Array.isArray(pageData.list) ? pageData.list : (Array.isArray(pageData) ? pageData : [])
          const addressList = this.normalizeAddressRows(rawList)
          if (addressList.length > 0) {
            this.selectAddressRow(addressList[0], true)
          } else {
            this.$set(this.addFormData, 'inspectAddressId', '')
            this.$set(this.addFormData, 'inspectAddress', '')
            this.$set(this.addFormData, 'inspectCityShort', '')
            this.$set(this.addFormData, 'contact', '')
          }
        }
      }).catch(error => {
        console.error('查询供应商地址失败:', error)
      })
    },

    // 打开新增弹窗专用供应商查询
    openPoSupplierDialog () {
      if (this.isSupplierPageMode) {
        return
      }
      this.poSupplierDialogVisible = true
      this.poSupplierPageIndex = 1
      this.poSupplierCurrentRow = null
      this.poSupplierSearch.supplierNo = this.addFormData.supplierNo || ''
      this.poSupplierSearch.supplierName = ''
      this.loadPoSupplierList()
    },

    // 查询新增弹窗专用供应商列表
    loadPoSupplierList () {
      const params = {
        site: this.$store.state.user.site,
        supplierNo: this.poSupplierSearch.supplierNo || '',
        supplierName: this.poSupplierSearch.supplierName || '',
        page: this.poSupplierPageIndex,
        limit: this.poSupplierPageSize
      }
      this.poSupplierLoading = true
      queryPoSupplierPage(params).then(({ data }) => {
        if (data.code === 0 && data.page) {
          this.poSupplierList = (data.page.list || []).map(item => ({
            ...item,
            supplierNo: item.supplierNo || item.supplier_no || '',
            supplierName: item.supplierName || item.supplier_name || '',
            planner: item.planner || ''
          }))
          this.poSupplierTotal = data.page.totalCount || 0
          this.poSupplierPageIndex = data.page.currPage || this.poSupplierPageIndex
          this.poSupplierPageSize = data.page.pageSize || this.poSupplierPageSize
          this.$nextTick(() => {
            if (this.poSupplierList.length > 0) {
              this.poSupplierCurrentRow = this.poSupplierList[0]
              if (this.$refs.poSupplierTable) {
                this.$refs.poSupplierTable.setCurrentRow(this.poSupplierCurrentRow)
              }
            } else {
              this.poSupplierCurrentRow = null
              if (this.$refs.poSupplierTable) {
                this.$refs.poSupplierTable.setCurrentRow()
              }
            }
          })
        } else {
          this.poSupplierList = []
          this.poSupplierTotal = 0
          this.poSupplierCurrentRow = null
        }
      }).catch(() => {
        this.poSupplierList = []
        this.poSupplierTotal = 0
        this.poSupplierCurrentRow = null
        this.$message.error('加载供应商列表失败')
      }).finally(() => {
        this.poSupplierLoading = false
      })
    },

    // 供应商弹框查询
    searchPoSupplierList () {
      this.poSupplierPageIndex = 1
      this.loadPoSupplierList()
    },

    // 供应商弹框重置查询
    resetPoSupplierSearch () {
      this.poSupplierSearch.supplierNo = ''
      this.poSupplierSearch.supplierName = ''
      this.poSupplierPageIndex = 1
      this.loadPoSupplierList()
    },

    // 供应商弹框页大小变化
    onPoSupplierPageSizeChange (val) {
      this.poSupplierPageSize = val
      this.poSupplierPageIndex = 1
      this.loadPoSupplierList()
    },

    // 供应商弹框页码变化
    onPoSupplierPageCurrentChange (val) {
      this.poSupplierPageIndex = val
      this.loadPoSupplierList()
    },

    // 供应商弹框选中行变化
    onPoSupplierCurrentChange (row) {
      this.poSupplierCurrentRow = row || null
    },

    // 供应商弹框双击选择
    onPoSupplierRowDblClick (row) {
      this.selectPoSupplier(row)
    },

    // 供应商弹框点击确认
    confirmPoSupplierSelect () {
      this.selectPoSupplier(this.poSupplierCurrentRow)
    },

    // 回填供应商并刷新PO明细
    selectPoSupplier (row) {
      if (!row || !row.supplierNo) {
        this.$message.warning('请选择供应商')
        return
      }
      const supplierNoVal = row.supplierNo || ''
      const supplierNameVal = row.supplierName || ''
      this.$set(this.addFormData, 'supplierNo', supplierNoVal)
      this.$set(this.addFormData, 'supplierName', supplierNameVal)
      this.$set(this.addFormData, 'inspectAddressId', '')
      this.$set(this.addFormData, 'inspectAddress', '')
      this.$set(this.addFormData, 'inspectCityShort', '')
      this.$set(this.addFormData, 'contact', '')
      this.addPoFilter = {
        orderNo: '',
        partNo: '',
        item: '',
        sku: '',
        partDesc: '',
        supplierName: '',
        planner: ''
      }
      this.addPoPlannerCodeFromChooser = ''
      this.addPoPlannerDisplayFromChooser = ''
      this.poSupplierDialogVisible = false
      this.orderSupplierDialogVisible = false
      this.loadPoList()
      this.fetchSupplierAddress(supplierNoVal)
    },

    // 判断两条PO明细是否为同一行（优先用内部主键，再回退到展示字段）
    isSamePoDetailRow (sourceRow, targetRow) {
      if (!sourceRow || !targetRow) {
        return false
      }
      const sourceOrderNo = String(sourceRow.orderNo || sourceRow.order_no || '')
      const sourceItemNo = String(sourceRow.itemNo || sourceRow.item_no || '')
      const targetOrderNo = String(targetRow.orderNo || targetRow.order_no || '')
      const targetItemNo = String(targetRow.itemNo || targetRow.item_no || '')
      if (sourceOrderNo && sourceItemNo && targetOrderNo && targetItemNo) {
        return sourceOrderNo === targetOrderNo && sourceItemNo === targetItemNo
      }
      return String(sourceRow.orderRef1 || '') === String(targetRow.orderRef1 || '') &&
        String(sourceRow.orderRef2 || '') === String(targetRow.orderRef2 || '') &&
        String(sourceRow.partNo || '') === String(targetRow.partNo || '')
    },

    // 供应商回填后，自动勾选“从订单选择供应商”时选中的那条PO明细
    applyPendingAutoSelectPoRow () {
      if (!this.pendingAutoSelectPoRow) {
        return
      }
      const targetRow = this.pendingAutoSelectPoRow
      this.$nextTick(() => {
        const tableRef = this.$refs.addPoTable
        if (!tableRef) {
          this.pendingAutoSelectPoRow = null
          return
        }
        let matchedRow = null
        for (let i = 0; i < this.filteredPoList.length; i++) {
          if (this.isSamePoDetailRow(this.filteredPoList[i], targetRow)) {
            matchedRow = this.filteredPoList[i]
            break
          }
        }
        if (matchedRow) {
          tableRef.toggleRowSelection(matchedRow, true)
        }
        this.pendingAutoSelectPoRow = null
      })
    },

    // 打开“从订单选择供应商”弹框（不默认筛供应商）
    openOrderSupplierDialog () {
      if (this.isSupplierPageMode) {
        return
      }
      this.orderSupplierDialogVisible = true
      this.orderSupplierCurrentRow = null
      this.orderSupplierPageIndex = 1
      this.orderSupplierTotal = 0
      this.orderSupplierSearch = {
        orderNo: '',
        partNo: '',
        item: '',
        sku: '',
        partDesc: '',
        supplierName: '',
        planner: ''
      }
      this.loadOrderSupplierList()
    },

    // 订单来源供应商弹框查询
    searchOrderSupplierByPo () {
      this.orderSupplierPageIndex = 1
      this.loadOrderSupplierList()
    },

    // 加载订单来源供应商分页列表（专用后端方法）
    loadOrderSupplierList () {
      const params = {
        site: this.$store.state.user.site,
        page: this.orderSupplierPageIndex,
        limit: this.orderSupplierPageSize,
        orderNo: this.orderSupplierSearch.orderNo || '',
        partNo: this.orderSupplierSearch.partNo || '',
        item: this.orderSupplierSearch.item || '',
        sku: this.orderSupplierSearch.sku || '',
        partDesc: this.orderSupplierSearch.partDesc || '',
        supplierName: this.orderSupplierSearch.supplierName || '',
        planner: this.orderSupplierSearch.planner || ''
      }
      this.orderSupplierLoading = true
      queryPoSupplierOrderPage(params).then(({ data }) => {
        if (data.code === 0 && data.page) {
          const list = (data.page.list || []).map(item => ({
            ...item,
            supplierNo: item.supplierNo || item.supplier_no || '',
            supplierName: item.supplierName || item.supplier_name || '',
            planner: item.planner || '',
            crd: item.crd ? String(item.crd).split(' ')[0] : ''
          }))
          this.orderSupplierList = list
          this.orderSupplierTotal = data.page.totalCount || 0
          this.orderSupplierPageIndex = data.page.currPage || this.orderSupplierPageIndex
          this.orderSupplierPageSize = data.page.pageSize || this.orderSupplierPageSize
          this.$nextTick(() => {
            if (this.orderSupplierList.length > 0) {
              this.orderSupplierCurrentRow = this.orderSupplierList[0]
              if (this.$refs.orderSupplierTable) {
                this.$refs.orderSupplierTable.setCurrentRow(this.orderSupplierCurrentRow)
              }
            } else {
              this.orderSupplierCurrentRow = null
              if (this.$refs.orderSupplierTable) {
                this.$refs.orderSupplierTable.setCurrentRow()
              }
            }
          })
        } else {
          this.orderSupplierList = []
          this.orderSupplierCurrentRow = null
          this.orderSupplierTotal = 0
        }
      }).catch(() => {
        this.orderSupplierList = []
        this.orderSupplierCurrentRow = null
        this.orderSupplierTotal = 0
        this.$message.error('加载订单来源供应商失败')
      }).finally(() => {
        this.orderSupplierLoading = false
      })
    },

    // 重置“从订单选择供应商”筛选条件
    resetOrderSupplierSearch () {
      this.orderSupplierSearch = {
        orderNo: '',
        partNo: '',
        item: '',
        sku: '',
        partDesc: '',
        supplierName: '',
        planner: ''
      }
      this.orderSupplierPageIndex = 1
      this.loadOrderSupplierList()
    },

    // 订单来源供应商弹框页大小变化
    onOrderSupplierPageSizeChange (val) {
      this.orderSupplierPageSize = val
      this.orderSupplierPageIndex = 1
      this.loadOrderSupplierList()
    },

    // 订单来源供应商弹框页码变化
    onOrderSupplierPageCurrentChange (val) {
      this.orderSupplierPageIndex = val
      this.loadOrderSupplierList()
    },

    // “从订单选择供应商”选中行变化
    onOrderSupplierCurrentChange (row) {
      this.orderSupplierCurrentRow = row || null
    },

    // “从订单选择供应商”双击选择
    onOrderSupplierRowDblClick (row) {
      this.selectSupplierByOrderRow(row)
    },

    // “从订单选择供应商”点击确认
    confirmOrderSupplierSelect () {
      this.selectSupplierByOrderRow(this.orderSupplierCurrentRow)
    },

    // 从订单行回填供应商并触发原有后续流程
    selectSupplierByOrderRow (row) {
      if (!row) {
        this.$message.warning('请选择订单行')
        return
      }
      const supplierNo = row.supplierNo || row.supplier_no || ''
      const supplierName = row.supplierName || row.supplier_name || ''
      if (!supplierNo) {
        this.$message.warning('所选订单行缺少供应商编码')
        return
      }
      this.pendingAutoSelectPoRow = {
        orderNo: row.orderNo || row.order_no || '',
        itemNo: row.itemNo || row.item_no || '',
        orderRef1: row.orderRef1 || '',
        orderRef2: row.orderRef2 || '',
        partNo: row.partNo || ''
      }
      this.selectPoSupplier({
        supplierNo: supplierNo,
        supplierName: supplierName
      })
    },

    // 加载PO列表（选择供应商后调用）
    loadPoList () {
      if (!this.addFormData.supplierNo) {
        this.$message.warning('请先选择供应商')
        return
      }

      const params = {
        supplierNo: this.addFormData.supplierNo,
        site: this.$store.state.user.site,
        page: 1,
        limit: 1000
      }

      queryPoPage(params).then(({ data }) => {
        if (data.code === 0 && data.page) {
          this.poList = data.page.list.map(item => ({
            ...item,
            supplierNo: item.supplierNo || item.supplier_no || this.addFormData.supplierNo || '',
            supplierName: item.supplierName || item.supplier_name || this.addFormData.supplierName || '',
            planner: item.planner || '',
            inspectQty: item.waitInspectQty || 0, // 默认值为未验货数量
            shipMethod: item.shipMethod || '',// 运输方式
            crd: item.crd ? item.crd.split(' ')[0] : ''
          }))
          this.filterAddPoList()
          this.applyPendingAutoSelectPoRow()
        } else {
          this.poList = []
          this.filteredPoList = []
          this.pendingAutoSelectPoRow = null
          this.$message.info('该供应商暂无可申请验货的PO')
        }
      }).catch(() => {
        this.poList = []
        this.filteredPoList = []
        this.pendingAutoSelectPoRow = null
        this.$message.error('加载PO列表失败')
      })
    },

    // 表格选择变化
    handleSelectionChange (selection) {
      this.selectedPoList = selection
    },
    // Planner 输入若被手工改动，则清理双击选择时缓存的显示名映射
    handleAddPoPlannerInput (value) {
      const plannerKeyword = String(value || '').trim()
      const chooserPlannerCode = String(this.addPoPlannerCodeFromChooser || '').trim()
      if (!plannerKeyword || plannerKeyword !== chooserPlannerCode) {
        this.addPoPlannerCodeFromChooser = ''
        this.addPoPlannerDisplayFromChooser = ''
      }
    },

    // 新增验货申请-PO明细筛选
    filterAddPoList () {
      let result = [...this.poList]
      const filter = this.addPoFilter || {}
      const orderNoKeyword = (filter.orderNo || '').toLowerCase().trim()
      const partNoKeyword = (filter.partNo || '').toLowerCase().trim()
      const itemKeyword = (filter.item || '').toLowerCase().trim()
      const skuKeyword = (filter.sku || '').toLowerCase().trim()
      const partDescKeyword = (filter.partDesc || '').toLowerCase().trim()
      const supplierNameKeyword = (filter.supplierName || '').toLowerCase().trim()
      const plannerKeyword = (filter.planner || '').toLowerCase().trim()
      const chooserPlannerCode = String(this.addPoPlannerCodeFromChooser || '').toLowerCase().trim()
      const chooserPlannerDisplay = String(this.addPoPlannerDisplayFromChooser || '').toLowerCase().trim()
      const useChooserDisplayKeyword = plannerKeyword && chooserPlannerCode && plannerKeyword === chooserPlannerCode
        ? chooserPlannerDisplay
        : ''

      if (orderNoKeyword) {
        result = result.filter(item => {
          const orderRef1 = String(item.orderRef1 || '').toLowerCase()
          const orderNo = String(item.orderNo || item.order_no || '').toLowerCase()
          return orderRef1.includes(orderNoKeyword) || orderNo.includes(orderNoKeyword)
        })
      }
      if (partNoKeyword) {
        result = result.filter(item => String(item.partNo || '').toLowerCase().includes(partNoKeyword))
      }
      if (itemKeyword) {
        result = result.filter(item => String(item.item || '').toLowerCase().includes(itemKeyword))
      }
      if (skuKeyword) {
        result = result.filter(item => String(item.sku || '').toLowerCase().includes(skuKeyword))
      }
      if (partDescKeyword) {
        result = result.filter(item => String(item.partDesc || '').toLowerCase().includes(partDescKeyword))
      }
      if (supplierNameKeyword) {
        result = result.filter(item => String(item.supplierName || '').toLowerCase().includes(supplierNameKeyword))
      }
      if (plannerKeyword) {
        result = result.filter(item => {
          const plannerText = String(item.planner || '').toLowerCase()
          if (plannerText.includes(plannerKeyword)) {
            return true
          }
          return useChooserDisplayKeyword ? plannerText.includes(useChooserDisplayKeyword) : false
        })
      }
      this.filteredPoList = result
    },

    // 新增验货申请-PO筛选重置
    resetAddPoFilter () {
      this.addPoFilter = {
        orderNo: '',
        partNo: '',
        item: '',
        sku: '',
        partDesc: '',
        supplierName: '',
        planner: ''
      }
      this.addPoPlannerCodeFromChooser = ''
      this.addPoPlannerDisplayFromChooser = ''
      this.filterAddPoList()
    },

    // CRD日期排序方法
    sortCrdDate (a, b) {
      const dateA = a.crd || ''
      const dateB = b.crd || ''

      if (!dateA && !dateB) return 0
      if (!dateA) return -1
      if (!dateB) return 1

      return dateA.localeCompare(dateB)
    },

    // 验货数量变化
    handleInspectQtyChange (row, value) {
      console.log('验货数量变化：', row.orderRef1, value)
      // 确保数据被正确更新
      this.$set(row, 'inspectQty', value)
    },


    // 保存
    handleSaveAdd () {
      if (this.isEditDialogMode) {
        this.handleSaveEdit()
        return
      }
      console.log('开始保存，当前选择的PO列表：', this.selectedPoList)
      console.log('表单数据：', this.addFormData)

      this.$refs.addFormData.validate((valid) => {
        console.log('表单验证结果：', valid)
        if (valid) {
          if (this.selectedPoList.length === 0) {
            this.$message.warning('请至少选择一条PO明细')
            return
          }

          // 检查验货数量
          const hasInvalidQty = this.selectedPoList.some(item => !item.inspectQty || item.inspectQty <= 0)
          if (hasInvalidQty) {
            this.$message.warning('请填写有效的验货数量')
            return
          }

          // 构建提交数据
          const submitData = {
            requestDate: this.addFormData.requestDate,
            needInspectDate: this.addFormData.needInspectDate,
            supplierNo: this.addFormData.supplierNo,
            inspectAddress: this.addFormData.inspectAddressId || this.addFormData.inspectAddress,
            inspectAddressId: this.addFormData.inspectAddressId || '',
            inspectCityShort: this.addFormData.inspectCityShort || '',
            inspectContract: this.addFormData.contact,
            remark: '',
            items: this.selectedPoList.map(item => ({
              orderNo: item.orderNo || item.order_ref1 || item.orderRef1,
              itemNo: item.itemNo || item.item_no || item.order_ref2 || item.orderRef2,
              partNo: item.partNo,
              orderRef1: item.orderRef1,
              orderRef2: item.orderRef2,
              qty: item.inspectQty,
              shipMethod: item.shipMethod,
              crd: item.crd
            }))
          }

          console.log('提交的数据：', submitData)

          saveInspectionRequest(submitData).then(({ data }) => {
            console.log('保存接口返回：', data)
            if (data.code === 0) {
              this.$message.success('保存成功')
              this.handleCloseAddDialog()
              this.getMainData()
            } else {
              this.$message.error(data.msg || '保存失败')
            }
          }).catch((error) => {
            console.error('保存接口错误：', error)
            this.$message.error('保存失败，请稍后重试')
          })
        } else {
          console.log('表单验证失败')
          this.$message.warning('请填写完整的表单信息')
        }
      })
    },

    // 草稿编辑保存：仅更新基础信息中的可编辑字段 - rqrq
    handleSaveEdit () {
      this.$refs.addFormData.validate((valid) => {
        if (!valid) {
          this.$message.warning('请填写完整的表单信息')
          return
        }
        const submitData = {
          requestNo: this.addFormData.requestNo,
          needInspectDate: this.addFormData.needInspectDate,
          inspectAddress: this.addFormData.inspectAddressId || this.addFormData.inspectAddress,
          inspectAddressId: this.addFormData.inspectAddressId || '',
          inspectContract: this.addFormData.contact
        }
        updateInspectionRequest(submitData).then(({ data }) => {
          if (data.code === 0) {
            this.$message.success('修改成功')
            this.handleCloseAddDialog()
            this.getMainData()
          } else {
            this.$message.error(data.msg || '修改失败')
          }
        }).catch((error) => {
          console.error('修改接口错误：', error)
          this.$message.error('修改失败，请稍后重试')
        })
      })
    },

    // Excel导入
    importExcel () {
      this.uploadDialogVisible = true
      this.uploadFileName = ''
      this.uploadFile = null
      this.uploadPreviewList = []
    },

    // 文件选择变化
    handleFileChange (file) {
      this.uploadFile = file.raw
      this.uploadFileName = file.name
    },

    // 预览上传数据
    previewUpload () {
      if (!this.uploadFile) {
        this.$message.warning('请先选择文件')
        return
      }

      const formData = new FormData()
      formData.append('file', this.uploadFile)

      // 调用后端预览接口
      previewUpload(this.uploadFile).then(({ data }) => {
        if (data && data.code === 0) {
          this.uploadPreviewList = data.data || []
          this.$message.success('文件解析成功，请确认数据后点击保存')
        } else {
          this.$message.error(data.msg || '文件解析失败')
        }
      }).catch((error) => {
        console.error('文件解析失败:', error)
        const errorMsg = (error.response && error.response.data && error.response.data.msg) || error.message || '未知错误'
        this.$message.error('文件解析失败: ' + errorMsg)
      })
    },

    // 确认上传
    confirmUpload () {
      if (this.uploadPreviewList.length === 0) {
        this.$message.warning('没有可保存的数据')
        return
      }

      this.$confirm(`确认保存 ${this.uploadPreviewList.length} 条数据吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用后端保存接口
        batchSave(this.uploadFile).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message.success('数据保存成功')
            this.uploadDialogVisible = false
            this.getMainData()
          } else {
            this.$message.error(data.msg || '数据保存失败')
          }
        }).catch((error) => {
          console.error('数据保存失败:', error)
          const errorMsg = (error.response && error.response.data && error.response.data.msg) || error.message || '未知错误'
          this.$message.error('数据保存失败: ' + errorMsg)
        })
      }).catch(() => {})
    },

    // 下载模板
    downloadTemplate () {
      const loading = this.$loading({
        lock: true,
        text: '正在下载模板...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      this.$http({
        url: this.$http.adornUrl('/inspection/downloadTemplate'),
        method: 'post',
        responseType: 'blob'
      }).then(response => {
        loading.close()

        // 创建下载文件
        const blob = new Blob([response.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })

        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = '验货申请导入模板.xlsx'

        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        window.URL.revokeObjectURL(url)

        this.$message.success('模板下载成功')
      }).catch(error => {
        loading.close()
        console.error('模板下载失败:', error)
        this.$message.error('模板下载失败，请联系管理员')
      })
    },

    // 导出
    exportExcel () {
      console.log('开始导出...')

      // 生成文件名（使用原生 Date）
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hour = String(now.getHours()).padStart(2, '0')
      const minute = String(now.getMinutes()).padStart(2, '0')
      const second = String(now.getSeconds()).padStart(2, '0')
      const exportName = `检验申请单${year}${month}${day}${hour}${minute}${second}`

      console.log('导出参数:', this.searchData)

      // 获取当前查询条件
      const exportParams = {
        ...this.searchData,
        limit: 99999,
        page: 1
      }

      try {
        excel.exportTable({
          url: 'inspection/searchInspectionRequestHeaderList',
          columnMapping: this.columnArray1,
          mergeSetting: [],
          params: exportParams,
          fileName: exportName + '.xlsx',
          rowFetcher: res => {
            console.log('导出数据响应:', res)
            if (res.data && res.data.page && res.data.page.list) {
              return res.data.page.list
            }
            console.error('响应数据结构异常:', res.data)
            this.$message.error('导出数据格式异常，请查看控制台')
            return []
          },
          columnFormatter: [],
          dropColumns: []
        })
        console.log('导出请求已发送')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败: ' + error.message)
      }
    },

    // 确认验货申请
    confirmInspection (row) {
      this.$confirm('确定要确认该验货申请吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        confirmInspectionRequest(row.requestNo).then(({ data }) => {
          if (data.code === 0) {
            this.$message.success('确认成功')
            this.getMainData()
          } else {
            this.$message.error(data.msg || '确认失败')
          }
        }).catch((error) => {
          console.error('确认接口错误：', error)
          this.$message.error('确认失败，请稍后重试')
        })
      }).catch(() => {
        this.$message.info('已取消确认')
      })
    },

    // 删除验货申请
    deleteInspectionRequest (row) {
      if (!this.isRowStatus(row, ['Draft', 'Confirmed'])) {
        this.$message.warning('只有草稿和待审核状态允许删除')
        return
      }
      this.$confirm('确定要删除该验货申请吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteInspectionRequest(row.requestNo).then(({ data }) => {
          if (data.code === 0) {
            this.$message.success('删除成功')
            this.getMainData()
          } else {
            this.$message.error(data.msg || '删除失败')
          }
        }).catch((error) => {
          console.error('删除接口错误：', error)
          this.$message.error('删除失败，请稍后重试')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 草稿编辑：仅可编辑建议验货日期、验货地址、联系人 - rqrq
    editInspectionRequest (row) {
      if (!this.isRowStatus(row, ['Draft'])) {
        this.$message.warning('只有草稿状态允许编辑')
        return
      }
      this.openEditInspectionDialog(row)
    },

    // 申请变更（已下达/已排程） - rqrq
    applyChangeRequest (row) {
      if (!this.isRowStatus(row, ['Audited', 'Scheduled'])) {
        this.$message.warning('只有已下达或已排程状态允许申请变更')
        return
      }
      const isScheduled = this.isRowStatus(row, ['Scheduled'])
      if (isScheduled) {
        this.applyChangeForm = {
          requestNo: row.requestNo || '',
          statusDb: 'Scheduled',
          changeRemark: ''
        }
        this.applyChangeDialogVisible = true
        return
      }
      const tipText = '已下达申请单申请变更后将回到【草稿】，是否继续？'
      this.$confirm(tipText, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.executeApplyChangeRequest(row.requestNo, '')
      }).catch(() => {
        this.$message.info('已取消申请变更')
      })
    },

    // 提交已排程的变更申请（需填写备注）- rqrq
    submitApplyChangeRequest () {
      const requestNo = this.applyChangeForm.requestNo || ''
      const changeRemark = this.applyChangeForm.changeRemark ? this.applyChangeForm.changeRemark.trim() : ''
      if (!requestNo) {
        this.$message.warning('申请单号不能为空')
        return
      }
      if (!changeRemark) {
        this.$message.warning('请填写变更备注')
        return
      }
      this.$confirm('确定提交变更申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.executeApplyChangeRequest(requestNo, changeRemark)
      }).catch(() => {
        this.$message.info('已取消提交')
      })
    },

    executeApplyChangeRequest (requestNo, changeRemark) {
      this.applyChangeLoading = true
      applyChangeInspectionRequest(requestNo, { changeRemark }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message.success('申请变更成功')
          this.applyChangeDialogVisible = false
          this.getMainData()
        } else {
          this.$message.error((data && data.msg) || '申请变更失败')
        }
      }).catch((error) => {
        console.error('申请变更接口错误：', error)
        this.$message.error('申请变更失败，请稍后重试')
      }).finally(() => {
        this.applyChangeLoading = false
      })
    }
  }
}
</script>

<style scoped lang="scss">
.search-form-inline {
  background: #fff;
  padding: 0;
  margin-bottom: 0;
}

.search-row {
  display: flex;
  align-items: flex-end;
  flex-wrap: wrap;
  gap: 0;
  margin-bottom: 0;
}

.search-item {
  flex: none;
  margin-bottom: 0;
  margin-right: 12px;
}

/* 使用 Element UI 默认字体大小，不再覆盖 */
.search-item /deep/ .el-form-item__label {
  padding-bottom: 0;
  line-height: 1.2;
}

.search-btn-item {
  flex: none;
  margin-bottom: 0;
  margin-right: 0;
}

.search-item /deep/ .el-form-item__content {
  line-height: normal;
}

.date-range {
  display: flex;
  align-items: center;
}

.split {
  padding: 0 6px;
  color: #606266;
  font-size: 13px;
}

/**
 * 验货申请详情页签统一高度容器：
 * 1) 固定高度：保证“基本信息/明细/结果/费用/附件”视觉高度一致；
 * 2) 内部滚动：内容超高时在当前页签滚动，避免整体布局抖动。
 */
.tab-pane-content {
  width: 100%;
  overflow-y: auto;
  overflow-x: hidden;
}

/deep/ .customer-tab .el-tabs__content {
  padding: 5px !important;
}

.form-section {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  padding: 5px 10px;
}

.add-dialog-form /deep/ .el-form-item {
  margin-bottom: 10px;
}

.add-dialog-form /deep/ .el-form-item__label {
  text-align: left;
  float: none;
  display: block;
  padding: 0 0 5px 0;
  line-height: 1;
  font-size: 13px;
}

.add-dialog-form /deep/ .el-form-item__content {
  margin-left: 0 !important;
}

.po-section {
  .section-title {
    font-size: 14px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 8px;
  }

  .section-desc {
    font-size: 12px;
    color: #909399;
    margin-bottom: 10px;
  }
}

.dialog-footer {
  text-align: center;
}

/deep/ .el-input-number .el-input__inner {
  text-align: right !important;
  padding-right: 32px !important;
  padding-left: 8px !important;
  box-sizing: border-box;
}

/deep/ .el-input .el-input--mini {
  line-height: 20px;
}

/deep/ .el-input-number .el-input--mini {
  line-height: 20px;
}

/* PO表格输入控件防遮挡 */
.po-section {

  /deep/ .el-table .cell {
    height: auto;
    line-height: 20px;
    overflow: hidden !important;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding-left: 4px;
    padding-right: 4px;
  }

  /deep/ .el-input,
  /deep/ .el-select {
    width: 100% !important;
  }

  /deep/ .el-input-number .el-input__inner {
    padding-left: 8px !important;
    padding-right: 35px !important;
    text-align: right;
  }

  /deep/ .el-input-number {
    width: 120px !important;
    min-width: 120px !important;
  }

  /deep/ .el-select .el-input__inner {
    padding-right: 25px !important;
  }
}

// 数字输入框按钮样式修复
/deep/ .el-input-number {
  position: relative;

  .el-input-number__increase,
  .el-input-number__decrease {
    width: 28px;
    height: 50%;
    position: absolute;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    border: none;
    cursor: pointer;
    transition: all 0.2s;
    font-size: 12px;

    &:hover {
      background-color: #ecf5ff;
      color: #409eff;
    }

    &:active {
      background-color: #d9e1f0;
    }
  }

  .el-input-number__increase {
    top: 0;
    bottom: auto;
    border-bottom: 1px solid #dcdfe6;
    border-top-right-radius: 4px;
  }

  .el-input-number__decrease {
    top: auto;
    bottom: 0;
    border-bottom-right-radius: 4px;
  }

  // 确保输入框右边留出按钮空间
  .el-input__inner {
    padding-right: 32px !important;
  }
}

// 数字输入框按钮样式修复
/deep/ .el-input-number {
  position: relative;

  .el-input-number__increase,
  .el-input-number__decrease {
    width: 28px;
    height: 50%;
    position: absolute;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    border: none;
    cursor: pointer;
    transition: all 0.2s;
    font-size: 12px;

    &:hover {
      background-color: #ecf5ff;
      color: #409eff;
    }

    &:active {
      background-color: #d9e1f0;
    }
  }

  .el-input-number__increase {
    top: 0;
    bottom: auto;
    border-bottom: 1px solid #dcdfe6;
    border-top-right-radius: 4px;
  }

  .el-input-number__decrease {
    top: auto;
    bottom: 0;
    border-bottom-right-radius: 4px;
  }

  .el-input__inner {
    padding-right: 32px !important;
  }
}

/deep/ .el-input-number--mini {
  .el-input-number__increase,
  .el-input-number__decrease {
    width: 24px;
    font-size: 10px;
  }

  .el-input__inner {
    padding-right: 28px !important;
  }
}


.po-section {

  /deep/ .el-date-editor.el-input,
  /deep/ .el-date-editor.el-input__inner {
    width: 100%;
  }

  /deep/ .el-date-editor .el-input__inner {
    height: 28px;
    line-height: 28px;
    padding-left: 10px;
    padding-right: 10px;
    font-size: 12px;
  }

  /deep/ .el-date-editor .el-input__prefix {
    display: none;
  }

  /deep/ .el-date-editor .el-input__suffix {
    right: 5px;
  }
}

.choose-label {
  color: #2ec7c9;
  cursor: pointer;
  font-weight: 500;
}

.choose-label:hover {
  text-decoration: underline;
}

.po-supplier-search-form {
  margin-bottom: 8px;
}

.order-supplier-search-form {
  margin-bottom: 8px;
}

.add-po-search-form {
  margin-bottom: 8px;
}
</style>
