<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="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-form-item>
        <el-form-item label="业务员" prop="employeeName">
          <el-input
            v-model="queryParams.employeeName"
            placeholder="请输入业务员"
            clearable
          />
        </el-form-item>
        <el-form-item label="报价单名称" prop="quotationName">
          <el-input
            v-model="queryParams.employeeName"
            placeholder="请输入业务员"
            clearable
          />
        </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" width="150" fixed prop="quotationName" />
        <el-table-column label="单据编号" align="center" width="200" fixed prop="quotationNum" />
        <el-table-column label="拷贝单号" align="center" width="200" prop="copyNum" />
        <el-table-column label="单据日期" align="center" width="180" prop="documentDate" />
        <el-table-column label="报价日期" align="center" width="180" prop="quotationDate" />
        <el-table-column label="供应商编号" align="center" width="150" prop="supplierNum" />
        <el-table-column label="供应商简称" align="center" width="150" prop="supplierName" />
        <el-table-column label="供应商电话" align="center" width="150" prop="supplierName" />
        <el-table-column label="业务员" align="center" width="150" prop="employeeName" />
        <el-table-column label="备注1" align="center" width="200" prop="remark1" />
        <el-table-column label="备注2" align="center" width="200" prop="remark2" />
        <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" fixed="right" width="150" prop="totalAmount">
          <template slot-scope="scope">
            <span>{{getMoney(scope.row.totalAmount)}}</span>
          </template>
        </el-table-column>
<!--        <el-table-column label="备注" align="center" prop="remark" />-->
        <el-table-column label="操作" width="180" fixed="right" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <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 ref="form" v-if="!isView" :model="form" :rules="formRules" :disabled="isView" label-width="100px">
        <el-row>
          <el-col :span="16">
            <el-form-item label="报价单名称" prop="quotationName">
              <el-input
                ref="quotationName"
                v-model="form.quotationName"
                placeholder="请输入报价单名称"
                @keydown.enter.native="goNext($event, 'quotationNum')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="拷贝单号" prop="copyNum">
              <el-input
                ref="copyNum"
                v-model="form.copyNum"
                placeholder="请输入拷贝单号"
                @keydown.enter.native="goNext($event, 'quotationNum')"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="单据编号" prop="quotationNum">
              <el-input
                ref="quotationNum"
                v-model="form.quotationNum"
                placeholder="请输入单据编号"
                @keydown.enter.native="goNext($event, 'documentDate')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据日期" prop="documentDate">
              <el-date-picker
                ref="documentDate"
                style="width: 100%;"
                v-model="form.documentDate"
                value-format="yyyy-MM-dd"
                placeholder="请选择单据日期"
                @keydown.enter.native="goNext($event, 'quotationDate')"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="报价日期" prop="quotationDate">
              <el-date-picker
                ref="quotationDate"
                style="width: 100%;"
                v-model="form.quotationDate"
                placeholder="请选择单据日期"
                @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="supplierPhone">
              <el-input disabled v-model="form.supplierPhone" placeholder="选择供应商名称自动填充"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <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-col :span="16">
            <el-form-item label="备注1" prop="remark1">
              <el-input ref="remark1" v-model="form.remark1" placeholder="请输入备注"></el-input>
            </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 min-width="160" 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 min-width="120" 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="请输入货品名称"
                      disabled
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="规格" prop="goodsSpec" min-width="100" 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="请输入规格"
                      disabled
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="仓库" prop="warehouseName" min-width="120" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.warehouseName`"
                    :rules="rules.warehouseName"
                    class="table-form-item"
                  >
                    <el-input
                      v-model="row.warehouseName"
                      placeholder="请输入仓库"
                      disabled
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="基本计量数量" prop="baseNum" min-width="120" 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"
                      disabled
                      :min="0"
                      :max="999999"
                      :precision="2"
                      placeholder="请输入基本计量数量"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="基本计量单位" prop="baseUnit" min-width="100" 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="请输入基本计量单位"
                      disabled
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="辅助计量数量" prop="assNum" min-width="120" 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"
                      :precision="2"
                      :min="0"
                      :max="999999"
                      placeholder="请输入辅助计量数量"
                      @change="handleEdit($index, 'assNum', row.assNum)"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="辅助计量单位" prop="assUnit" min-width="100" 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="请输入辅助计量单位"
                      disabled
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="单价(元)" prop="unitPrice" min-width="100" align="center" fixed="right">
                <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" min-width="100" align="center" fixed="right">
                <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="操作" 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-row>
          <el-col :span="8">
            <el-form-item label="总金额" prop="totalAmount">
              <decimal-input v-model="form.totalAmount" :min="0" :max="999999" :precision="2" placeholder="请输入总金额" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注2" prop="remark2">
              <el-input ref="remark2" v-model="form.remark2" placeholder="请输入备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-form-item label="处理方式" prop="dealWay">-->
        <!--          <el-input type="textarea" v-model="form.dealWay" maxlength="50" show-word-limit placeholder="请输入处理方式" />-->
        <!--        </el-form-item>-->
      </el-form>
      <template v-else>
        <el-descriptions border>
          <el-descriptions-item label="报价单名称">{{form.quotationName}}</el-descriptions-item>
          <el-descriptions-item label="单据编号">{{form.quotationNum}}</el-descriptions-item>
          <el-descriptions-item v-if="form.copyNum" label="拷贝单号">{{form.copyNum}}</el-descriptions-item>
          <el-descriptions-item label="单据日期">{{form.documentDate}}</el-descriptions-item>
          <el-descriptions-item label="报价日期">{{form.quotationDate}}</el-descriptions-item>
          <el-descriptions-item label="供应商编号">{{form.supplierNum}}</el-descriptions-item>
          <el-descriptions-item label="供应商名称">{{form.supplierName}}</el-descriptions-item>
          <el-descriptions-item label="供应商电话">{{form.supplierPhone}}</el-descriptions-item>
          <el-descriptions-item label="业务员">{{form.employeeName}}</el-descriptions-item>
          <el-descriptions-item label="备注1">{{form.remark1}}</el-descriptions-item>
          <el-descriptions-item label="备注2">{{form.remark2}}</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  align="center"></el-table-column>
          <el-table-column label="货品名称" prop="goodsName" fixed  align="center"></el-table-column>
          <el-table-column label="规格" prop="goodsSpec"  align="center"></el-table-column>
          <el-table-column label="仓库" prop="warehouseName" align="center"></el-table-column>
          <el-table-column label="基本计量数量" prop="baseNum"  align="center">
            <template slot-scope="scope">
              <span>{{getMoney(scope.row.baseNum)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="基本计量单位" prop="baseUnit"  align="center"></el-table-column>
          <el-table-column label="辅助计量数量" prop="assNum"  align="center">
            <template slot-scope="scope">
              <span>{{getMoney(scope.row.assNum)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="辅助计量单位" prop="assUnit"  align="center"></el-table-column>
          <el-table-column label="单价(元)" prop="unitPrice" sortable  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  align="center" fixed="right">
            <template slot-scope="scope">
              <span>{{getMoney(scope.row.amount)}}</span>
            </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>
  </div>
</template>
<script>
import { getPurchaseQuotationPage, getPurchaseQuotationById, addPurchaseQuotation, editPurchaseQuotation, delPurchaseQuotation, getQuotationNum } from "@/api/purchase/purchaseQuotation";
import { getSupplierList } from "@/api/purchase/supplier";
import { getStaffList } from "@/api/baseInfo/staff";
import { formatMoney, formatDateYMS, getFindByKey } from "@/utils";
import queryMaterial from "../../components/queryMaterial.vue";

export default {
  name: "PurchaseQuotation",
  components: {
    queryMaterial
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      disposalList: [],
      // 弹出层标题
      title: "",
      isView:false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplierName: null,
        employeeName: null,
        quotationName: 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: {},
      formRules: {
        quotationName: [{ required: true, message: '请输入报价单名称', trigger: 'blur' }],
        quotationNum: [{ required: true, message: '请输入单据编号', trigger: 'blur' }],
        documentDate: [{ required: true, message: '请选择单据日期', trigger: 'change' }],
        quotationDate: [{ required: true, message: '请选择报价日期', trigger: 'change' }],
        supplierName: [{ required: true, message: '请选择供应商名称', trigger: 'change' }],
        employeeNum: [{ required: true, message: '请选择业务员', trigger: 'change' }],
        totalAmount: [{ 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: 'blur' },
        ],
        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",
          },
        ],
      },
      supplierList: [],
      staffList: [],
      goodsIndex: null
    }
  },
  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 = null
        newVal.forEach(item => {
          amount += item.amount || 0
        })
        this.form.totalAmount = amount
      },
      deep: true
    },
  },
  created() {
    this.getSupplier()
    this.getStaff()
    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();
    },
    /** 业务员 **/
    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
      }
    },
    /** 供应商 **/
    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
      }
    },
    /** 查询检验项目列表 */
    getList() {
      getPurchaseQuotationPage(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,
        supplierName: 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
    },
    /** 获取最新报价单编号 **/
    initNum() {
      getQuotationNum({}).then(res => {
        this.form.quotationNum = 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
      }
      getPurchaseQuotationById(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
      }
      getPurchaseQuotationById(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,
        quotationNum: null,
        quotationName: null,
        copyNum: null,
        // 往后一天
        documentDate: formatDateYMS(new Date().getTime() + 1000 * 60 * 60 * 24),
        quotationDate: formatDateYMS(new Date().getTime() + 1000 * 60 * 60 * 24),
        supplierNum: null,
        supplierName: null,
        supplierPhone: null,
        employeeNum: null,
        employeeName: null,
        remark2: null,
        remark1: null,
        goods: [
          {
            goodsNum: null,
            goodsName: null,
            goodsSpec: null,
            warehouseName: null,
            baseNum: null,
            baseUnit: null,
            assNum: null,
            assUnit: null,
            conversionValue: null,
            unitPrice: null,
            amount: null
          }
        ],
        totalAmount: null
      };
      this.resetForm("form");
    },
    handleAddRow() {
      let row = {
        goodsNum: null,
        goodsName: null,
        goodsSpec: null,
        warehouseName: null,
        baseNum: null,
        baseUnit: null,
        assNum: null,
        assUnit: null,
        conversionValue: null,
        unitPrice: null,
        amount: null
      }
      this.form.goods.push(row)
      setTimeout(() => {
        this.validateTableRow(this.form.goods.length - 1)
      }, 0)
    },
    // 处理编辑
    handleEdit(index, field, value) {
      console.log(`编辑第 ${index} 行，字段: ${field}，值: ${value}`);

      // 触发对应字段的校验
      this.$refs.form.validateField(`goods.${index}.${field}`);

      const row = this.form.goods[index];

      // 辅助计量数量变化：baseNum = assNum * conversionValue
      if (field === "assNum") {
        const conv = row.conversionValue != null ? Number(row.conversionValue) : 1;
        const ass = row.assNum != null ? Number(row.assNum) : 0;
        const base = Number.isFinite(conv) ? ass * conv : 0;
        this.$set(row, "baseNum", base.toFixed(2));
        // 触发 baseNum 校验（即便输入框只读，校验也需要更新）
        this.$refs.form.validateField(`goods.${index}.baseNum`);
      }

      // 自动计算金额：amount = baseNum * unitPrice
      if (field === "unitPrice" || field === "baseNum" || field === "assNum") {
        row.amount = (Number(row.unitPrice) || 0) * (Number(row.baseNum) || 0);
      }
    },
    handleDeleteRow(index) {
      this.$confirm('确定要删除该货品吗？','提示', {
        type: 'warning'
      }).then(() => {
        this.form.goods.splice(index, 1)
        this.$message.success('删除成功')
      })
    },
    // 验证表格行
    validateTableRow(rowIndex) {
      const fields = ['goodsName', 'unitPrice', 'baseNum'];
      fields.forEach(field => {
        this.$refs.form.validateField(`goodsList.${rowIndex}.${field}`);
      });
    },
    /**
     * 提交前清理：删除“整行全空”的货品行
     * 规则：除 conversionValue 外，只要该行所有字段都是 null 或空字符串，则删除该行
     */
    cleanupEmptyGoodsRows() {
      const isEmpty = (v) => v === null || v === undefined || (typeof v === "string" && v.trim() === "");
      const ignoreKeys = new Set(["conversionValue"]);
      const list = this.form && Array.isArray(this.form.goods) ? this.form.goods : [];
      const cleaned = list.filter((row) => {
        const r = row || {};
        const keys = Object.keys(r).filter((k) => !ignoreKeys.has(k));
        if (!keys.length) return false;
        return keys.some((k) => !isEmpty(r[k]));
      });
      this.form.goods = cleaned;
    },
    /** 提交按钮 */
    submitForm() {
      this.cleanupEmptyGoodsRows();
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 编辑
            editPurchaseQuotation(this.form).then(res => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          } else {
            // 新增
            addPurchaseQuotation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      let params = {
        ids: ids
      }
      delPurchaseQuotation(params).then(res => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      })
    },
    /** 删除按钮操作 */
    handleDeleteAll() {
      const ids = this.ids;
      this.$modal.confirm('确定要删除这条数据吗？').then(() => {
        let params = {
          ids: ids.join(',')
        }
        delPurchaseQuotation(params).then(res => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.$refs.multipleTable.clearSelection();
        })
      })
    },
    // 打开物料速查表
    openQueryMaterial(index) {
      this.goodsIndex = index
      this.$refs['query-material'].open()
    },
    // 拿到物料
    getSelectList(list) {
      const safeGoodsIndex = this.goodsIndex == null ? 0 : this.goodsIndex;
      const currentRow = (this.form && this.form.goods && this.form.goods[safeGoodsIndex]) || {};

      const normalized = (list || []).filter((x) => x && x.goodsNum != null);
      if (normalized.length === 0) {
        this.form.goods = [];
        return;
      }

      // 计算：当前行之外已经存在的货品集合
      const existedSet = new Set(
        (this.form.goods || [])
          .map((g, idx) => (idx === safeGoodsIndex ? null : g && g.goodsNum))
          .filter((v) => v !== null && v !== undefined && v !== "")
      );

      // 单选：若货品已存在（含当前行），则忽略本次选择
      if (normalized.length === 1) {
        const chosen = normalized[0];
        const chosenNo = chosen.goodsNum;
        if (existedSet.has(chosenNo) || currentRow.goodsNum === chosenNo) {
          this.$message.warning("该货品已存在，已忽略本次选择");
          return;
        }
        this.form.goods.splice(safeGoodsIndex, 1, {
          goodsNum: chosen.goodsNum,
          goodsName: chosen.goodsName,
          goodsSpec: chosen.goodsSpec,
          warehouseName: chosen.warehouseName,
          baseNum: null,
          baseUnit: chosen.unit,
          assNum: null,
          assUnit: chosen.assistantUnit,
          conversionValue: chosen.conversionValue != null ? chosen.conversionValue : 1,
          unitPrice: null,
          amount: null
        });
        return;
      }

      // 多选：先过滤掉已存在的重复项
      const filtered = [];
      const seen = new Set();
      normalized.forEach((item) => {
        const no = item.goodsNum;
        if (seen.has(no)) return;
        seen.add(no);
        if (existedSet.has(no)) return;
        filtered.push(item);
      });

      if (filtered.length === 0) {
        this.$message.warning("所选货品均已存在，已忽略本次选择");
        return;
      }

      // 按原逻辑：当前行放第一个，其它追加
      this.form.goods.splice(safeGoodsIndex, 1, {
        goodsNum: filtered[0].goodsNum,
        goodsName: filtered[0].goodsName,
        goodsSpec: filtered[0].goodsSpec,
        warehouseName: filtered[0].warehouseName,
        baseNum: null,
        baseUnit: filtered[0].unit,
        assNum: null,
        assUnit: filtered[0].assistantUnit,
        conversionValue: filtered[0].conversionValue != null ? filtered[0].conversionValue : 1,
        unitPrice: null,
        amount: null
      });

      for (let i = 1; i < filtered.length; i++) {
        this.form.goods.push({
          goodsNum: filtered[i].goodsNum,
          goodsName: filtered[i].goodsName,
          goodsSpec: filtered[i].goodsSpec,
          warehouseName: filtered[i].warehouseName,
          baseNum: null,
          baseUnit: filtered[i].unit,
          assNum: null,
          assUnit: filtered[i].assistantUnit,
          conversionValue: filtered[i].conversionValue != null ? filtered[i].conversionValue : 1,
          unitPrice: null,
          amount: null
        });
      }
    },
  },
}
</script>

<style scoped lang="scss">
/* 移除表格中表单元素的内边距 */
.table-form-item {
  margin-bottom: 0;
}

/* 调整表格中表单元素的大小 */
.table-form-item ::v-deep .el-form-item__content {
  margin-left: 0 !important;
  line-height: normal;
}

/* 表格中input的样式 */
.el-table .el-input,
.el-table .el-input-number {
  width: 100%;
}

/* 错误行的样式 */
.el-table .error-row {
  background-color: #fef0f0;
}

.el-table .error-row:hover > td {
  background-color: #fde2e2;
}

/* 警告行的样式 */
.el-table .warning-row {
  background-color: #fdf6ec;
}

.el-table .warning-row:hover > td {
  background-color: #faecd8;
}

/* 操作按钮样式 */
.table-actions {
  display: flex;
  justify-content: center;
  gap: 8px;
}
</style>
