
<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
        <el-form-item label="单据编号" prop="receivingNum">
          <el-input
            v-model="queryParams.receivingNum"
            placeholder="请输入单据编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="日期" prop="timeRange">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="供应商简称" prop="supplierName">
          <el-input  v-model="queryParams.supplierName"
                     placeholder="请输入供应商简称"
                     clearable></el-input>
        </el-form-item>
        <el-form-item label="业务员" prop="employeeName">
          <el-input  v-model="queryParams.employeeName"
                     placeholder="请输入业务员"
                     clearable></el-input>
        </el-form-item>
        <el-form-item label="货物名称" prop="goodsName">
          <el-input  v-model="queryParams.goodsName"
                     placeholder="请输入货物名称"
                     clearable></el-input>
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input  v-model="queryParams.warehouseName"
                     placeholder="请输入仓库名称"
                     clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['purchase:purchaseStorage:add']"
          >新增</el-button>
        </el-col>
<!--        <el-col :span="1.5">-->
<!--          <el-button-->
<!--            type="danger"-->
<!--            plain-->
<!--            icon="el-icon-delete"-->
<!--            size="mini"-->
<!--            :disabled="multiple"-->
<!--            @click="handleDeleteAll"-->
<!--            v-hasPermi="['purchase:purchaseStorage:remove']"-->
<!--          >批量删除</el-button>-->
<!--        </el-col>-->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-card>
    <br />
    <el-card>
      <el-table border stripe  v-loading="loading" ref="multipleTable" :data="disposalList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="单据编号" width="150" align="center" fixed prop="receivingNum" />
        <el-table-column label="单据日期" width="150" align="center" prop="receivingDate" />
        <el-table-column label="订货日期" width="150" align="center" prop="orderDate" />
        <el-table-column label="采购类型" width="150"  align="center" prop="orderType" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.purchase_order_type" :value="scope.row.orderType"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="到场时间" width="180" align="center" prop="arriveDate" />
        <el-table-column label="供应商编号" width="150" align="center" prop="supplierNum" />
        <el-table-column label="供应商名称" width="150" align="center" prop="supplierName" />
        <el-table-column label="业务员" width="150" align="center" prop="employeeName" />
        <el-table-column label="采购部门" width="150" align="center" prop="departmentName" />
        <el-table-column label="畜主" width="150" align="center" prop="livestockOwner" />
        <el-table-column label="畜主信息" width="250" align="center" prop="livestockOwnerInfo" />
        <el-table-column label="检疫证号" width="200" align="center" prop="animalCertNo" />
        <el-table-column label="准宰证号" width="200" align="center" prop="allowSlaughterNo" />
        <el-table-column label="产地" width="150" align="center" prop="placeOfOrigin" />
        <el-table-column label="采购货品"   align="center" fixed="right" width="150">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
            >查看详情报价单</el-button>
          </template>
        </el-table-column>
        <el-table-column label="合计金额(元)" align="center" width="150" fixed="right" prop="totalAmount">
          <template slot-scope="scope">
            <span>{{getMoney(scope.row.totalAmount)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right" class-name="small-padding fixed-width">
          <template slot-scope="scope">
<!--            <el-button-->
<!--              size="mini"-->
<!--              type="text"-->
<!--              icon="el-icon-view"-->
<!--              @click="handleView(scope.row)"-->
<!--            >查看</el-button>-->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['purchase:purchaseStorage:edit']"
              style="margin-right: 8px"
            >修改</el-button>
          <el-popconfirm
          v-hasPermi="['purchase:purchaseStorage:remove']"
          :title="'确定要删除这条数据吗？'"
            @confirm="handleDelete(scope.row)"
              >
          <el-button
          size="mini"
            type="text"
                slot="reference"
          icon="el-icon-delete"
            >删除</el-button>
          </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改死淘处理方式对话框 -->
    <el-dialog :title="title" :visible.sync="open" fullscreen append-to-body>
      <el-form v-if="!isView" ref="form" :model="form" :rules="formRules" :disabled="isView" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="单据编号" prop="receivingNum">
              <el-input
                ref="receivingNum"
                v-model="form.receivingNum"
                placeholder="请输入单据编号"
                @keydown.enter.native="goNext($event, 'quotationDate')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据日期" prop="receivingDate">
              <el-date-picker
                ref="receivingDate"
                style="width: 100%;"
                v-model="form.receivingDate"
                value-format="yyyy-MM-dd"
                placeholder="请选择单据日期"
                @keydown.enter.native="goNext($event, 'orderDate')"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="价格转入" prop="priceTransfer">
              <el-input v-model="form.priceTransfer">
                <template #append>
                  <el-button
                    type="primary"
                    icon="el-icon-search"
                    @click="openPriceTransferQueryDialog"
                  />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="订货日期" prop="orderDate">
              <el-date-picker
                ref="orderDate"
                style="width: 100%;"
                v-model="form.orderDate"
                value-format="yyyy-MM-dd"
                placeholder="请选择订货日期"
                @keydown.enter.native="goNext($event, 'orderType')"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购类型" prop="orderType">
              <el-select
                v-model="form.orderType"
                style="width: 100%;"
                filterable
                ref="orderType"
                placeholder="请选择采购类型"
                @keydown.enter.native="goNext($event, 'arriveDate')"
              >
                <el-option v-for="item in dict.type.purchase_order_type" :key="item.value" :value="item.value" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="到场时间" prop="arriveDate">
              <el-date-picker
                type="datetime"
                ref="arriveDate"
                style="width: 100%;"
                v-model="form.arriveDate"
                placeholder="请选择到场时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                @keydown.enter.native="goNext($event, 'supplierName')"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-select
                filterable
                ref="supplierName"
                style="width: 100%;"
                v-model="form.supplierName"
                @change="changeSupplier"
                placeholder="请选择供应商"
                @keydown.enter.native="goNext($event, 'employeeNum')"
              >
                <el-option
                  v-for="(item ,i) in supplierList"
                  :key="i"
                  :label="item.supplierName"
                  :value="item.supplierName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商编号" prop="supplierNum">
              <el-input disabled v-model="form.supplierNum" placeholder="选择供应商名称自动填充"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务员" prop="employeeNum">
              <el-select
                filterable
                ref="employeeNum"
                v-model="form.employeeNum"
                style="width: 100%;"
                @change="changeEmployee"
                placeholder="请选择业务员"
                @keydown.enter.native="goNext($event, 'remark1')"
              >
                <el-option
                  v-for="(item ,i) in staffList"
                  :key="i"
                  :label="item.employeeName"
                  :value="item.employeeNum"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="采购部门" prop="departmentNum">
              <el-select
                filterable
                ref="departmentNum"
                v-model="form.departmentNum"
                style="width: 100%;"
                @change="changeDepartment"
                placeholder="请选择采购部门"
                @keydown.enter.native="goNext($event, 'livestockOwner')"
              >
                <el-option v-for="item in departmentList" :key="item.departmentNum" :value="item.departmentNum" :label="item.departmentName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="畜主" prop="livestockOwner">
              <el-input
                ref="livestockOwner"
                v-model="form.livestockOwner"
                placeholder="请输入畜主"
                @keydown.enter.native="goNext($event, 'livestockOwnerInfo')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="畜主信息" prop="livestockOwnerInfo">
              <el-input
                ref="livestockOwnerInfo"
                v-model="form.livestockOwnerInfo"
                placeholder="请输入畜主信息"
                @keydown.enter.native="goNext($event, 'animalCertNo')"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="检疫证号" prop="animalCertNo">
              <el-input
                ref="animalCertNo"
                v-model="form.animalCertNo"
                placeholder="请输入检疫证号"
                @keydown.enter.native="goNext($event, 'allowSlaughterNo')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="准宰证号" prop="allowSlaughterNo">
              <el-input
                ref="allowSlaughterNo"
                v-model="form.allowSlaughterNo"
                placeholder="请输入准宰证号"
                @keydown.enter.native="goNext($event, 'livestockOwner')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产地" prop="placeOfOrigin">
              <el-select
                filterable
                ref="placeOfOrigin"
                v-model="form.placeOfOrigin"
                style="width: 100%;"
                placeholder="请选择产地"
                @keydown.enter.native="goNext($event, 'remark')"
              ></el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="form.remark"  placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-divider content-position="left">货品列表</el-divider>
          <el-form-item label-width="0" prop="goods">
            <el-table
              :data="form.goods"
              style="width: 100%;"
              border
              stripe
            >
              <el-table-column label="货品编号" prop="goodsNum" fixed width="200" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.goodsNum`"
                    :rules="rules.goodsNum"
                    class="table-form-item"
                  >
                    <el-input
                      v-model="row.goodsNum"
                      placeholder="请输入货品编号"
                      @change="handleEdit($index, 'goodsNum', row.goodsNum)"
                    >
                      <template #append>
                        <el-tooltip class="item" effect="dark" content="货品速查" placement="top">
                          <el-button type="success" icon="el-icon-search" circle size="mini" @click="openQueryMaterial($index)"></el-button>
                        </el-tooltip>
                      </template>
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="货品名称" prop="goodsName" fixed width="150" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.goodsName`"
                    :rules="rules.goodsName"
                    class="table-form-item"
                  >
                    <el-input
                      v-model="row.goodsName"
                      placeholder="请输入货品名称"
                      @change="handleEdit($index, 'goodsNum', row.goodsName)"
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="规格" prop="goodsSpec" width="120" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.goodsSpec`"
                    :rules="rules.goodsSpec"
                    class="table-form-item"
                  >
                    <el-input
                      v-model="row.goodsSpec"
                      placeholder="请输入规格"
                      @change="handleEdit($index, 'goodsSpec', row.goodsSpec)"
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="仓库" prop="warehouseNo" width="150" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.warehouseNo`"
                    :rules="rules.warehouseNo"
                    class="table-form-item"
                  >
                    <el-select
                      style="width: 100%"
                      filterable
                      v-model="row.warehouseNo"
                      @change="handleEdit($index, 'warehouseNo', row.warehouseNo)">
                      <el-option 
                      v-for="item in warehouseList"
                       :key="item.warehouseNo"
                        :value="item.warehouseNo"
                         :label="item.warehouseName"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="批次" prop="batch" width="150" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.batch`"
                    :rules="rules.batch"
                    class="table-form-item"
                  >
                    <el-input
                      v-model="row.batch"
                      placeholder="请输入批次"
                      @change="handleEdit($index, 'batch', row.batch)"
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="到场方式" prop="arriveMethod" width="150" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.arriveMethod`"
                    :rules="rules.arriveMethod"
                    class="table-form-item"
                  >
                    <el-select
                      style="width: 100%"
                      filterable
                      v-model="row.arriveMethod"
                      @change="handleEdit($index, 'arriveMethod', row.arriveMethod)">
                      <el-option v-for="item in dict.type.purchase_arrive_method" :key="item.value" :value="item.value" :label="item.label"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="牧场重量" prop="ranchWeight" width="150" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.ranchWeight`"
                    :rules="rules.ranchWeight"
                    class="table-form-item"
                  >
                    <decimal-input
                      v-model="row.ranchWeight"
                      :min="0"
                      :max="999999"
                      :precision="2"
                      placeholder="请输入牧场重量"
                      @change="handleEdit($index, 'ranchWeight', row.ranchWeight)"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="到场重量" prop="arriveWeight" width="150" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.arriveWeight`"
                    :rules="rules.arriveWeight"
                    class="table-form-item"
                  >
                    <decimal-input
                      v-model="row.arriveWeight"
                      :min="0"
                      :max="999999"
                      :precision="2"
                      placeholder="请输入到场重量"
                      @change="handleEdit($index, 'arriveWeight', row.arriveWeight)"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="基本计量数量" prop="baseNum" width="150" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.baseNum`"
                    :rules="rules.baseNum"
                    class="table-form-item"
                  >
                    <decimal-input
                      v-model="row.baseNum"
                      :min="0"
                      :max="999999"
                      :precision="2"
                      placeholder="请输入基本计量数量"
                      @change="handleEdit($index, 'baseNum', row.baseNum)"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="基本计量单位" prop="baseUnit" width="120" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.baseUnit`"
                    :rules="rules.baseUnit"
                    class="table-form-item"
                  >
                    <el-input
                      v-model="row.baseUnit"
                      placeholder="请输入基本计量单位"
                      @change="handleEdit($index, 'baseUnit', row.baseUnit)"
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="辅助计量数量" prop="assNum" width="150" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.assNum`"
                    :rules="rules.assNum"
                    class="table-form-item"
                  >
                    <decimal-input
                      v-model="row.assNum"
                      :min="0"
                      :max="999999"
                      :precision="2"
                      placeholder="请输入辅助计量数量"
                      @change="handleEdit($index, 'assNum', row.assNum)"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="辅助计量单位" prop="assUnit" width="120" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.assUnit`"
                    :rules="rules.assUnit"
                    class="table-form-item"
                  >
                    <el-input
                      v-model="row.assUnit"
                      placeholder="请输入辅助计量单位"
                      @change="handleEdit($index, 'assUnit', row.assUnit)"
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="单价(元)" prop="unitPrice" width="150" align="center" >
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.unitPrice`"
                    :rules="rules.unitPrice"
                    class="table-form-item"
                  >
                    <decimal-input
                      v-model="row.unitPrice"
                      :min="0"
                      :max="999999"
                      :precision="2"
                      placeholder="请输入单价"
                      @change="handleEdit($index, 'unitPrice', row.unitPrice)"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="金额(元)" prop="amount" width="150" align="center" >
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.amount`"
                    :rules="rules.amount"
                    class="table-form-item"
                  >
                    <decimal-input
                      v-model="row.amount"
                      :min="0"
                      :max="999999"
                      :precision="2"
                      placeholder="请输入金额"
                      disabled
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="交货日期" prop="deliveryDate" width="150" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.deliveryDate`"
                    :rules="rules.deliveryDate"
                    class="table-form-item"
                  >
                    <el-date-picker
                      ref="orderDate"
                      style="width: 100%;"
                      v-model="form.deliveryDate"
                      value-format="yyyy-MM-dd"
                      placeholder="请选择交货日期"
                      @change="handleEdit($index, 'deliveryDate', row.deliveryDate)"
                    ></el-date-picker>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="结算方式" prop="settlementMethod" width="150" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.settlementMethod`"
                    :rules="rules.settlementMethod"
                    class="table-form-item"
                  >
                    <el-select
                      style="width: 100%"
                      filterable
                      v-model="row.settlementMethod"
                      @change="handleEdit($index, 'settlementMethod', row.settlementMethod)">
                      <el-option v-for="item in dict.type.purchase_settle" :key="item.value" :value="item.value" :label="item.label"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="经营类型" prop="businessType" width="150" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.businessType`"
                    :rules="rules.businessType"
                    class="table-form-item"
                  >
                    <el-select
                      style="width: 100%"
                      filterable
                      v-model="row.businessType"
                      @change="handleEdit($index, 'businessType', row.businessType)">
                      <el-option v-for="item in dict.type.purchase_business" :key="item.value" :value="item.value" :label="item.label"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="预估级别" prop="estimateLevel" width="150" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.estimateLevel`"
                    :rules="rules.estimateLevel"
                    class="table-form-item"
                  >
                    <el-input
                      v-model="row.estimateLevel"
                      placeholder="请输入预估级别"
                      @change="handleEdit($index, 'estimateLevel', row.estimateLevel)"
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="预估重量" prop="estimateWeight" width="150" align="center" >
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.estimateWeight`"
                    :rules="rules.estimateWeight"
                    class="table-form-item"
                  >
                    <decimal-input
                      v-model="row.estimateWeight"
                      :min="0"
                      :max="999999"
                      :precision="2"
                      placeholder="请输入预估重量"
                      @change="handleEdit($index, 'estimateWeight', row.estimateWeight)"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="是否黑猪扣款" prop="isDeduction" width="150" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.isDeduction`"
                    :rules="rules.isDeduction"
                    class="table-form-item"
                  >
                    <el-select
                      style="width: 100%"
                      filterable
                      v-model="row.isDeduction"
                      @change="handleEdit($index, 'isDeduction', row.isDeduction)">
                      <el-option :value="'1'" label="是"></el-option>
                      <el-option :value="'0'" label="否"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <!-- 操作列 -->
              <el-table-column label="操作" width="100" align="center" fixed="right">
                <template slot-scope="{ $index }">
                  <el-button
                    type="danger"
                    size="small"
                    icon="el-icon-delete"
                    @click="handleDeleteRow($index)"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <!-- 添加按钮 -->
          <div style="margin-top: 10px; text-align: center;">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="handleAddRow"
            >
              添加货品
            </el-button>
          </div>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="总金额" prop="totalAmount">
              <decimal-input v-model="form.totalAmount" :min="0" :max="999999" :precision="2" placeholder="请输入总金额" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-else>
        <el-descriptions border>
          <el-descriptions-item label="单据编号">{{form.receivingNum}}</el-descriptions-item>
          <el-descriptions-item label="单据日期">{{form.receivingDate}}</el-descriptions-item>
          <el-descriptions-item label="订货日期">{{form.orderDate}}</el-descriptions-item>
          <el-descriptions-item label="采购类型">
            <dict-tag :options="dict.type.purchase_order_type" :value="form.orderType"></dict-tag>
          </el-descriptions-item>
          <el-descriptions-item label="供应商名称">{{form.supplierName}}</el-descriptions-item>
          <el-descriptions-item label="业务员">{{form.employeeName}}</el-descriptions-item>
          <el-descriptions-item label="采购部门">{{form.departmentName}}</el-descriptions-item>
          <el-descriptions-item label="畜主">{{form.livestockOwner}}</el-descriptions-item>
          <el-descriptions-item label="畜主信息">{{form.livestockOwnerInfo}}</el-descriptions-item>
          <el-descriptions-item label="检疫证号">{{form.animalCertNo}}</el-descriptions-item>
          <el-descriptions-item label="准宰证号">{{form.allowSlaughterNo}}</el-descriptions-item>
          <el-descriptions-item label="备注">{{form.remark}}</el-descriptions-item>
        </el-descriptions>
        <el-divider content-position="left">货品列表</el-divider>
        <el-table
          :data="form.goods"
          style="width: 100%;"
          border
          stripe
          show-summary
          :summary-method="getSummaries"
        >
          <el-table-column label="货品编号" prop="goodsNum" fixed width="200" align="center"></el-table-column>
          <el-table-column label="货品名称" prop="goodsName" fixed width="150" align="center"></el-table-column>
          <el-table-column label="规格" prop="goodsSpec" width="120" align="center"></el-table-column>
          <el-table-column label="仓库" prop="warehouseName" width="150" align="center"></el-table-column>
          <el-table-column label="批次" prop="batch" width="150" align="center"></el-table-column>
          <el-table-column label="到场方式" width="150" align="center">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.purchase_arrive_method" :value="scope.row.arriveMethod"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="牧场重量" prop="ranchWeight" width="150" align="center">
            <template slot-scope="scope">
              <span>{{getMoney(scope.row.ranchWeight)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="到场重量" prop="arriveWeight" width="150" align="center">
            <template slot-scope="scope">
              <span>{{getMoney(scope.row.arriveWeight)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="基本计量数量" prop="baseNum" width="150" align="center">
            <template slot-scope="scope">
              <span>{{getMoney(scope.row.baseNum)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="基本计量单位" prop="baseUnit" width="120" align="center"></el-table-column>
          <el-table-column label="辅助计量数量" prop="assNum" width="150" align="center">
            <template slot-scope="scope">
              <span>{{getMoney(scope.row.assNum)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="辅助计量单位" prop="assUnit" width="120" align="center"></el-table-column>
          <el-table-column label="单价(元)" prop="unitPrice" sortable width="150" align="center" fixed="right">
            <template slot-scope="scope">
              <span>{{getMoney(scope.row.unitPrice)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="金额(元)" prop="amount"  sortable width="150" align="center" fixed="right">
            <template slot-scope="scope">
              <span>{{getMoney(scope.row.amount)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="交货日期" prop="deliveryDate" width="150" align="center"></el-table-column>
          <el-table-column label="结算方式" width="150" align="center">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.purchase_settle" :value="scope.row.settlementMethod"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="经营类型" width="150" align="center">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.purchase_business" :value="scope.row.businessType"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="预估级别" prop="estimateLevel" width="150" align="center"></el-table-column>
          <el-table-column label="预估重量" prop="estimateWeight" width="150" align="center">
            <template slot-scope="scope">
              <span>{{getMoney(scope.row.estimateWeight)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="预估级别" prop="isDeduction" width="150" align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.isDeduction === '0'" type="primary">否</el-tag>
              <el-tag v-else-if="scope.row.isDeduction === '1'" type="success">是</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <div slot="footer" class="dialog-footer" v-if="!isView">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <query-material ref="query-material" @selectList="getSelectList"></query-material>
    </el-dialog>

    <!-- 价格转入查询：单选（高亮浅蓝） -->
    <el-dialog
      title="价格转入查询"
      :visible.sync="priceTransferQueryDialogOpen"
      width="1200px"
      append-to-body
      class="price-transfer-dialog"
      @close="priceTransferQueryDialogOpen = false"
    >
      <el-table
        :data="priceTransferList"
        border
        stripe
        highlight-current-row
        height="420"
        style="width: 100%;"
        class="price-transfer-table"
        @row-click="handlePriceTransferRowClick"
      >
        <el-table-column label="单据日期" align="center" min-width="140">
          <template slot-scope="{ row }">
            {{ row.documentDate || row.quotationDate || row.receivingDate || "—" }}
          </template>
        </el-table-column>
        <el-table-column label="单据编号" align="center" min-width="160">
          <template slot-scope="{ row }">
            {{ row.quotationNum || row.billNo || row.receivingNum || "—" }}
          </template>
        </el-table-column>
        <el-table-column label="供应商编号" align="center" min-width="150">
          <template slot-scope="{ row }">
            {{ row.supplierNum || "—" }}
          </template>
        </el-table-column>
        <el-table-column label="供应商简称" align="center" min-width="160">
          <template slot-scope="{ row }">
            {{ row.supplierShortName || row.supplierName || "—" }}
          </template>
        </el-table-column>
        <el-table-column label="备注1" align="center" min-width="160">
          <template slot-scope="{ row }">
            {{ row.remark1 || row.remark || "—" }}
          </template>
        </el-table-column>
        <el-table-column label="采购员编号" align="center" min-width="150">
          <template slot-scope="{ row }">
            {{ row.employeeNum || "—" }}
          </template>
        </el-table-column>
        <el-table-column label="采购员名称" align="center" min-width="160">
          <template slot-scope="{ row }">
            {{ row.employeeName || "—" }}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlePriceTransferConfirm">确 定</el-button>
        <el-button @click="priceTransferQueryDialogOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getSupplierList } from "@/api/purchase/supplier";
import { getStaffList } from "@/api/baseInfo/staff";
import {
  getPurchaseStoragePage,
  addPurchaseStorage,
  editPurchaseStorage,
  delPurchaseStorage,
  getPurchaseStorageById,
  getStorageNum,
} from "../../../api/purchase/purchaseStorage";
import {
  getFindByKey,
  formatMoney,
  formatDateYMS,
  formatDate,
} from "../../../utils";
import { getDepartmentList } from "../../../api/baseInfo/department";
import queryMaterial from "../../components/queryMaterial.vue";
import { getWareHouseList } from "../../../api/inventory/wareHouse";
import {
  getPurchaseQuotationList,
  getPurchaseQuotationById,
} from "../../../api/purchase/purchaseQuotation";

export default {
  name: "PurchaseStorage",
  dicts: [
    "purchase_order_type",
    "purchase_arrive_method",
    "purchase_settle",
    "purchase_business",
  ],
  components: {
    queryMaterial,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      disposalList: [],
      // 弹出层标题
      title: "",
      isView: false,
      // 是否显示弹出层
      open: false,
      // 价格转入查询弹框
      priceTransferQueryDialogOpen: false,
      // 价格转入查询表格数据
      priceTransferList: [],
      // 当前选择的价格转入单据行
      priceTransferSelectedRow: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        receivingNum: null,
        timeRange: null,
        startTime: null,
        endTime: null,
        supplierName: null,
        employeeName: null,
        goodsName: null,
        warehouseName: null,
      },
      pickerOptions: {
        disabledDate(time) {
          // 获取当前日期
          const today = new Date();
          today.setHours(0, 0, 0, 0); // 将时间设置为当天的 00:00:00

          // 禁用今天之后的日期
          return time.getTime() > today.getTime();
        },
      },
      // 表单参数
      form: {},
      formRules: {
        receivingNum: [
          { required: true, message: "请输入单据编号", trigger: "blur" },
        ],
        receivingDate: [
          { required: true, message: "请选择单据日期", trigger: "change" },
        ],
        orderDate: [
          { required: true, message: "请选择订货日期", trigger: "change" },
        ],
        orderType: [
          { required: true, message: "请选择采购类型", trigger: "change" },
        ],
        arriveDate: [
          { required: true, message: "请选择到场时间", trigger: "change" },
        ],
        supplierName: [
          { required: true, message: "请选择供应商名称", trigger: "change" },
        ],
        employeeNum: [
          { required: true, message: "请选择业务员", trigger: "change" },
        ],
        animalCertNo: [
          { required: true, message: "请输入检疫证号", trigger: "blur" },
        ],
        allowSlaughterNo: [
          { required: true, message: "请输入准宰证号", trigger: "blur" },
        ],
        goods: [
          {
            validator: (rule, value, callback) => {
              if (!value || value.length === 0) {
                callback(new Error("至少需要一件货品"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
      },
      rules: {
        goodsNum: [
          { required: true, message: "货品编号不能为空", trigger: "change" },
        ],
        batch: [{ required: true, message: "请输入批次", trigger: "change" }],
        ranchWeight: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === null || value === undefined || value === "") {
                callback(new Error("牧场重量不能为空"));
                return;
              }
              const w = Number(value);
              if (!Number.isFinite(w) || w <= 0) {
                callback(new Error("牧场重量必须大于 0"));
                return;
              }
              // arriveMethod === '2' 时：牧场重量必须等于基本计量数量
              const fullField = rule && (rule.fullField || rule.field);
              const m = String(fullField || "").match(/^goods\.(\d+)\./);
              const index = m ? Number(m[1]) : null;
              const row =
                index != null && this.form && Array.isArray(this.form.goods)
                  ? this.form.goods[index]
                  : {};
              if (row && String(row.arriveMethod) === "2") {
                const base = Number(row.baseNum);
                if (
                  !Number.isFinite(base) ||
                  Number(w).toFixed(2) !== Number(base).toFixed(2)
                ) {
                  callback(new Error("要与基本计量数量一致"));
                  return;
                }
              }
              callback();
            },
            trigger: "change",
          },
        ],
        arriveWeight: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === null || value === undefined || value === "") {
                callback(new Error("到场重量不能为空"));
                return;
              }
              const w = Number(value);
              if (!Number.isFinite(w) || w <= 0) {
                callback(new Error("到场重量必须大于 0"));
                return;
              }
              // arriveMethod === '1' 时：到场重量必须等于基本计量数量
              const fullField = rule && (rule.fullField || rule.field);
              const m = String(fullField || "").match(/^goods\.(\d+)\./);
              const index = m ? Number(m[1]) : null;
              const row =
                index != null && this.form && Array.isArray(this.form.goods)
                  ? this.form.goods[index]
                  : {};
              if (row && String(row.arriveMethod) === "1") {
                const base = Number(row.baseNum);
                if (
                  !Number.isFinite(base) ||
                  Number(w).toFixed(2) !== Number(base).toFixed(2)
                ) {
                  callback(new Error("要与基本计量数量一致"));
                  return;
                }
              }
              callback();
            },
            trigger: "change",
          },
        ],
        baseNum: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === null || value === undefined || value === "") {
                callback(new Error("请输入基本计量数量"));
                return;
              }
              const n = Number(value);
              if (!Number.isFinite(n) || n <= 0) {
                callback(new Error("基本计量数量必须大于 0"));
                return;
              }
              callback();
            },
            trigger: "change",
          },
        ],
        assNum: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === null || value === undefined || value === "") {
                callback(new Error("请输入辅助计量数量"));
                return;
              }
              const n = Number(value);
              if (!Number.isFinite(n) || n <= 0) {
                callback(new Error("辅助计量数量必须大于 0"));
                return;
              }
              callback();
            },
            trigger: "change",
          },
        ],
        unitPrice: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === null || value === undefined || value === "") {
                callback(new Error("请输入单价"));
                return;
              }
              const n = Number(value);
              if (!Number.isFinite(n) || n <= 0) {
                callback(new Error("单价必须大于 0"));
                return;
              }
              callback();
            },
            trigger: "change",
          },
        ],
        warehouseNo: [
          { required: true, message: "请选择仓库", trigger: "change" },
        ],
      },
      supplierList: [],
      staffList: [],
      departmentList: [],
      warehouseList: [],
    };
  },
  watch: {
    "queryParams.timeRange": {
      handler(newVal) {
        if (newVal) {
          this.queryParams.startTime = newVal[0];
          this.queryParams.endTime = newVal[1];
        } else {
          this.queryParams.startTime = null;
          this.queryParams.endTime = null;
        }
      },
      deep: true,
    },
    "form.goods": {
      handler(newVal) {
        let amount = 0;
        (newVal || []).forEach((item) => {
          const v = Number(item && item.amount);
          amount += Number.isFinite(v) ? v : 0;
        });
        this.form.totalAmount = amount;
      },
      deep: true,
    },
  },
  created() {
    this.getSupplier();
    this.getDepartment();
    this.getStaff();
    this.getWarehouse();
    this.getList();
  },
  methods: {
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          // 第一列显示"合计"
          sums[index] = "总金额";
          return;
        }
        // 获取列属性
        const property = column.property;
        if (property === "amount") {
          const values = data.map((item) => Number(item[property]));
          if (!values.every((value) => isNaN(value))) {
            // 计算总和
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            // 格式化金额（千分位，两位小数）
            sums[index] = this.getMoney(sums[index]);
          } else {
            sums[index] = "N/A";
          }
        } else {
          sums[index] = "N/A";
        }
      });
      return sums;
    },
    getMoney(val) {
      return formatMoney(val);
    },
    goNext(event, nextRef) {
      event.preventDefault();
      this.$refs[nextRef].focus();
    },
    /**
     * 打开价格转入查询弹框（预留）
     */
    openPriceTransferQueryDialog() {
      if (this.isView) return;
      this.priceTransferQueryDialogOpen = true;
      this.priceTransferSelectedRow = null;
      this.fetchPriceTransferList();
    },
    /**
     * 获取价格转入列表（用于“价格转入查询”弹框）
     */
    fetchPriceTransferList() {
      const params = {
        pageNum: 1,
        pageSize: 10,
      };
      getPurchaseQuotationList(params)
        .then((res) => {
          const data = res && res.data ? res.data : res;
          const records = data && (data.records || data.list || data);
          this.priceTransferList = Array.isArray(records) ? records : [];
        })
        .catch(() => {
          this.priceTransferList = [];
        });
    },
    handlePriceTransferRowClick(row) {
      if (!row) return;
      this.priceTransferSelectedRow = row;
    },
    /**
     * 确认：将选中的价格转入单据回填并关闭弹框
     */
    handlePriceTransferConfirm() {
      if (this.isView) return;
      const row = this.priceTransferSelectedRow;
      if (!row) {
        this.$message.warning("请先选择一条价格转入记录");
        return;
      }
      const id = row.id != null ? row.id : row.quotationId;
      if (id == null) {
        this.$message.warning("当前选择数据缺少 id，无法回填明细");
        return;
      }

      getPurchaseQuotationById({ id }).then((res) => {
        const data = res && res.data ? res.data : res;

        // 1) 表头赋值
        this.form.priceTransfer = row.quotationNum;
        this.form.supplierNum =
          data.supplierNum != null ? data.supplierNum : row.supplierNum || null;
        this.form.supplierName =
          data.supplierName != null
            ? data.supplierName
            : row.supplierName || row.supplierShortName || null;
        this.form.employeeNum =
          data.employeeNum != null ? data.employeeNum : row.employeeNum || null;
        this.form.employeeName =
          data.employeeName != null
            ? data.employeeName
            : row.employeeName || null;
        this.form.totalAmount =
          data.totalAmount != null ? data.totalAmount : this.form.totalAmount;

        // 2) 明细赋值（goods）
        const qGoods = Array.isArray(data.goods) ? data.goods : [];
        const list = qGoods.map((g) => {
          const warehouseName = g.warehouseName || g.warehouse || null;
          const whHit =
            warehouseName && Array.isArray(this.warehouseList)
              ? this.warehouseList.find(
                  (x) => x.warehouseName === warehouseName
                )
              : null;

          const conv =
            g.conversionValue != null ? Number(g.conversionValue) : 1;
          const baseNum =
            g.baseNum != null
              ? g.baseNum
              : g.assNum != null
              ? Number(g.assNum) * conv
              : null;

          return {
            goodsNum: g.goodsNum,
            goodsName: g.goodsName,
            goodsSpec: g.goodsSpec,
            warehouseNo: whHit ? whHit.warehouseNo : g.warehouseNo || null,
            warehouseName: warehouseName,
            baseNum: baseNum,
            baseUnit: g.baseUnit,
            assNum: g.assNum,
            assUnit: g.assUnit || g.assistantUnit || null,
            unitPrice: g.unitPrice,
            amount: g.amount,
            conversionValue: conv,

            // 其它字段保持可空（不覆盖你后续业务逻辑）
            batch: null,
            arriveMethod: "1",
            ranchWeight: null,
            arriveWeight: null,
            deliveryDate: null,
            settlementMethod: "1",
            businessType: "1",
            estimateLevel: null,
            estimateWeight: null,
            isDeduction: "0",
            remark: null,
          };
        });

        this.form.goods = list.length ? list : this.form.goods;
        this.priceTransferQueryDialogOpen = false;
      });
    },
    /** 仓库**/
    getWarehouse() {
      getWareHouseList({}).then((res) => {
        this.warehouseList = res.data;
      });
    },
    /** 采购部门 **/
    getDepartment() {
      getDepartmentList({}).then((res) => {
        this.departmentList = res.data;
      });
    },
    changeDepartment(val) {
      let item = getFindByKey(this.departmentList, val, "departmentNum");
      if (item) {
        this.form.departmentName = item.departmentName;
      }
    },
    /** 供应商 **/
    getSupplier() {
      getSupplierList({}).then((res) => {
        this.supplierList = res.data.filter(
          (item) => item.supplierType === "1"
        );
      });
    },
    changeSupplier(val) {
      let item = getFindByKey(this.supplierList, val, "supplierName");
      if (item) {
        this.form.supplierNum = item.supplierNum;
        this.form.supplierPhone = item.phone;
      }
    },
    /** 业务员 **/
    getStaff() {
      getStaffList({}).then((res) => {
        this.staffList = res.data.filter((item) => item.employeeType === "2");
      });
    },
    changeEmployee(val) {
      let item = getFindByKey(this.staffList, val, "employeeNum");
      if (item) {
        this.form.employeeName = item.employeeName;
      }
    },
    /** 查询检验项目列表 */
    getList() {
      getPurchaseStoragePage(this.queryParams).then((res) => {
        this.disposalList = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        receivingNum: null,
        timeRange: null,
        startTime: null,
        endTime: null,
        supplierName: null,
        employeeName: null,
        goodsName: null,
        warehouseName: null,
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    initNum() {
      getStorageNum({}).then((res) => {
        this.form.receivingNum = res.msg;
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isView = false;
      this.title = "添加";
      let that = this;
      this.$nextTick(() => {
        that.initNum();
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      let params = {
        id: id,
      };
      getPurchaseStorageById(params).then((res) => {
        this.form = res.data;
        this.open = true;
        this.isView = false;
        this.title = "编辑";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id;
      let params = {
        id: id,
      };
      getPurchaseStorageById(params).then((res) => {
        this.form = res.data;
        this.open = true;
        this.isView = true;
        this.title = "查看";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        receivingNum: null,
        receivingDate: formatDateYMS(
          new Date().getTime() + 1000 * 60 * 60 * 24
        ),
        priceTransfer: null,
        orderDate: formatDateYMS(new Date().getTime() + 1000 * 60 * 60 * 24),
        orderType: "1",
        arriveDate: formatDate(new Date().getTime()),
        supplierNum: null,
        supplierName: null,
        employeeNum: null,
        employeeName: null,
        departmentNum: null,
        departmentName: null,
        livestockOwner: null,
        livestockOwnerInfo: null,
        animalCertNo: null,
        allowSlaughterNo: null,
        placeOfOrigin: null,
        totalAmount: null,
        remark: null,
        goods: [
          {
            goodsNum: null,
            goodsName: null,
            goodsSpec: null,
            warehouseNo: null,
            warehouseName: null,
            batch: null,
            arriveMethod: "1",
            ranchWeight: null,
            arriveWeight: null,
            baseNum: null,
            baseUnit: null,
            assNum: null,
            assUnit: null,
            unitPrice: null,
            amount: null,
            deliveryDate: null,
            settlementMethod: "1",
            businessType: "1",
            estimateLevel: null,
            estimateWeight: null,
            isDeduction: "0",
            remark: null,
            conversionValue: null,
          },
        ],
      };
      this.resetForm("form");
    },
    handleAddRow() {
      let row = {
        goodsNum: null,
        goodsName: null,
        goodsSpec: null,
        warehouseName: null,
        batch: null,
        arriveMethod: "1",
        ranchWeight: null,
        arriveWeight: null,
        baseNum: null,
        baseUnit: null,
        assNum: null,
        assUnit: null,
        unitPrice: null,
        amount: null,
        deliveryDate: null,
        settlementMethod: "1",
        businessType: "1",
        estimateLevel: null,
        estimateWeight: null,
        isDeduction: "0",
        remark: null,
        conversionValue: null,
      };
      this.form.goods.push(row);
      setTimeout(() => {
        this.validateTableRow(this.form.goods.length - 1);
      }, 0);
    },
    // 处理编辑
    handleEdit(index, field, value) {
      // 触发对应字段的校验
      this.$refs.form.validateField(`goods.${index}.${field}`);

      // 到场方式/基本计量数量变更时，需要联动校验重量字段的一致性
      if (field === "arriveMethod" || field === "baseNum") {
        this.$refs.form.validateField(`goods.${index}.arriveWeight`);
        this.$refs.form.validateField(`goods.${index}.ranchWeight`);
      }

      // 辅助计量数量变更时：baseNum = conversionValue * assNum
      if (field === "assNum") {
        const row = this.form.goods[index] || {};
        const conv =
          row.conversionValue != null ? Number(row.conversionValue) : 1;
        const ass = value != null && value !== "" ? Number(value) : null;
        if (ass == null || !Number.isFinite(ass)) {
          row.baseNum = null;
        } else {
          row.baseNum = conv * ass;
        }

        // 更新金额（amount = baseNum * unitPrice）
        row.amount = (row.unitPrice || 0) * (row.baseNum || 0);

        // 让 baseNum / 重量一致性校验能及时反映最新值
        this.$nextTick(() => {
          this.$refs.form.validateField(`goods.${index}.baseNum`);
          this.$refs.form.validateField(`goods.${index}.arriveWeight`);
          this.$refs.form.validateField(`goods.${index}.ranchWeight`);
        });
      }

      if (field === "warehouseNo") {
        let item = getFindByKey(this.warehouseList, value, "warehouseNo");
        if (item) {
          this.form.goods[index].warehouseName = item.warehouseName;
        }
      }
      // 自动计算金额
      if (field === "unitPrice" || field === "baseNum") {
        const row = this.form.goods[index];
        row.amount = (row.unitPrice || 0) * (row.baseNum || 0);
      }
    },
    handleDeleteRow(index) {
      // 保证表格至少保留一行（占位行也保留）
      if (
        !this.form ||
        !Array.isArray(this.form.goods) ||
        this.form.goods.length <= 1
      ) {
        this.$message.warning("至少保留一行货品");
        return;
      }
      this.$confirm("确定要删除该货品吗？", "提示", {
        type: "warning",
      }).then(() => {
        this.form.goods.splice(index, 1);
        this.$message.success("删除成功");
      });
    },
    // 验证表格行
    validateTableRow(rowIndex) {
      // 这里校验行内必填字段（prop 路径必须和模板一致：goods.${index}.*）
      const fields = [
        "goodsNum",
        "batch",
        "ranchWeight",
        "arriveWeight",
        "baseNum",
        "assNum",
        "unitPrice",
      ];
      fields.forEach((field) => {
        this.$refs.form.validateField(`goods.${rowIndex}.${field}`);
      });
    },
    /** 提交按钮 */
    submitForm() {
      // 提交前：删除表格中 goodsNum 为空/为 null 的行
      this.removeEmptyGoodsRows();

      this.$nextTick(() => {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.form.id != null) {
              // 编辑
              editPurchaseStorage(this.form).then((res) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              // 新增
              addPurchaseStorage(this.form).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      let params = {
        ids: ids,
      };
      delPurchaseStorage(params).then((res) => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      });
    },
    /** 删除按钮操作 */
    handleDeleteAll() {
      const ids = this.ids;
      this.$modal.confirm("确定要删除这条数据吗？").then(() => {
        let params = {
          ids: ids.join(","),
        };
        // (params).then(res => {
        //   this.getList();
        //   this.$modal.msgSuccess("删除成功");
        //   this.$refs.multipleTable.clearSelection();
        // })
      });
    },
    // 打开物料速查表
    openQueryMaterial(index) {
      this.goodsIndex = index;
      this.$refs["query-material"].open();
    },
    // 拿到物料
    getSelectList(list) {
      if (list.length === 0) {
        this.form.goods = [];
        return;
      }
      console.log(list);
      const createGoodsRow = (item) => {
        console.log(item);
        return {
          goodsNum: item.goodsNum,
          goodsName: item.goodsName,
          goodsSpec: item.goodsSpec,
          warehouseNo: item.warehouseNo,
          warehouseName: item.warehouseName,
          batch: null,
          arriveMethod: "1",
          ranchWeight: null,
          arriveWeight: null,
          baseNum: null,
          baseUnit: item.unit,
          assNum: null,
          assUnit: item.assistantUnit,
          unitPrice: null,
          amount: null,
          deliveryDate: null,
          settlementMethod: "1",
          businessType: "1",
          estimateLevel: null,
          estimateWeight: null,
          isDeduction: "0",
          conversionValue:
            item.conversionValue != null ? item.conversionValue : 1,
          remark: null,
        };
      };

      const toKey = (v) =>
        v === null || v === undefined ? "" : String(v).trim();
      const selectedGoodsNum0 = toKey(list[0] && list[0].goodsNum);

      // 当前表格中是否已经存在相同 goodsNum（排除正在替换的那一行）
      const hasDuplicateGoodsNum = (goodsNum, excludeIndex) => {
        const key = toKey(goodsNum);
        if (!key) return false;
        return (this.form.goods || []).some((row, idx) => {
          if (
            excludeIndex !== undefined &&
            excludeIndex !== null &&
            idx === excludeIndex
          )
            return false;
          return toKey(row && row.goodsNum) === key;
        });
      };

      // 先处理第一个：替换当前 goodsIndex 行
      if (hasDuplicateGoodsNum(selectedGoodsNum0, this.goodsIndex)) {
        this.$message.warning("该货品已在表格中，请勿重复选择");
      } else {
        this.form.goods.splice(this.goodsIndex, 1, createGoodsRow(list[0]));
      }

      // 其余项：append 进去前也要做重复判断（如果重复则跳过，并提示）
      for (let i = 1; i < list.length; i++) {
        const item = list[i];
        if (hasDuplicateGoodsNum(item.goodsNum, null)) {
          this.$message.warning("该货品已在表格中，请勿重复选择");
          continue;
        }
        this.form.goods.push(createGoodsRow(item));
      }
    },

    // 删除表格中 goodsNum 为空/null 的行，提交前使用
    removeEmptyGoodsRows() {
      const goods = Array.isArray(this.form.goods) ? this.form.goods : [];

      const filtered = goods.filter((row) => {
        if (!row) return false;
        const key =
          row.goodsNum === null || row.goodsNum === undefined
            ? ""
            : String(row.goodsNum).trim();
        return key !== "";
      });

      // 如果全部都是空行：必须保留一条占位行，确保校验能命中“必填”
      if (filtered.length === 0) {
        if (goods.length > 0) {
          this.form.goods.splice(0, goods.length, goods[0]);
        } else {
          this.form.goods = [
            {
              goodsNum: null,
              goodsName: null,
              goodsSpec: null,
              warehouseNo: null,
              warehouseName: null,
              batch: null,
              arriveMethod: "1",
              ranchWeight: null,
              arriveWeight: null,
              baseNum: null,
              baseUnit: null,
              assNum: null,
              assUnit: null,
              unitPrice: null,
              amount: null,
              deliveryDate: null,
              settlementMethod: "1",
              businessType: "1",
              estimateLevel: null,
              estimateWeight: null,
              isDeduction: "0",
              remark: null,
              conversionValue: null,
            },
          ];
        }
        return;
      }

      // 否则只保留有 goodsNum 的行
      if (filtered.length !== goods.length) {
        this.form.goods.splice(0, goods.length, ...filtered);
      }
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .price-transfer-dialog .el-table__body tr.current-row > td {
  background-color: #d9ecff !important;
}
// el-table 单元格默认会裁剪内容，导致嵌套 el-form-item 的错误提示文字不可见
// 放开 overflow，让校验错误能在单元格下方显示出来
::v-deep .el-table td {
  overflow: visible !important;
}

// 让错误提示脱离绝对定位/裁剪
::v-deep .el-table .el-form-item__error {
  position: static !important;
  white-space: nowrap;
}
</style>
