<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='materialName'>
              <el-input v-model='queryParams.materialName' placeholder='请输入物料名称' clearable @keyup.enter='handleQuery' />
            </el-form-item>
<!--            <el-form-item label='顶级标识' prop='topFlag'>-->
<!--              <el-input v-model='queryParams.topFlag' placeholder='请输入顶级标识' clearable-->
<!--                        @keyup.enter='handleQuery' />-->
<!--            </el-form-item>-->
<!--            <el-form-item label='校验类型' prop='checkType'>-->
<!--              <el-select v-model='queryParams.checkType' placeholder='请选择校验类型' clearable>-->
<!--                <el-option v-for='dict in mes_check_type' :key='dict.value' :label='dict.label' :value='dict.value' />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--            <el-form-item label='激活标识' prop='activeFlag'>-->
<!--              <el-input v-model='queryParams.activeFlag' 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="['mes:materialBom:add']">新增
            </el-button>
          </el-col>

<!--          <el-col :span='1.5'>
            <el-button type='primary' plain icon='Plus' @click='handleAddMaterialBom()' v-hasPermi="['mes:materialBom:add']">
              新增BOM
            </el-button>
          </el-col>-->

          <el-col :span='1.5'>
            <el-button type='info' plain icon='Sort' @click='handleToggleExpandAll'>展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch='showSearch' @queryTable='getList'></right-toolbar>
        </el-row>
      </template>
      <el-table
        ref='materialBomTableRef'
        v-loading='loading'
        :data='materialBomList'
        row-key='materialName'
        :default-expand-all='isExpandAll'
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
<!--        <el-table-column label='主键标识' align='center' prop='materialBomId' />-->
<!--        <el-table-column label='父级标识' align='center' prop='parentId' />-->
<!--        <el-table-column label='物料ID' align='center' prop='materialId' />-->
        <el-table-column label='物料名称' align='left' prop='materialName' width='500'/>
        <el-table-column label='bom说明' align='center' prop='materialBomDesc' />
        <el-table-column label='bom版本' align='center' prop='materialBomVersion' />
<!--        <el-table-column label='祖级列表' align='center' prop='ancestors' />-->
        <el-table-column label='标准数量' align='center' prop='standardAmount' />
        <el-table-column label='顶级标识' align='center' prop='topFlag'>
          <template #default='scope'>
            <dict-tag :options='active_flag' :value='scope.row.topFlag' />
          </template>
        </el-table-column>
        <el-table-column label='校验类型' align='center' prop='checkType'>
          <template #default='scope'>
            <dict-tag :options='mes_check_type' :value='scope.row.checkType' />
          </template>
        </el-table-column>
<!--        <el-table-column label='项目ID' align='center' prop='projectId' />-->
<!--        <el-table-column label='装配时长(秒)' align='center' prop='assembleTime' />-->
        <el-table-column label='物料分类' align='center' prop='materialClassfication'>
          <template #default='scope'>
            <dict-tag :options='material_classfication' :value='scope.row.materialClassfication' />
          </template>
        </el-table-column>
<!--        <el-table-column label='附件信息' align='center' prop='attachId' />-->
        <el-table-column label='激活标识' align='center' prop='activeFlag'>
          <template #default='scope'>
            <dict-tag :options='active_flag' :value='scope.row.activeFlag' />
          </template>
        </el-table-column>
        <el-table-column label='备注' align='center' prop='remark' />
<!--        <el-table-column label='创建部门' align='center' prop='createDept' />-->
<!--        <el-table-column label='创建人' align='center' prop='createBy' />-->
<!--        <el-table-column label='创建时间' align='center' prop='createTime' width='180'>-->
<!--          <template #default='scope'>-->
<!--            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label='更新人' align='center' prop='updateBy' />-->
<!--        <el-table-column label='更新时间' align='center' prop='updateTime' width='180'>-->
<!--          <template #default='scope'>-->
<!--            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label='操作' align='center' class-name='small-padding fixed-width'>
          <template #default='scope'>
            <el-tooltip content='修改' placement='top'>
              <el-button link type='primary' icon='Edit' @click='handleUpdate(scope.row)'
                         v-hasPermi="['mes:materialBom:edit']" />
            </el-tooltip>
            <el-tooltip content='新增' placement='top'>
              <el-button link type='primary' icon='Plus' @click='handleAdd(scope.row)'
                         v-hasPermi="['mes:materialBom:add']" />
            </el-tooltip>
            <el-tooltip content='删除' placement='top'>
              <el-button link type='primary' icon='Delete' @click='handleDelete(scope.row)'
                         v-hasPermi="['mes:materialBom:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改物料BOM信息对话框 -->
    <el-dialog :title='dialog.title' v-model='dialog.visible' width='500px' append-to-body>
      <el-form ref='materialBomFormRef' :model='form' :rules='rules' label-width='80px'>
        <el-form-item label='父级标识' prop='parentId'>
          <el-tree-select
            v-model='form.parentId'
            :data='materialBomOptions'
            :props="{ value: 'materialBomId', label: 'materialName', children: 'children' }"
            value-key='materialBomId'
            placeholder='请选择父级标识'
            check-strictly
          />
        </el-form-item>
        <el-form-item label='物料名称' prop='materialId'>
          <el-input v-model="form.materialName" placeholder="请点击检索物料" @click="handleMaterialAdd" readonly>
            <template #append>
              <el-icon class="el-input__icon" ><search/></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label='bom说明' prop='materialBomDesc'>
          <el-input v-model='form.materialBomDesc' placeholder='请输入bom说明' />
        </el-form-item>
        <el-form-item label='bom版本' prop='materialBomVersion'>
          <el-input v-model='form.materialBomVersion' placeholder='请输入bom版本' />
        </el-form-item>
<!--        <el-form-item label='祖级列表' prop='ancestors'>-->
<!--          <el-input v-model='form.ancestors' placeholder='请输入祖级列表' />-->
<!--        </el-form-item>-->
        <el-form-item label='标准数量' prop='standardAmount'>
          <el-input-number v-model='form.standardAmount' placeholder='请输入标准数量' style="width: 200px;" />
        </el-form-item>
<!--        <el-form-item label='顶级标识' prop='topFlag'>-->
<!--          <el-input v-model='form.topFlag' placeholder='请输入顶级标识' />-->
<!--        </el-form-item>-->
        <el-form-item label='校验类型' prop='checkType'>
          <el-radio-group v-model='form.checkType'>
            <el-radio
              v-for='dict in mes_check_type'
              :key='dict.value'
              :value='dict.value'
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
<!--        <el-form-item label='项目ID' prop='projectId'>-->
<!--          <el-input v-model='form.projectId' placeholder='请输入项目ID' />-->
<!--        </el-form-item>-->
<!--        <el-form-item label='装配时长(秒)' prop='assembleTime'>-->
<!--          <el-input v-model='form.assembleTime' placeholder='请输入装配时长(秒)' />-->
<!--        </el-form-item>-->
<!--        <el-form-item label='物料分类' prop='materialClassfication'>-->
<!--          <el-radio-group v-model='form.materialClassfication'>-->
<!--            <el-radio-->
<!--              v-for='dict in material_classfication'-->
<!--              :key='dict.value'-->
<!--              :value='dict.value'-->
<!--            >{{ dict.label }}-->
<!--            </el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
<!--        <el-form-item label='附件信息' prop='attachId'>-->
<!--          <el-input v-model='form.attachId' placeholder='请输入附件信息' />-->
<!--        </el-form-item>-->
        <el-form-item label='激活标识' prop='activeFlag'>
          <el-radio-group v-model='form.activeFlag'>
            <el-radio
              v-for='dict in active_flag'
              :key='dict.value'
              :value='dict.value'
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='备注' prop='remark'>
          <el-input v-model='form.remark' placeholder='请输入备注' />
        </el-form-item>
      </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>

    <!-- 添加物料信息对话框 -->
    <el-dialog title="选择物料信息" v-model="materialOpen" width='1200px' append-to-body>
      <MaterialSelect @selection="handleSelection" ref="materialSelectRef" v-if="materialOpen"></MaterialSelect>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMaterialForm">确 定</el-button>
        <el-button @click="materialOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 根据结构BOM添加物料BOM信息对话框 -->
<!--    <el-dialog
      :title="materialBomDialog.title"
      v-model="materialBomDialog.visible"
      width="1600px"
      append-to-body
      @close="cancelMaterialBom"
    >
      <el-table
        ref="materialBomTableRef"
        :data="materialBomList"
        row-key="materialBomId"
        border
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren'
        }"
        :default-expand-all="true"
      >
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="结构BOM名称" prop="materialTypeName" min-width="120" />
        <el-table-column label="物料" prop="materialName" min-width="180">
          <template #default="scope">
            <el-input
              v-model="scope.row.materialName"
              placeholder="点击选择物料"
              readonly
              @click="handleMaterialSelect(scope.row)">
              <template #append>
                <el-button icon="Search" />
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="BOM说明" prop="materialBomDesc" min-width="120">
          <template #default="scope">
            <el-input v-model="scope.row.materialBomDesc" placeholder="请输入BOM说明" />
          </template>
        </el-table-column>
        <el-table-column label="BOM版本" prop="materialBomVersion" min-width="120">
          <template #default="scope">
            <el-input v-model="scope.row.materialBomVersion" placeholder="请输入BOM版本" />
          </template>
        </el-table-column>
        <el-table-column label="标准数量" prop="standardAmount" width="160">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.standardAmount"
              :min="1"
              :precision="2"
              :step="1"
              :controls="true"
              style="width: 100%"
            />
          </template>
        </el-table-column>
        <el-table-column label="校验类型" prop="checkType" width="120">
          <template #default="scope">
            <el-select v-model="scope.row.checkType" placeholder="请选择">
              <el-option
                v-for="dict in mes_check_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="激活标识" prop="activeFlag" width="120">
          <template #default="scope">
            <el-select v-model="scope.row.activeFlag" placeholder="请选择">
              <el-option
                v-for="dict in active_flag"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" min-width="120">
          <template #default="scope">
            <el-input v-model="scope.row.remark" placeholder="请输入备注" />
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitMaterialBom">确 定</el-button>
          <el-button @click="cancelMaterialBom">取 消</el-button>
        </div>
      </template>
    </el-dialog>-->

  </div>
</template>

<script setup name='MaterialBom' lang='ts'>
import {
  listMaterialBom,
  getMaterialBom,
  delMaterialBom,
  addMaterialBom,
  updateMaterialBom,  addBatchMaterialBom
} from '@/api/mes/materialBom';
import { MaterialBomVO, MaterialBomQuery, MaterialBomForm } from '@/api/mes/materialBom/types';
import MaterialSelect from '@/views/mes/baseMaterialInfo/addMaterial.vue';
import { BaseStructureBomVO } from '@/api/mes/baseStructureBom/types';
import { getBaseStructureBomList } from '@/api/mes/baseStructureBom';

type MaterialBomOption = {
  materialBomId: number;
  materialName: string;
  children?: MaterialBomOption[];
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
;

const { mes_check_type, material_classfication, active_flag } = toRefs<any>(proxy?.useDict('mes_check_type', 'material_classfication', 'active_flag'));

const materialBomList = ref<any[]>([]);
const materialBomOptions = ref<MaterialBomOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const materialBomFormRef = ref<ElFormInstance>();
const materialBomTableRef = ref<ElTableInstance>();
const materialOpen = ref(false);
const materialSelectRef = ref();


const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});


const initFormData: MaterialBomForm = {
  materialBomId: undefined,
  parentId: undefined,
  materialId: undefined,
  materialName: undefined,
  materialBomDesc: undefined,
  materialBomVersion: undefined,
  ancestors: undefined,
  standardAmount: 1,
  topFlag: undefined,
  checkType: '1',
  projectId: undefined,
  assembleTime: undefined,
  materialClassfication: undefined,
  attachId: undefined,
  activeFlag: '1',
  remark: undefined
};

const data = reactive<PageData<MaterialBomForm, MaterialBomQuery>>({
  form: { ...initFormData },
  queryParams: {
    materialBomId: undefined,
    parentId: undefined,
    materialId: undefined,
    materialName: undefined,
    materialBomDesc: undefined,
    materialBomVersion: undefined,
    ancestors: undefined,
    standardAmount: undefined,
    topFlag: undefined,
    checkType: undefined,
    projectId: undefined,
    assembleTime: undefined,
    materialClassfication: undefined,
    attachId: undefined,
    activeFlag: undefined,
    params: {}
  },
  rules: {
    materialBomId: [
      { required: true, message: '主键标识不能为空', trigger: 'blur' }
    ],
    parentId: [
      { required: true, message: '父级标识不能为空', trigger: 'blur' }
    ],
    materialName: [
      { required: true, message: '物料名称不能为空', trigger: 'blur' }
    ]
  }
});

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

/** 查询物料BOM信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMaterialBom(queryParams.value);
  const data = proxy?.handleTree<MaterialBomVO>(res.data, 'materialBomId', 'parentId');

  if (data) {
    materialBomList.value = data;
    loading.value = false;
  }
};

/** 查询物料BOM信息下拉树结构 */
const getTreeselect = async () => {
  const res = await listMaterialBom();
  materialBomOptions.value = [];
  const data: MaterialBomOption = { materialBomId: 0, materialName: '顶级节点', children: [] };
  data.children = proxy?.handleTree<MaterialBomOption>(res.data, 'materialBomId', 'parentId');
  materialBomOptions.value.push(data);
};

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

// 表单重置
const reset = () => {
  form.value = { ...initFormData };
  materialBomFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

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

/** 新增按钮操作 */
const handleAdd = (row?: MaterialBomVO) => {
  reset();
  getTreeselect();
  if (row != null && row.materialBomId) {
    form.value.parentId = row.materialBomId;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = '添加物料BOM信息';
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(materialBomList.value, isExpandAll.value);
};

/** 展开/折叠操作 */
const toggleExpandAll = (data: MaterialBomVO[], status: boolean) => {
  data.forEach((item) => {
    materialBomTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row: MaterialBomVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getMaterialBom(row.materialBomId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改物料BOM信息';
};

/** 提交按钮 */
const submitForm = () => {
  materialBomFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.materialBomId) {
        await updateMaterialBom(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addMaterialBom(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: MaterialBomVO) => {
  await proxy?.$modal.confirm('是否确认删除物料BOM信息编号为"' + row.materialBomId + '"的数据项？');
  loading.value = true;
  await delMaterialBom(row.materialBomId).finally(() => loading.value = false);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

/** 新增按钮操作 */
const handleMaterialAdd = () => {
  materialOpen.value = true;
};
// 提交物料选择
const submitMaterialForm = () => {
  const selectedRow = materialSelectRef.value.tableRef.store.states.currentRow.value;
  if (materialBomDialog.visible) {
    if (currentRow.value && selectedRow) {
      currentRow.value.materialId = selectedRow.materialId;
      currentRow.value.materialName = selectedRow.materialName;
      materialOpen.value = false;
    }
  } else {
    form.value.materialId = selectedRow.materialId;
    form.value.materialName = selectedRow.materialName;
    materialOpen.value = false;
  }
};

/** 当前选中的行 */
const currentRow = ref<any>(null);

// 打开物料选择对话框
const handleMaterialSelect = (row: any) => {
  currentRow.value = row;
  materialOpen.value = true;
};

// 物料选择回调
const handleSelection = (selection: any) => {
  if (currentRow.value) {
    currentRow.value.materialId = selection.materialId;
    currentRow.value.materialName = selection.materialName;
  }
};

//根据结构BOM新增物料BOM对话框
const materialBomDialog = reactive({
  visible: false,
  title: ''
});

// const materialBomForm = ref({});
// const currentStructureBom = ref<BaseStructureBomVO>({} as BaseStructureBomVO);
const materialOptions = ref<any>({});


// 打开添加物料BOM对话框
const handleAddMaterialBom = async () => {
  materialBomDialog.visible = true;
  materialBomDialog.title = "新增BOM";
  // 重置物料BOM列表，避免影响页面主列表
  materialBomList.value = [];
  // 获取结构BOM数据并生成物料BOM列表
  await generateMaterialBomList();
};

// 生成物料BOM列表
const generateMaterialBomList = async () => {
  try {
    // 获取结构BOM数据
    const res = await getBaseStructureBomList(null);

    // 递归处理结构BOM树
    const processBomTree = (items: any[]): MaterialBomForm[] => {
      return items.map(item => ({
        materialBomId: -Math.abs(item.structureBomId), // 使用负数作为临时ID
        parentId: item.parentId === 0 ? 0 : -Math.abs(item.parentId), // 保持父子关系
        materialTypeId: item.materialTypeId,
        materialTypeName: item.materialTypeName,
        materialId: undefined,
        materialName: undefined,
        materialBomDesc: '',
        materialBomVersion: '',
        standardAmount: 1,
        checkType: "0",
        activeFlag: "1",
        remark: '',
        children: item.children && item.children.length > 0
          ? processBomTree(item.children)
          : []
      }));
    };

    // 构建完整的树形结构
    const structureBomData = buildTree(res.data);
    // 处理数据并赋值
    materialBomList.value = processBomTree(structureBomData);
  } catch (error) {
    console.error('获取结构BOM数据失败:', error);
    proxy?.$modal.msgError('获取数据失败');
  }
};

// 构建树形结构
const buildTree = (data: any[]) => {
  const tree: any[] = [];
  const map = new Map();

  // 首先创建一个以id为键的映射
  data.forEach(item => {
    // 创建新对象，避免修改原始数据
    const node = { ...item, children: [] };
    map.set(item.structureBomId, node);
  });

  // 然后构建树形结构
  data.forEach(item => {
    const node = map.get(item.structureBomId);
    if (item.parentId === 0) {
      // 顶级节点直接加入树中
      tree.push(node);
    } else {
      // 将当前节点添加到父节点的children中
      const parent = map.get(item.parentId);
      if (parent) {
        if (!parent.children) {
          parent.children = [];
        }
        parent.children.push(node);
      }
    }
  });

  return tree;
};

// 物料选择变更处理
const handleMaterialChange = (materialId: string | number, row: any) => {
  const material = materialOptions.value[row.materialTypeId]?.find(
    (item: any) => item.materialId === materialId
  );
  if (material) {
    row.materialName = material.materialName;
  }
};

// 提交物料BOM
const submitMaterialBom = async () => {
  try {
    // 验证数据完整性
    const validateTreeData = (nodes: any[], path: string = ''): string | null => {
      for (let i = 0; i < nodes.length; i++) {
        const node = nodes[i];
        const currentPath = path ? `${path} -> ${node.materialTypeName}` : node.materialTypeName;

        // 如果当前节点没有选择物料
        if (!node.materialId) {
          // 但是有子节点被选择了，说明跳过了当前层。例如一三层填充但跳过了第二层
          if (hasSelectedDescendant(node)) {
            return `请先为 "${currentPath}" 选择物料，不能跳过中间层级`;
          }
        }

        // 递归检查子节点
        if (node.children && node.children.length > 0) {
          const childResult = validateTreeData(node.children, currentPath);
          if (childResult) {
            return childResult;
          }
        }
      }
      return null;
    };

    // 检查节点是否有被选择的后代节点
    const hasSelectedDescendant = (node: any): boolean => {
      if (!node.children) {
        return false;
      }
      return node.children.some((child: any) => {
        if (child.materialId) {
          return true;
        }
        return hasSelectedDescendant(child);
      });
    };

    // 执行验证
    const validationError = validateTreeData(materialBomList.value);
    if (validationError) {
      proxy?.$modal.msgError(validationError);
      return;
    }

    // 将树形结构转换为扁平数组，并处理父子关系
    const flattenTree = (nodes: any[], parentId: number = 0): any[] => {
      let result: any[] = [];
      nodes.forEach((node, index) => {
        const { children, ...nodeWithoutChildren } = node;

        // 只处理选择了物料的节点
        if (nodeWithoutChildren.materialId) {
          // 检查必填字段
          if (!nodeWithoutChildren.standardAmount) {
            throw new Error(`物料 "${nodeWithoutChildren.materialName}" 的标准数量不能为空`);
          }
          if (nodeWithoutChildren.standardAmount <= 0) {
            throw new Error(`物料 "${nodeWithoutChildren.materialName}" 的标准数量必须大于0`);
          }
          if (!nodeWithoutChildren.checkType) {
            throw new Error(`物料 "${nodeWithoutChildren.materialName}" 的校验类型不能为空`);
          }
          if (!nodeWithoutChildren.activeFlag) {
            throw new Error(`物料 "${nodeWithoutChildren.materialName}" 的激活标识不能为空`);
          }

          const newNode = {
            ...nodeWithoutChildren,
            parentId: parentId
          };

          result.push(newNode);

          // 如果有子节点，递归处理
          if (children && children.length > 0) {
            result = result.concat(flattenTree(children, newNode.materialBomId));
          }
        }
      });
      return result;
    };

    const flattenedData = flattenTree(materialBomList.value);
    if (flattenedData.length === 0) {
      proxy?.$modal.msgError('请至少输入一行有效数据');
      return;
    }

    // 提交数据
    await addBatchMaterialBom(flattenedData);
    proxy?.$modal.msgSuccess('新增成功');
    materialBomDialog.visible = false;
    getList(); // 刷新列表
  } catch (error: any) {
    console.error('提交失败:', error);
    proxy?.$modal.msgError(error.message || '提交失败');
  }
};

// 取消
const cancelMaterialBom = () => {
  materialBomDialog.visible = false;
  // 重新获取主列表数据
  getList();
};

// 选中数据
const selection = ref([]);

onMounted(() => {
  getList();
});
</script>
