<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="orderNum">
          <el-input
            v-model="queryParams.orderNum"
            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>
          <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="['app:test: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="['app:test: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="生产日期" align="center" prop="orderDate"  />
        <el-table-column label="单据编号" align="center" prop="orderNum"  />
        <el-table-column label="生产类型" align="center" prop="productionType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.inventory_production_type" :value="scope.row.productionType" />
          </template>
        </el-table-column>
        <el-table-column label="生产起始时间" align="center" prop="orderStartDate"  />
        <el-table-column label="生产结束时间" align="center" prop="orderEndDate"  />
        <el-table-column label="生产数量" align="center" prop="num"  />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="详细货品" align="center">
          <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="操作" width="180" align="center" 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="['app:test:edit']"
              style="margin-right: 8px"
            >修改</el-button>
            <el-popconfirm
              v-hasPermi="['app:test: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="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产日期" prop="orderDate">
              <el-date-picker
                ref="inDate"
                style="width: 100%;"
                v-model="form.orderDate"
                value-format="yyyy-MM-dd"
                placeholder="请选择生产日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据编号" prop="orderNum">
              <el-input v-model="form.orderNum"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产类型" prop="productionType">
              <el-select style="width: 100%;" filterable v-model="form.productionType" placeholder="请选择生产类型">
                <el-option v-for="item in dict.type.inventory_production_type" :key="item.value" :value="item.value" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产车间" prop="productionPlantNo">
              <el-select style="width: 100%;" filterable v-model="form.productionPlantNo" placeholder="请选择生产车间" @change="changeProductionPlant">
                <el-option v-for="item in productionPlantList" :key="item.productionPlantNo" :value="item.productionPlantNo" :label="item.productionPlantName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产起始时间" prop="orderStartDate">
              <el-date-picker
                ref="inDate"
                style="width: 100%;"
                v-model="form.orderStartDate"
                value-format="yyyy-MM-dd"
                placeholder="请选择生产起始时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产结束时间" prop="orderEndDate">
              <el-date-picker
                ref="inDate"
                style="width: 100%;"
                v-model="form.orderEndDate"
                value-format="yyyy-MM-dd"
                placeholder="请选择生产结束时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产数量" prop="num">
              <decimal-input v-model="form.num" :min="0" :max="999999" :precision="2" placeholder="请输入生产数量" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <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="180" 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, 'goodsName', row.goodsName)"
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="规格" prop="goodsSpec" width="180" 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="varietyNo" width="180" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.varietyNo`"
                    :rules="rules.varietyNo"
                    class="table-form-item"
                  >
                    <el-select
                      v-model="row.varietyNo"
                      placeholder="请选择级别"
                      @change="handleEdit($index, 'varietyNo', row.varietyNo)"
                    >
                      <el-option v-for="item in varietyList" :key="item.varietyNo" :value="item.varietyNo" :label="item.varietyName"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="级别" prop="levelNo" width="180" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.levelNo`"
                    :rules="rules.levelNo"
                    class="table-form-item"
                  >
                    <el-select
                      v-model="row.levelNo"
                      placeholder="请选择级别"
                      @change="handleEdit($index, 'levelNo', row.levelNo)"
                    >
                      <el-option v-for="item in levelList" :key="item.levelNo" :value="item.levelNo" :label="item.levelName"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="仓库" prop="warehouseName" width="180" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.warehouseName`"
                    :rules="rules.warehouseName"
                    class="table-form-item"
                  >
                    <el-select
                      v-model="row.warehouseName"
                      placeholder="请选择仓库"
                      @change="handleEdit($index, 'warehouseName', row.warehouseName)"
                    >
                      <el-option v-for="item in wareList" :key="item.warehouseNo" :value="item.warehouseName" :label="item.warehouseName"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="批次" prop="batch" width="180" 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)"
                    >
                      <template #append>
                        <el-button
                          type="primary"
                          icon="el-icon-search"
                          @click="openBatchQueryDialog($index)"
                        />
                      </template>
                    </el-input>
                  </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="150" 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="assistantUnit" width="150" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.assistantUnit`"
                    :rules="rules.assistantUnit"
                    class="table-form-item"
                  >
                    <el-input
                      v-model="row.assistantUnit"
                      placeholder="请输入辅助计量单位"
                      @change="handleEdit($index, 'assistantUnit', row.assistantUnit)"
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="成本" prop="cost" width="150" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.cost`"
                    :rules="rules.cost"
                    class="table-form-item"
                  >
                    <decimal-input
                      v-model="row.cost"
                      :min="0"
                      :max="999999"
                      :precision="2"
                      placeholder="请输入成本"
                      @change="handleEdit($index, 'cost', row.cost)"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="白条编号" prop="whiteNum" width="180" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.whiteNum`"
                    :rules="rules.whiteNum"
                    class="table-form-item"
                  >
                    <el-input
                      v-model="row.whiteNum"
                      placeholder="请输入白条编号"
                      @change="handleEdit($index, 'whiteNum', row.whiteNum)"
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="货品备注" prop="remark" width="200" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.remark`"
                    :rules="rules.remark"
                    class="table-form-item"
                  >
                    <el-input
                      v-model="row.remark"
                      placeholder="请输入货品备注"
                      @change="handleEdit($index, 'remark', row.remark)"
                    >
                    </el-input>
                  </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>
            <!-- 添加按钮 -->
            <div style="margin-top: 10px; text-align: center;">
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="small"
                @click="handleAddRow"
              >
                添加货品
              </el-button>
            </div>
          </el-form-item>
        </el-row>
      </el-form>
      <template v-else>
        <el-descriptions :column="3" border class="detail-desc">
          <el-descriptions-item label="生产日期">{{ form.orderDate || "-" }}</el-descriptions-item>
          <el-descriptions-item label="单据编号">{{ form.orderNum || "-" }}</el-descriptions-item>
          <el-descriptions-item label="生产类型">
            <dict-tag :options="dict.type.inventory_production_type" :value="form.productionType" />
          </el-descriptions-item>
          <el-descriptions-item label="生产车间">{{ form.productionPlantName || form.productionPlantNo || "-" }}</el-descriptions-item>
          <el-descriptions-item label="生产起始时间">{{ form.orderStartDate || "-" }}</el-descriptions-item>
          <el-descriptions-item label="生产结束时间">{{ form.orderEndDate || "-" }}</el-descriptions-item>
          <el-descriptions-item label="生产数量">{{ getMoney(form.num) }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ form.remark || "-" }}</el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">货品列表</el-divider>
        <el-table :data="form.goods" border stripe style="width: 100%;">
          <el-table-column label="货品编号" prop="goodsNum" fixed width="200" align="center" />
          <el-table-column label="货品名称" prop="goodsName" fixed width="180" align="center" />
          <el-table-column label="规格" prop="goodsSpec" width="180" align="center" />
          <el-table-column label="品种" prop="varietyName" width="180" align="center" />
          <el-table-column label="级别" prop="levelName" width="180" align="center" />
          <el-table-column label="仓库" prop="warehouseName" width="180" align="center" />
          <el-table-column label="批次" prop="batch" width="180" align="center" />
          <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="150" align="center" />
          <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="assistantUnit" width="150" align="center" />
          <el-table-column label="成本" prop="cost" width="150" align="center">
            <template slot-scope="scope">
              <span>{{ getMoney(scope.row.cost) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="白条编号" prop="whiteNum" width="180" align="center" />
          <el-table-column label="货品备注" prop="remark" width="200" align="center" show-overflow-tooltip />
        </el-table>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!isView" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">{{ isView ? "关 闭" : "取 消" }}</el-button>
      </div>
      <query-material ref="query-material" @selectList="getSelectList"></query-material>
    </el-dialog>

    <!-- 批次查询（接口未接：先写死数据；按当前行货品编号过滤；单选） -->
    <el-dialog
      title="批次查询"
      :visible.sync="batchQueryDialogOpen"
      width="1100px"
      append-to-body
      class="batch-query-dialog"
      @close="onBatchQueryDialogClose"
    >
      <div class="batch-query-tip" v-if="batchQueryGoodsNum">
        当前货品编号：<strong>{{ batchQueryGoodsNum }}</strong>
      </div>
      <el-table
        ref="batchQueryTable"
        :data="batchQueryTableData"
        border
        stripe
        highlight-current-row
        height="400"
        style="width: 100%;"
        @row-click="handleBatchQueryRowClick"
      >
        <el-table-column label="物料编码" prop="goodsNum" align="center" min-width="120" />
        <el-table-column label="物料名称" prop="goodsName" align="center" min-width="140" show-overflow-tooltip />
        <el-table-column label="批次" prop="batch" align="center" min-width="120" />
        <el-table-column label="剩余数量" prop="remainQty" align="center" min-width="100" />
        <el-table-column label="单位" prop="unit" align="center" width="80" />
        <el-table-column label="供应商采购单号" prop="supplierPoNo" align="center" min-width="160" show-overflow-tooltip />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleBatchQueryConfirm">确 定</el-button>
        <el-button @click="batchQueryDialogOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { formatMoney, formatDateYMS, getFindByKey } from "../../../utils";
import { getVarietyList } from "../../../api/baseInfo/variety";
import { getLevelList } from "../../../api/baseInfo/level";
import { getWareHouseList } from "../../../api/inventory/wareHouse";
import { getPlanPage, addPlan, editPlan, delPlan, getPlanById } from "../../../api/production/plan";
import queryMaterial from "../../components/queryMaterial.vue";

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

          // 禁用今天之后的日期
          return time.getTime() > today.getTime();
        }
      },
      // 表单参数
      form: {},
      /** 主表单校验（不含货品列表 goods；goods 仅在生产类型为 '1' 时由 computed formRules 合并） */
      baseFormRules: {
        orderDate: [
          { required: true, message: "请选择生产日期", trigger: "change" },
        ],
        orderNum: [
          { required: true, message: "请输入单据编号", trigger: "blur" },
        ],
        productionType: [
          { required: true, message: "请选择生产类型", trigger: "change" },
        ],
        productionPlantNo: [
          { required: true, message: "请选择生产车间", trigger: "change" },
        ],
        orderStartDate: [
          { required: true, message: "请选择生产起始时间", trigger: "change" },
        ],
        orderEndDate: [
          { required: true, message: "请选择生产结束时间", trigger: "change" },
        ],
      },
      /** 生产类型为 '1' 时合并进 formRules：至少一条货品 */
      goodsListFormRules: [
        {
          validator: (rule, value, callback) => {
            if (!value || value.length === 0) {
              callback(new Error('至少需要一件货品'));
            } else {
              callback();
            }
          },
          trigger: 'change'
        }
      ],
      /** 货品表格行内校验规则（仅生产类型 '1' 时通过 computed rules 生效） */
      goodsTableRules: {
        goodsNum: [
          { required: true, message: "货品编号不能为空", trigger: ["blur", "change"] },
        ],
        goodsName: [
          { required: true, message: "货品名称不能为空", trigger: ["blur", "change"] },
        ],
        goodsSpec: [],
        varietyNo: [
          { required: true, message: "请选择品种", trigger: "change" },
        ],
        levelNo: [],
        warehouseName: [
          { required: true, message: "请选择仓库", trigger: "change" },
        ],
        batch: [
          { required: true, message: "请输入批次", trigger: ["blur", "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)) {
                callback(new Error("基本计量数量格式不正确"));
                return;
              }
              callback();
            },
            trigger: ["change", "blur"],
          },
        ],
        baseUnit: [],
        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)) {
                callback(new Error("辅助计量数量格式不正确"));
                return;
              }
              callback();
            },
            trigger: ["change", "blur"],
          },
        ],
        assistantUnit: [],
        cost: [],
        whiteNum: [],
        remark: [],
      },
      goodsIndex: null,
      wareList: [],
      levelList: [],
      productionPlantList: [
        {
          productionPlantNo: '001',
          productionPlantName: '常规生产车间'
        }
      ],
      varietyList: [],
      // 批次查询弹框
      batchQueryDialogOpen: false,
      /** 当前操作的是货品列表第几行 */
      batchQueryGoodsRowIndex: null,
      /** 打开弹框时带入的货品编号（展示用） */
      batchQueryGoodsNum: "",
      /** 弹框表格数据（由 mock 按货品编号过滤） */
      batchQueryTableData: [],
      /** 当前选中的批次行（单选） */
      batchQuerySelectedRow: null,
      /**
       * 批次列表 mock（后续替换为接口）
       * 字段：物料编码、物料名称、批次、剩余数量、单位、供应商采购单号
       */
      mockBatchList: [
        {
          goodsNum: "001001",
          goodsName: "外三元生猪",
          batch: "PC20250301-01",
          remainQty: 120.5,
          unit: "kg",
          supplierPoNo: "CG20250301001",
        },
        {
          goodsNum: "001001",
          goodsName: "外三元生猪",
          batch: "PC20250301-02",
          remainQty: 88,
          unit: "kg",
          supplierPoNo: "CG20250301002",
        },
        {
          goodsNum: "002",
          goodsName: "外三元一级白条",
          batch: "PC20250302-01",
          remainQty: 200,
          unit: "件",
          supplierPoNo: "CG20250302001",
        },
      ],
    }
  },
  computed: {
    /** 生产类型为字典值 '1' 时才校验货品列表（formRules.goods）及表格行内 rules */
    isProductionTypeRegular() {
      const v = this.form && this.form.productionType
      return String(v != null ? v : "") === "1"
    },
    /** 合并主表单规则：仅常规生产追加 goods 至少一条校验 */
    formRules() {
      const merged = { ...this.baseFormRules }
      if (this.isProductionTypeRegular) {
        merged.goods = this.goodsListFormRules
      }
      return merged
    },
    /**
     * 货品表格 el-form-item 的 :rules
     * 非常规生产时返回各字段空规则，避免行内必填与「至少一件货品」生效。
     */
    rules() {
      if (!this.isProductionTypeRegular) {
        const empty = {}
        Object.keys(this.goodsTableRules).forEach((k) => {
          empty[k] = []
        })
        return empty
      }
      return this.goodsTableRules
    },
  },
  watch: {
    /** 切换生产类型后清掉表单校验态，避免从常规切走后仍显示货品红字 */
    "form.productionType"() {
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    "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
    },
  },
  created() {
    this.getWarehouse()
    this.getLevel()
    this.getVariety();
    this.getList();
  },
  methods: {
    getMoney(val) {
      return formatMoney(val)
    },
    goNext(event, nextRef) {
      event.preventDefault();
      this.$refs[nextRef].focus();
    },
    /** 仓库列表 **/
    getWarehouse() {
      getWareHouseList({}).then(res => {
        this.wareList = res.data
      })
    },
    /** 级别 **/
    getLevel() {
      getLevelList({}).then(res => {
        this.levelList = res.data
      })
    },
    /** 品种 **/
    getVariety() {
      getVarietyList({}).then(res => {
        this.varietyList = res.data
      })
    },
    /**生产车间**/
    changeProductionPlant(val) {
      let item = getFindByKey(this.productionPlantList, val, 'productionPlantNo')
      if(item) {
        this.form.productionPlantName = item.productionPlantName
      }
    },
    /** 查询检验项目列表 */
    getList() {
      getPlanPage(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,
        orderNum: null,
        timeRange: null,
        startTime: null,
        endTime: null,
      }
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isView = false;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      let params = {
        id: id
      }
      getPlanById(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
      }
      getPlanById(params).then(res => {
        this.form = res.data;
        this.open = true;
        this.isView = true;
        this.title = "查看"
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      const tomorrow = formatDateYMS(new Date().getTime() + 1000 * 60 * 60 * 24);
      this.form = {
        id: null,
        orderDate: tomorrow,
        orderNum: null,
        productionType: null,
        productionPlantNo: null,
        productionPlantName: null,
        orderStartDate: tomorrow,
        orderEndDate: tomorrow,
        num: null,
        remark: null,
        goods: [
          {
            goodsNum: null,
            goodsName: null,
            goodsSpec: null,
            levelNo: null,
            levelName: null,
            varietyNo: null,
            varietyName: null,
            warehouseNo: null,
            warehouseName: null,
            batch: null,
            baseNum: null,
            baseUnit: null,
            assNum: null,
            assistantUnit: null,
            cost: null,
            whiteNum: null,
            remark: null,
            conversionValue: null
          }
        ]
      };
      this.resetForm("form");
    },
    // 打开物料速查表
    openQueryMaterial(index) {
      this.goodsIndex = index
      this.$refs['query-material'].open()
    },
    /** 打开批次查询：按当前行货品编号过滤 mock 列表，单选 */
    openBatchQueryDialog(rowIndex) {
      const row = this.form.goods && this.form.goods[rowIndex];
      const goodsNum =
        row && row.goodsNum != null && String(row.goodsNum).trim() !== ""
          ? String(row.goodsNum).trim()
          : "";
      if (!goodsNum) {
        this.$message.warning("请先填写或选择货品编号");
        return;
      }
      this.batchQueryGoodsRowIndex = rowIndex;
      this.batchQueryGoodsNum = goodsNum;
      this.batchQuerySelectedRow = null;
      this.batchQueryTableData = (this.mockBatchList || []).filter(
        (item) =>
          item && String(item.goodsNum || "").trim() === goodsNum
      );
      this.batchQueryDialogOpen = true;
      this.$nextTick(() => {
        if (this.$refs.batchQueryTable) {
          this.$refs.batchQueryTable.setCurrentRow(null);
        }
      });
    },
    handleBatchQueryRowClick(row) {
      this.batchQuerySelectedRow = row;
      this.$nextTick(() => {
        if (this.$refs.batchQueryTable) {
          this.$refs.batchQueryTable.setCurrentRow(row);
        }
      });
    },
    handleBatchQueryConfirm() {
      const sel = this.batchQuerySelectedRow;
      if (!sel) {
        this.$message.warning("请选择一条批次记录");
        return;
      }
      const idx = this.batchQueryGoodsRowIndex;
      if (idx == null || !this.form.goods || !this.form.goods[idx]) {
        this.batchQueryDialogOpen = false;
        return;
      }
      const row = this.form.goods[idx];
      const assNum = Number(sel.remainQty);
      const conv = Number(row.conversionValue != null ? row.conversionValue : 1);

      // 回填：批次、辅助计量数量
      row.batch = sel.batch;
      row.assNum = Number.isFinite(assNum) ? assNum : null;
      // 基本计量数量 = 辅助计量数量 * 换算值(conversionValue)
      row.baseNum =
        row.assNum != null && Number.isFinite(conv) ? row.assNum * conv : null;

      this.handleEdit(idx, "batch", row.batch);
      this.handleEdit(idx, "assNum", row.assNum);
      this.handleEdit(idx, "baseNum", row.baseNum);
      this.batchQueryDialogOpen = false;
    },
    onBatchQueryDialogClose() {
      this.batchQuerySelectedRow = null;
      this.batchQueryGoodsRowIndex = null;
      this.batchQueryTableData = [];
    },
    handleAddRow() {
      let row = {
        goodsNum: null,
        goodsName: null,
        goodsSpec: null,
        levelNo: null,
        levelName: null,
        varietyNo: null,
        varietyName: null,
        warehouseNo: null,
        warehouseName: null,
        batch: null,
        baseNum: null,
        baseUnit: null,
        assNum: null,
        assistantUnit: null,
        cost: null,
        whiteNum: null,
        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 === "assNum") {
        const row = this.form.goods[index] || {};
        const conv = Number(row.conversionValue != null ? row.conversionValue : 1);
        const ass = value === null || value === undefined || value === "" ? null : Number(value);
        row.baseNum = ass != null && Number.isFinite(ass) && Number.isFinite(conv) ? ass * conv : null;
        this.$nextTick(() => {
          this.$refs.form.validateField(`goods.${index}.baseNum`);
        });
      }

      if (field === "warehouseName") {
        const item = getFindByKey(this.wareList, value, "warehouseName");
        if (item) {
          this.form.goods[index].warehouseNo = item.warehouseNo;
        }
      }
      if (field === "varietyNo") {
        const item = getFindByKey(this.varietyList, value, "varietyNo");
        if (item) {
          this.form.goods[index].varietyName = item.varietyName;
        }
      }
      if (field === "levelNo") {
        const item = getFindByKey(this.levelList, value, "levelNo");
        if (item) {
          this.form.goods[index].levelName = item.levelName;
        }
      }
    },
    handleDeleteRow(index) {
      this.$confirm('确定要删除该货品吗？','提示', {
        type: 'warning'
      }).then(() => {
        this.form.goods.splice(index, 1)
        this.$message.success('删除成功')
      })
    },
    // 验证表格行（仅生产类型为常规 '1' 时与 rules 一致）
    validateTableRow(rowIndex) {
      if (!this.isProductionTypeRegular) return
      const fields = [
        "goodsNum",
        "goodsName",
        "varietyNo",
        "warehouseName",
        "batch",
        "baseNum",
        "assNum",
      ];
      fields.forEach((field) => {
        this.$refs.form.validateField(`goods.${rowIndex}.${field}`);
      });
    },
    /**
     * 判断货品行是否「整行无有效数据」（与 reset 默认行字段一致，用于非常规生产提交前整理）。
     */
    isGoodsRowAllEmpty(row) {
      if (!row || typeof row !== "object") return true
      const keys = [
        "goodsNum",
        "goodsName",
        "goodsSpec",
        "levelNo",
        "levelName",
        "varietyNo",
        "varietyName",
        "warehouseNo",
        "warehouseName",
        "batch",
        "baseNum",
        "baseUnit",
        "assNum",
        "assistantUnit",
        "cost",
        "whiteNum",
        "remark",
        "conversionValue",
      ]
      return keys.every((k) => {
        const v = row[k]
        return v === null || v === undefined || v === ""
      })
    },
    /**
     * 非常规生产：若 goods 中每一行都是「全空」，提交前置为 []，避免带占位空行。
     */
    applyEmptyGoodsWhenNotRegular() {
      if (this.isProductionTypeRegular) return
      const list = Array.isArray(this.form.goods) ? this.form.goods : []
      if (list.length > 0 && list.every((row) => this.isGoodsRowAllEmpty(row))) {
        this.form.goods = []
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.applyEmptyGoodsWhenNotRegular()
          if (this.form.id != null) {
            // 编辑
            editPlan(this.form).then(res => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          } else {
            // 新增
            addPlan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      let params = {
        ids: ids
      }
      delPlan(params).then(res => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      })
    },
    /** 删除按钮操作 */
    handleDeleteAll() {
      const ids = this.ids;
      this.$modal.confirm('确定要删除这条数据吗？').then(() => {
        let params = {
          ids: ids.join(',')
        }
        delPlan(params).then(res => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.$refs.multipleTable.clearSelection();
        })
      })
    },
    getSelectList(list) {
      if(list.length === 0) {
        this.form.goods = []
      } else if(list.length === 1) {
        this.form.goods.splice(this.goodsIndex, 1, {
          goodsNum: list[0].goodsNum,
          goodsName: list[0].goodsName,
          goodsSpec: list[0].goodsSpec,
          levelNo: list[0].goodsLevel,
          levelName: list[0].goodsLevelName,
          varietyNo: list[0].variety,
          varietyName: list[0].varietyName,
          warehouseNo: list[0].warehouseNum,
          warehouseName: list[0].warehouseName,
          batch: null,
          baseNum: null,
          baseUnit: list[0].unit,
          assNum: null,
          assistantUnit: list[0].assistantUnit,
          cost: null,
          whiteNum: null,
          remark: null,
          conversionValue: list[0].conversionValue
        })
      } else if(list.length > 1) {
        this.form.goods.splice(this.goodsIndex, 1, {
          goodsNum: list[0].goodsNum,
          goodsName: list[0].goodsName,
          goodsSpec: list[0].goodsSpec,
          levelNo: list[0].goodsLevel,
          levelName: list[0].goodsLevelName,
          varietyNo: list[0].variety,
          varietyName: list[0].varietyName,
          warehouseNo: list[0].warehouseNum,
          warehouseName: list[0].warehouseName,
          batch: null,
          baseNum: null,
          baseUnit: list[0].unit,
          assNum: null,
          assistantUnit: list[0].assistantUnit,
          cost: null,
          whiteNum: null,
          remark: null,
          conversionValue: list[0].conversionValue
        })
        for(let i = 1; i<list.length; i++) {
          this.form.goods.push({
            goodsNum: list[i].goodsNum,
            goodsName: list[i].goodsName,
            goodsSpec: list[i].goodsSpec,
            levelNo: list[i].goodsLevel,
            levelName: list[i].goodsLevelName,
            varietyNo: list[i].variety,
            varietyName: list[i].varietyName,
            warehouseNo: list[i].warehouseNum,
            warehouseName: list[i].warehouseName,
            batch: null,
            baseNum: null,
            baseUnit: list[i].unit,
            assNum: null,
            assistantUnit: list[i].assistantUnit,
            cost: null,
            whiteNum: null,
            remark: null,
            conversionValue: list[i].conversionValue
          })
        }
      }
    }
  },
}
</script>

<style scoped lang="scss">
// 表格内嵌 el-form-item 时，避免单元格裁剪校验错误文字
::v-deep .el-table td {
  overflow: visible !important;
}
::v-deep .el-table .el-form-item__error {
  position: static !important;
  white-space: nowrap;
}

.batch-query-tip {
  margin-bottom: 10px;
  font-size: 13px;
  color: #606266;
}

::v-deep .batch-query-dialog .el-table__body tr.current-row > td {
  background-color: #d9ecff !important;
}
</style>

