<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="表单编号" prop="formCode">
              <el-input v-model="queryParams.formCode" placeholder="请输入表单编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
             <el-form-item label="材料来源" prop="materialSource">
              <el-select v-model="queryParams.materialSource" filterable placeholder="请选择材料来源">
                <el-option label="全部" value="0"></el-option>
                <el-option label="甲供材料" value="1"></el-option>
                <el-option label="乙供材料" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="材料名称" prop="materialName">
              <el-input v-model="queryParams.materialName" placeholder="请输入设备材料名称" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="订货单位" prop="orderingUnit">
              <el-input v-model="queryParams.orderingUnit" placeholder="请输入订货单位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供货单位" prop="supplierUnit">
              <el-input v-model="queryParams.supplierUnit" placeholder="请输入供货单位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['materials:materialReceive:add']">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="materialReceiveList" @selection-change="handleSelectionChange">
        <el-table-column type="index" width="60" label="序号" align="center" />
        <el-table-column label="表单编号" align="center" prop="formCode" />
        <el-table-column label="材料来源" align="center" prop="projectName">
          <template #default="scope">
            <el-tag :type="scope.row.materialSource == '1' ? 'success' : 'warning'">{{ scope.row.materialSource == '1' ?
              '甲供材料' : '乙供材料' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="设备材料名称" align="center" prop="materialName" />
        <el-table-column label="合同名称" align="center" prop="contractName" />
        <el-table-column label="订货单位" align="center" prop="orderingUnit">
          <template #default="scope">
            <span>{{ scope.row.orderingUnit || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="供货单位" align="center" prop="supplierUnit">
          <template #default="scope">
            <span>{{ scope.row.supplierUnit || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="设备材料入库/移交" align="center" prop="storageType">
          <template #default="scope">
            <dict-tag :options="storage_type" :value="scope.row.storageType" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" min-width="120" fixed="right">
          <template #default="scope">
            <!-- <el-button link type="primary" icon="edit" @click="handleUpdate(scope.row)" v-hasPermi="['materials:materialReceive:edit']"
              >修改</el-button
            > -->
            <el-button link type="primary" icon="View" @click="handleView(scope.row)"
              v-hasPermi="['materials:materialReceive:query']">查看</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['materials:materialReceive:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改物料接收单对话框 -->
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" draggable :title="dialog.title"
      v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="materialReceiveFormRef" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="材料来源" prop="materialSource">
              <el-select v-model="form.materialSource" filterable placeholder="请选择材料来源" style="width: 100%">
                <el-option label="甲供材料" value="1"></el-option>
                <el-option label="乙供材料" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表单编号" prop="formCode">
              <el-input v-model="form.formCode" placeholder="请输入表单编号" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.materialSource == '2'" :span="12">
            <el-form-item label="采购单编号" prop="docId">
              <el-select @change="handleSelect" v-model="form.docId" filterable placeholder="请选择采购单"
                style="width: 100%">
                <el-option v-for="item in purchaseDocList" :key="item.id" :label="item.docCode"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="form.materialSource == '2'" :span="12">
            <el-form-item label="供货单位" prop="supplierUnit">
              <el-input disabled v-model="form.supplierUnit" placeholder="请输入供货单位" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.materialSource == '2'" :span="12">
            <el-form-item label="订货单位" prop="orderingUnit">
              <el-input v-model="form.orderingUnit" placeholder="请输入订货单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工程名称" prop="projectName">
              <el-input disabled v-model="form.projectName" placeholder="请输入工程名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.materialSource == '2'">
            <el-form-item label="合同编号" prop="contractName">
              <el-select v-model="form.contractName" filterable placeholder="请选择合同" style="width: 100%">
                <el-option v-for="item in contractNameList" :key="item.contractCode" :label="item.contractCode"
                  :value="item.contractCode"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="缺陷情况" prop="defectDescription">
              <el-input v-model="form.defectDescription" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>

          <!-- 数量验收区域 -->
          <el-col :span="24">
            <div class="detail">
              <div class="detail-header">
                <span>数量验收</span>
                <el-button type="primary" v-if="form.materialSource == '1'" link @click="addItem"
                  icon="Plus">添加数量验收</el-button>
              </div>
              <div v-for="(item, index) in form.itemList" :key="item.id" class="detail-item">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="名称" :prop="`itemList.${index}.name`"
                      :rules="{ required: true, message: '名称不能为空', trigger: 'blur' }">
                      <el-input :disabled="form.materialSource == '2'" v-model="item.name" placeholder="请输入名称" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="规格" :prop="`itemList.${index}.specification`"
                      :rules="{ required: true, message: '规格不能为空', trigger: 'blur' }">
                      <el-input :disabled="form.materialSource == '2'" v-model="item.specification"
                        placeholder="请输入规格" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="单位" :prop="`itemList.${index}.unit`"
                      :rules="{ required: true, message: '单位不能为空', trigger: 'blur' }">
                      <el-input :disabled="form.materialSource == '2'" v-model="item.unit" placeholder="请输入单位" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="数量" :prop="`itemList.${index}.quantity`" :rules="rules.quantityRule"
                      ref="quantityFormItemRefs[index]">
                      <el-input :disabled="form.materialSource == '2'" type="number" v-model.number="item.quantity"
                        placeholder="请输入数量" min="0" @input="handleQuantityInput(index)"
                        @blur="handleQuantityBlur(index)" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="验收" :prop="`itemList.${index}.acceptedQuantity`"
                      :rules="rules.acceptedQuantityRule">
                      <el-input type="number" v-model.number="item.acceptedQuantity" placeholder="请输入验收" min="0"
                        @input="handleAcceptedInput(index)" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="缺件" :prop="`itemList.${index}.shortageQuantity`"
                      :rules="{ required: true, message: '缺件数量不能为空', trigger: 'blur' }">
                      <el-input type="number" min="0" v-model="item.shortageQuantity" placeholder="自动计算" readonly />
                      <span class="tips">*自动计算（数量-验收数量）</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="备注" :prop="`itemList.${index}.remark`">
                      <el-input v-model="item.remark" type="textarea" placeholder="请输入备注" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12" v-if="form.itemList.length > 1 && form.materialSource == '1'">
                    <div class="item-actions">
                      <el-button type="danger" link @click="removeItem(index)" icon="Delete">删除</el-button>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </div>
          </el-col>

          <el-col :span="12">
            <el-form-item label="合格证文件" prop="certCountFileId">
              <file-upload :isShowTip="false" :fileType="['pdf', 'png', 'jpg', 'jpeg']"
                v-model="form.certCountFileId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出厂报告文件" prop="reportCountFileId">
              <file-upload :isShowTip="false" :fileType="['pdf', 'png', 'jpg', 'jpeg']"
                v-model="form.reportCountFileId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="技术资料文件" prop="techDocCountFileId">
              <file-upload :isShowTip="false" :fileType="['pdf', 'png', 'jpg', 'jpeg']"
                v-model="form.techDocCountFileId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="厂家资质文件" prop="licenseCountFileId">
              <file-upload :isShowTip="false" :fileType="['pdf', 'png', 'jpg', 'jpeg']"
                v-model="form.licenseCountFileId" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <span style="color: #ff0000ab; margin-bottom: 10px; display: block">注意：pdf/png/jpg/jpeg格式文件</span>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <wordllReceive ref="wordllReceiveRef"></wordllReceive>
  </div>
</template>

<script setup name="MaterialReceive" lang="ts">
import {
  listMaterialReceive,
  getMaterialReceive,
  delMaterialReceive,
  addMaterialReceive,
  updateMaterialReceive,
  getContractNameList
} from '@/api/materials/materialReceive';
import { MaterialReceiveVO, MaterialReceiveQuery, MaterialReceiveForm } from '@/api/materials/materialReceive/types';
import { useUserStoreHook } from '@/store/modules/user';
import wordllReceive from './word/index.vue';
import { listPurchaseDoc, purchaseDocPlanList } from '@/api/materials/purchaseDoc';
import { watch, onMounted, onUnmounted, ref, reactive, computed, toRefs, getCurrentInstance } from 'vue';
import type { ComponentInternalInstance, ElFormInstance, DialogOption, ElFormItem } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { storage_type } = toRefs<any>(proxy?.useDict('storage_type'));
const userStore = useUserStoreHook();
const currentProject = computed(() => userStore.selectedProject);
const wordllReceiveRef = ref<InstanceType<typeof wordllReceive>>();

// 存储每个验收条目的watch停止函数
const itemWatchStopFns = ref<Array<() => void>>([]);
// 存储数量表单项的引用，用于手动触发验证
const quantityFormItemRefs = ref<(ElFormItem | null)[]>([]);

// 列表数据
const materialReceiveList = ref<MaterialReceiveVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 表单引用
const queryFormRef = ref<ElFormInstance>();
const materialReceiveFormRef = ref<ElFormInstance>();
const purchaseDocList = ref([]); // 物资采购单列表
const purchaseMap = new Map(); // 采购单映射（id -> 采购单对象）
const contractNameList = ref([]); //合同列表

// 对话框配置
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 生成验收条目唯一ID
const generateItemId = () => {
  return Date.now() + Math.random().toString(36).substr(2, 9);
};

// 初始化表单数据
const getInitFormData = (): MaterialReceiveForm => {
  return {
    id: undefined,
    projectId: currentProject.value?.id,
    materialSource: '1',
    formCode: undefined,
    projectName: undefined,
    materialName: undefined,
    contractName: undefined,
    orderingUnit: undefined,
    supplierUnit: undefined,
    defectDescription: undefined,
    certCount: undefined,
    certCountFileId: undefined,
    reportCount: undefined,
    reportCountFileId: undefined,
    techDocCount: undefined,
    techDocCountFileId: undefined,
    licenseCount: undefined,
    licenseCountFileId: undefined,
    storageType: '1',
    remark: undefined,
    docId: undefined,
    docCode: undefined,
    itemList: [
      {
        id: generateItemId(),
        name: undefined,
        specification: undefined,
        unit: undefined,
        quantity: undefined,
        acceptedQuantity: undefined,
        shortageQuantity: undefined,
        remark: undefined
      }
    ]
  };
};

// 响应式数据
const data = reactive({
  form: getInitFormData(),
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: currentProject.value?.id,
    materialSource: '0',
    formCode: undefined,
    projectName: undefined,
    materialName: undefined,
    contractName: undefined,
    orderingUnit: undefined,
    supplierUnit: undefined,
    params: {}
  },
  rules: {
    materialSource: [{ required: true, message: '请选择材料来源', trigger: 'change' }],
    formCode: [{ required: true, message: '请输入表单编号', trigger: 'blur' }],
    docId: [{ required: true, message: '请选择物资采购单', trigger: 'change' }],
    supplierUnit: [{ required: true, message: '请输入供货单位', trigger: 'blur' }],
    orderingUnit: [{ required: true, message: '请输入订货单位', trigger: 'blur' }],
    // 数量校验规则：确保触发时机包含change，且类型为number
    quantityRule: [
      { required: true, message: '数量不能为空', trigger: ['blur', 'change'] },
      { type: 'number', min: 0, message: '数量不能小于0', trigger: ['blur', 'change'] }
    ],
    // 验收数量规则（允许≤数量）
    acceptedQuantityRule: [
      { required: true, message: '验收数量不能为空', trigger: ['blur', 'change'] },
      { type: 'number', min: 0, message: '验收数量不能小于0', trigger: ['blur', 'change'] },
      {
        validator: (rule, value, callback) => {
          const prop = rule.field;
          const index = Number(prop.split('.')[1]);
          const quantity = Number(form.value.itemList[index].quantity) || 0;

          // 数量未填写时不验证大小关系；数量有值但验收数量未填时也不阻断（由required规则处理）
          if (form.value.itemList[index].quantity === undefined || form.value.itemList[index].quantity === null) {
            callback();
            return;
          }
          // 处理value为undefined/null的情况（避免Number(undefined)转为NaN）
          const acceptedVal = Number(value) || 0;
          if (acceptedVal > quantity) {
            callback(new Error('验收数量必须小于等于数量'));
          } else {
            callback();
          }
        },
        trigger: ['blur', 'change']
      }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询物料接收单列表 */
const getList = async () => {
  loading.value = true;
  try {
    if(queryParams.value.materialSource=='0'){
      delete queryParams.value.materialSource;
    }
    const res = await listMaterialReceive(queryParams.value);
    materialReceiveList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

// 获取合同列表数据
const getContractList = async () => {
  let res = await getContractNameList(currentProject.value?.id);
  contractNameList.value = res.rows;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  // 停止所有验收条目的watch监听
  itemWatchStopFns.value.forEach((stopFn) => stopFn());
  itemWatchStopFns.value = [];

  form.value = getInitFormData();
  if (materialReceiveFormRef.value) {
    materialReceiveFormRef.value.resetFields();
  }

  // 重新监听初始条目
  if (form.value.itemList.length > 0) {
    watchItemChanges(0);
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields();
  }
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: MaterialReceiveVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加物料接收单';
  form.value.projectName = currentProject.value?.name;
};

/** 修改按钮操作（核心修复：赋值后主动触发验证+数据类型转换） */
const handleUpdate = async (row?: MaterialReceiveVO) => {
  reset();
  const _id = row?.id || ids.value[0];

  try {
    const res = await getMaterialReceive(_id);
    const formData = res.data;

    // 修复1：处理itemList数据类型，确保数量/验收数量为数字（避免字符串与number规则冲突）
    formData.itemList = formData.itemList.map((item) => ({
      ...item,
      id: item.id || generateItemId(),
      quantity: item.quantity !== undefined ? Number(item.quantity) : undefined, // 转为数字
      acceptedQuantity: item.acceptedQuantity !== undefined ? Number(item.acceptedQuantity) : undefined, // 转为数字
      shortageQuantity: item.shortageQuantity !== undefined ? Number(item.shortageQuantity) : undefined // 转为数字
    }));

    Object.assign(form.value, formData);

    // 修复2：重新监听所有条目，并主动触发每个条目的验证（更新验证状态）
    form.value.itemList.forEach((_, index) => {
      watchItemChanges(index);
      // 手动触发当前条目的数量、验收数量、缺件数量验证
      if (materialReceiveFormRef.value) {
        materialReceiveFormRef.value.validateField(`itemList.${index}.quantity`, () => { });
        materialReceiveFormRef.value.validateField(`itemList.${index}.acceptedQuantity`, () => { });
        materialReceiveFormRef.value.validateField(`itemList.${index}.shortageQuantity`, () => { });
      }
    });

    dialog.visible = true;
    dialog.title = '修改物料接收单';
  } catch (err) {
    proxy?.$modal.msgError('获取详情失败');
  }
};

/** 提交按钮 */
const submitForm = () => {
  materialReceiveFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 提交前确保数据类型正确（数字）
        const submitForm = {
          ...form.value,
          itemList: form.value.itemList.map((item) => ({
            ...item,
            quantity: Number(item.quantity),
            acceptedQuantity: Number(item.acceptedQuantity),
            shortageQuantity: Number(item.shortageQuantity)
          }))
        };

        if (form.value.id) {
          await updateMaterialReceive(submitForm);
        } else {
          submitForm.itemList.forEach((item) => {
            delete item.id;
          });
          await addMaterialReceive(submitForm);
        }
        proxy?.$modal.msgSuccess('操作成功');
        dialog.visible = false;
        await getList();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: MaterialReceiveVO) => {
  const _ids = row?.id || ids.value;
  if (!_ids.length) return;

  try {
    await proxy?.$modal.confirm(`是否确认删除物料接收单编号为"${_ids}"的数据项？`);
    await delMaterialReceive(_ids);
    proxy?.$modal.msgSuccess('删除成功');
    await getList();
  } catch (err) {
    // 取消删除时不提示
  } finally {
    loading.value = false;
  }
};

/** 添加数量验收条目 */
const addItem = () => {
  const newItem = {
    id: generateItemId(),
    name: undefined,
    specification: undefined,
    unit: undefined,
    quantity: undefined,
    acceptedQuantity: undefined,
    shortageQuantity: undefined,
    remark: undefined
  };
  form.value.itemList.push(newItem);
  // 监听新条目变化并触发初始验证
  watchItemChanges(form.value.itemList.length - 1);
  validateQuantityField(form.value.itemList.length - 1);
};

// 数量输入事件处理
const handleQuantityInput = (index: number) => {
  // 确保值为数字类型
  if (form.value.itemList[index].quantity !== undefined) {
    form.value.itemList[index].quantity = Number(form.value.itemList[index].quantity);
  }

  // 手动触发验证
  validateQuantityField(index);
};

// 数量失焦事件
const handleQuantityBlur = (index: number) => {
  validateQuantityField(index);
};

// 验收数量输入事件
const handleAcceptedInput = (index: number) => {
  // 确保值为数字类型
  if (form.value.itemList[index].acceptedQuantity !== undefined) {
    form.value.itemList[index].acceptedQuantity = Number(form.value.itemList[index].acceptedQuantity);
  }

  // 手动触发相关字段验证
  validateQuantityField(index);
};

// 手动验证数量和验收数量字段
const validateQuantityField = (index: number) => {
  if (materialReceiveFormRef.value) {
    materialReceiveFormRef.value.validateField(`itemList.${index}.quantity`, () => { });
    materialReceiveFormRef.value.validateField(`itemList.${index}.acceptedQuantity`, () => { });
    materialReceiveFormRef.value.validateField(`itemList.${index}.shortageQuantity`, () => { });
  }
};

// 监听条目变化，自动计算缺件数量（修复：计算后触发验证）
const watchItemChanges = (index: number) => {
  if (itemWatchStopFns.value[index]) {
    itemWatchStopFns.value[index]();
  }

  const stopFn = watch(
    () => [form.value.itemList[index].quantity, form.value.itemList[index].acceptedQuantity],
    ([quantity, acceptedQuantity]) => {
      const qty = Number(quantity) || 0;
      let acceptedQty = Number(acceptedQuantity) || 0;

      // 仅当验收数量>数量时才修正（允许等于）
      if (acceptedQty > qty && qty > 0) {
        acceptedQty = qty; // 修正为数量值（最大合法值）
        form.value.itemList[index].acceptedQuantity = acceptedQty;
        proxy?.$modal.msgWarning(`验收数量不能大于数量，已自动修正为${acceptedQty}`);
      }

      // 计算缺件数量（允许为0）
      form.value.itemList[index].shortageQuantity = qty - acceptedQty;

      // 修复3：计算后触发当前条目的验证，确保缺件数量状态更新
      validateQuantityField(index);
    },
    { immediate: true }
  );

  itemWatchStopFns.value[index] = stopFn;
};

/** 删除数量验收条目 */
const removeItem = (index: number) => {
  if (form.value.itemList.length <= 1) {
    proxy?.$modal.msgWarning('至少需要保留一条数量验收记录');
    return;
  }

  // 停止该条目的监听
  if (itemWatchStopFns.value[index]) {
    itemWatchStopFns.value[index]();
  }

  // 删除条目和对应的停止函数
  form.value.itemList.splice(index, 1);
  itemWatchStopFns.value.splice(index, 1);
  quantityFormItemRefs.value.splice(index, 1);
};

/** 查看详情 */
const handleView = (row: MaterialReceiveVO) => {
  wordllReceiveRef.value?.openDialog(row);
};

/** 查询物资-采购联系单列表 */
const getlistPurchase = async () => {
  try {
    const res = await listPurchaseDoc({
      projectId: currentProject.value?.id,
      status: 'finish'
    });
    purchaseDocList.value = res.rows;
    purchaseDocList.value.forEach((item) => {
      purchaseMap.set(item.id, item);
    });
  } catch (err) {
    proxy?.$modal.msgError('获取采购单列表失败');
  }
};

/** 通过采购单获取需求信息（修复：数据类型转换） */
const getdemandInfo = async (docId: string) => {
  if (!docId) return;

  try {
    const res = await purchaseDocPlanList(docId);
    if (res.code === 200) {
      // 清空旧监听和条目
      itemWatchStopFns.value.forEach((stopFn) => stopFn());
      itemWatchStopFns.value = [];
      quantityFormItemRefs.value = [];
      form.value.itemList = [];

      // 赋值需求数据并添加监听（确保数量为数字）
      res.data.forEach((item, index) => {
        const qty = Number(item.demandQuantity) || 0;
        const newItem = {
          id: generateItemId(),
          name: item.name,
          specification: item.specification,
          unit: item.unit,
          quantity: qty, // 确保数字类型
          acceptedQuantity: 0, // 初始值为0（数字）
          shortageQuantity: qty, // 初始缺件=数量（数字）
          remark: item.remark,
          planId: item.id,
          id: null
        };
        form.value.itemList.push(newItem);
        watchItemChanges(index);
      });
    }
  } catch (err) {
    proxy?.$modal.msgError('获取采购单需求信息失败');
  }
};

/** 选择采购单触发 */
const handleSelect = (val: string) => {
  if (!val) return;

  const obj = purchaseMap.get(val);
  if (obj) {
    form.value.docCode = obj.docCode || '';
    form.value.supplierUnit = obj.supplier || '';
    form.value.materialName = obj.name || '';
  }

  getdemandInfo(val);
};

/** 监听材料来源变化，重置数量验收列表 */
watch(
  () => form.value.materialSource,
  (newSource, oldSource) => {
    if (newSource === oldSource) return;

    // 停止所有验收条目的监听
    itemWatchStopFns.value.forEach((stopFn) => stopFn());
    itemWatchStopFns.value = [];
    quantityFormItemRefs.value = [];
    // 清空所有文件上传字段的值
    form.value.certCountFileId = undefined; // 合格证文件
    form.value.reportCountFileId = undefined; // 出厂报告文件
    form.value.techDocCountFileId = undefined; // 技术资料文件
    form.value.licenseCountFileId = undefined; // 厂家资质文件
    // 重置数量验收列表为初始状态
    form.value.itemList = [
      {
        id: generateItemId(),
        name: undefined,
        specification: undefined,
        unit: undefined,
        quantity: undefined,
        acceptedQuantity: undefined,
        shortageQuantity: undefined,
        remark: undefined
      }
    ];

    // 重新监听初始条目并触发验证
    watchItemChanges(0);
    validateQuantityField(0);

    // 切换到乙供时，清空采购单相关数据
    if (newSource === '2') {
      form.value.docId = undefined;
      form.value.supplierUnit = undefined;
      form.value.materialName = undefined;
      form.value.docCode = undefined;
    }
  },
  { immediate: true }
);

/** 页面挂载时初始化 */
onMounted(() => {
  getContractList();
  getList();
  getlistPurchase();
  // 监听初始验收条目并触发验证
  if (form.value.itemList.length > 0) {
    watchItemChanges(0);
    validateQuantityField(0);
  }
});

/** 监听项目变化，刷新数据 */
const listeningProject = watch(
  () => currentProject.value?.id,
  (nid) => {
    queryParams.value.projectId = nid;
    form.value.projectId = nid;
    getContractList();
    getList();
    getlistPurchase();
  }
);

/** 页面卸载时清理监听 */
onUnmounted(() => {
  listeningProject();
  itemWatchStopFns.value.forEach((stopFn) => stopFn());
});
</script>

<style scoped lang="scss">
.detail {
  border-bottom: 1px solid #ececec;
  border-top: 1px solid #ececec;
  margin: 10px 0;
  padding: 10px 0;

  &-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    font-weight: bold;
    color: #1eaaff;
  }

  &-item {
    padding: 10px;
    margin-bottom: 15px;
    border-radius: 4px;
    background-color: #f8f9fa;
    position: relative;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.item-actions {
  display: flex;
  justify-content: flex-end;
  padding-top: 6px;
}

.tips {
  font-size: 12px;
  color: #666;
  margin-left: 8px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
