<template>
  <div class="box-card">
    <div class="process-left">
      <div class="process-select">
        <!-- 工艺级别：-->
        <el-form :model="form" label-width="auto">
          <el-form-item label="工艺级别:">
            <el-select
              v-model="rank"
              placeholder="请选择"
              style="width: 220px"
              @change="leavelChange"
              clearable
              filterable
            >
              <el-option label="一级工艺" value="1" />
              <el-option label="二级工艺" value="2" />
              <el-option label="三级工艺" value="3" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <el-tree
        ref="tree"
        :data="data"
        :props="defaultProps"
        node-key="id"
        @node-click="handleNodeClick"
        @node-contextmenu="handleNodeRightClick"
        default-expand-all
        :expand-on-click-node="false"
      />
      <div
        v-show="contextMenuVisible"
        class="custom-context-menu"
        :style="{ top: contextMenuTop + 'px', left: contextMenuLeft + 'px' }"
      >
        <div class="context-menu">
          <el-button
            link
            type="danger"
            @click="handleDeleteNode"
            v-if="contextTreeNode && contextTreeNode.level === 2"
          >
            删除
          </el-button>
        </div>
      </div>
    </div>
    <div class="process-right" v-loading="treeLoading">
      <el-form :model="treeNodes.rawData" label-width="auto" :rules="rules">
        <el-row :gutter="24" v-if="activeName == '1'">
          <el-col :span="8">
            <el-form-item label="重要度:" prop="prority">
              <el-select
                v-model="treeNodes.rawData.prority"
                :placeholder="'请选择'"
                clearable
                filterable
              >
                <el-option
                  v-for="item in priorityList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <!-- 不必填  如果为空 默认值是 临时工艺 -->
            <el-form-item label="流转编号:" prop="roamNo">
              <el-input v-model="treeNodes.rawData.roamNo" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注:" prop="remarks">
              <el-input v-model="treeNodes.rawData.remarks" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane
          label="工艺维护"
          name="1"
          v-if="treeLeave == 1 || treeLeave == 2"
        ></el-tab-pane>
        <el-tab-pane label="项目" name="2" v-if="treeLeave == 3"></el-tab-pane>
        <el-tab-pane label="尺寸、量具" name="3" v-if="treeLeave == 3"></el-tab-pane>
        <el-tab-pane label="工装、模具表" name="4" v-if="treeLeave == 3"></el-tab-pane>
      </el-tabs>
      <div class="table-btn">
        <div class="table-btn-left">
          <el-button type="primary" plain @click="addTable()">插入一行</el-button>
          <el-button type="danger" plain @click="delTable()">删除选择行</el-button>
          <el-button type="primary" @click="saveInfo()" :loading="craftLoading">保存</el-button>
        </div>
        <div class="table-btn-right" v-if="activeName == '1'">
          <el-select
            v-model="modelLevel"
            placeholder="选择工艺模板"
            style="width: 220px; margin-right: 12px"
            clearable
            filterable
            :filter-method="handleFilter"
          >
            <el-option
              v-for="(item, index) in filteredList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-button type="primary" @click="modelLevelChange()" :loading="modelLevelLoading"
            >导入模板</el-button
          >
        </div>
      </div>
      <!-- 工序 -->
      <el-form
        ref="tableForm1"
        :model="form1"
        :rules="formRules1"
        label-width="0px"
        v-if="activeName == '1'"
      >
        <el-table
          :data="form1.tableData1"
          style="width: 100%"
          @selection-change="handleSelectionChange1"
          :height="tableHeight"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="processNo" label="工序号">
            <template #header>
              <span><i style="color: red">*</i>工序号</span>
            </template>
            <template #default="scope">
              <el-form-item
                :prop="`tableData1[${scope.$index}].processNo`"
                :rules="formRules1.processNo"
              >
                <el-input
                  v-model="scope.row.processNo"
                  placeholder="请输入"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="ppsId" label="工序">
            <template #header>
              <span><i style="color: red">*</i>工序</span>
            </template>
            <template #default="scope">
              <el-form-item :prop="`tableData1[${scope.$index}].ppsId`" :rules="formRules1.ppsId">
                <el-select
                  v-model="scope.row.ppsId"
                  placeholder="请选择"
                  clearable
                  filterable
                  @change="processChange(scope.row, scope.$index)"
                >
                
                  <el-option
                    v-for="(item, index) in processSetOption"
                    :key="index"
                    :label="`${item.code}-${item.name}`"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="caId" label="工艺能力">
            <template #header>
              <span><i style="color: red">*</i>工艺能力</span>
            </template>
            <template #default="scope">
              <el-form-item :prop="`tableData1[${scope.$index}].caId`" :rules="formRules1.caId">
                <el-select
                  v-model="scope.row.caId"
                  placeholder="请选择"
                  clearable
                  filterable
                  @change="craftChange(scope.row, scope.$index)"
                >
                  <el-option
                    v-for="(item, index) in craftAbilityOption"
                    :key="index"
                    :label="`${item.caCode}-${item.caName}`"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="proDes" label="工序描述">
            <!-- <template #header>
              <span><i style="color: red">*</i>工序描述</span>
            </template> -->
            <template #default="scope">
              <el-form-item :prop="`tableData1[${scope.$index}].proDes`" :rules="formRules1.proDes">
                <el-input v-model="scope.row.proDes" placeholder="请输入"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="isMain" label="是否主工序">
            <template #header>
              <span><i style="color: red">*</i>是否主工序</span>
            </template>
            <template #default="scope">
              <el-form-item :prop="`tableData1[${scope.$index}].isMain`" :rules="formRules1.isMain">
                <el-select v-model="scope.row.isMain" placeholder="请选择" clearable filterable>
                  <el-option label="是" value="1"></el-option>
                  <el-option label="否" value="0"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <!-- 项目 -->
      <el-form
        ref="tableForm2"
        :model="form2"
        :rules="formRules2"
        label-width="0px"
        v-if="activeName == '2'"
      >
        <el-table
          :data="form2.tableData2"
          style="width: 100%"
          @selection-change="handleSelectionChange2"
          :height="tableHeight"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="trialNo" label="项目编号">
            <template #default="scope">
              <el-input
                v-model="scope.row.trialNo"
                placeholder="请输入"
                style="width: 100%"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="projectCode" label="检验项目">
            <template #header>
              <span><i style="color: red">*</i>检验项目</span>
            </template>
            <template #default="scope">
              <el-form-item
                :prop="`tableData2[${scope.$index}].projectCode`"
                :rules="formRules2.projectCode"
              >
                <el-select
                  v-model="scope.row.projectCode"
                  placeholder="请选择"
                  clearable
                  filterable
                  @change="projectChange(scope.row, scope.$index)"
                >
                  <el-option
                    v-for="(item, index) in projectOptions"
                    :key="index"
                    :label="`${item.code}-${item.name}`"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="projectStandard" label="检验标准">
            <template #header>
              <span><i style="color: red">*</i>检验标准</span>
            </template>
            <template #default="scope">
              <el-form-item
                :prop="`tableData2[${scope.$index}].projectStandard`"
                :rules="formRules2.projectStandard"
              >
                <el-select
                  v-model="scope.row.projectStandard"
                  placeholder="请选择"
                  clearable
                  filterable
                  @change="standardChange(scope.row, scope.$index)"
                >
                  <el-option
                    v-for="(item, index) in standardList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="proHours" label="定额工时(分钟)">
            <template #header>
              <span><i style="color: red">*</i>定额工时(分钟)</span>
            </template>
            <template #default="scope">
              <el-form-item
                :prop="`tableData2[${scope.$index}].proHours`"
                :rules="formRules2.proHours"
              >
                <el-input
                  v-model="scope.row.proHours"
                  placeholder="请输入"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="prepareHours" label="准备工时(分钟)">
            <template #default="scope">
              <el-input
                v-model="scope.row.prepareHours"
                placeholder="请输入"
                style="width: 100%"
              ></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <!-- 量具 -->
      <el-form
        ref="tableForm3"
        :model="form3"
        :rules="formRules3"
        label-width="0px"
        v-if="activeName == '3'"
      >
        <el-table
          :data="form3.tableData3"
          :height="tableHeight"
          style="width: 100%"
          @selection-change="handleSelectionChange3"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="trialNo" label="项目编号">
            <template #default="scope">
              <el-input
                v-model="scope.row.trialNo"
                placeholder="请输入"
                style="width: 100%"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="testType" label="镀前镀后">
            <template #header>
              <span><i style="color: red">*</i>镀前镀后</span>
            </template>
            <template #default="scope">
              <el-form-item
                :prop="`tableData3[${scope.$index}].testType`"
                :rules="formRules3.testType"
              >
                <el-select v-model="scope.row.testType" placeholder="请选择" clearable filterable>
                  <el-option label="是" value="1"></el-option>
                  <el-option label="否" value="2"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="tool" label="量具">
            <template #header>
              <span><i style="color: red">*</i>量具</span>
            </template>
            <template #default="scope">
              <el-form-item :prop="`tableData3[${scope.$index}].tool`" :rules="formRules3.tool">
                <el-input
                  v-model="scope.row.tool"
                  placeholder="请输入"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="toolSize" label="量具尺寸">
            <template #default="scope">
              <el-input
                v-model="scope.row.toolSize"
                placeholder="请输入"
                style="width: 100%"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="toolSize" label="图纸尺寸">
            <template #default="scope">
              <el-input
                v-model="scope.row.toolSize"
                placeholder="请输入"
                style="width: 100%"
              ></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <!-- 工装 -->
      <el-form
        ref="tableForm4"
        :model="form4"
        :rules="formRules4"
        label-width="0px"
        v-if="activeName == '4'"
      >
        <el-table
          :data="form4.tableData4"
          style="width: 100%"
          @selection-change="handleSelectionChange4"
          :height="tableHeight"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <!-- <el-table-column prop="trialNo" label="工序号">
            <template #default="scope">
              <el-input
                v-model="scope.row.trialNo"
                placeholder="请输入"
                style="width: 100%"
              ></el-input>
            </template>
          </el-table-column> -->
          <el-table-column prop="moldCode" label="对应工装">
            <template #header>
              <span><i style="color: red">*</i>对应工装</span>
            </template>
            <template #default="scope">
              <el-form-item
                :prop="`tableData4[${scope.$index}].moldCode`"
                :rules="formRules4.moldCode"
              >
                <el-input
                  v-model="scope.row.moldCode"
                  placeholder="请输入"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="moldName" label="工装名称">
            <template #default="scope">
              <el-input
                v-model="scope.row.moldName"
                placeholder="请输入"
                style="width: 100%"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="isPrint" label="是否印字">
            <template #default="scope">
              <el-input
                v-model="scope.row.isPrint"
                placeholder="请输入"
                style="width: 100%"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="printNo" label="印字版编号">
            <template #default="scope">
              <el-input
                v-model="scope.row.printNo"
                placeholder="请输入"
                style="width: 100%"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="testFixtureNo" label="测试夹具号">
            <template #default="scope">
              <el-input
                v-model="scope.row.testFixtureNo"
                placeholder="请输入"
                style="width: 100%"
              ></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
  </div>
</template>
<script>
import {
  getProcessAuthorized,
  getModelList,
  getModelDetailList,
  authorizedAccomplish2,
  saveProcessProjectSave,
  saveProcessMeasuringTool,
  saveProcessMoldTool,
  getProcessSetList,
  getCraftAbilityList,
  getProject,
  getStandardList,
  craftBatchRemoval,
} from '@/api/processManagement/taskProcessing';
import { getPqList } from '@/api/qualityManagement/remindRedeem/remindRedeem';
import { getDictionary } from '@/api/system/dict';
export default {
  name: 'CraftIndex',
  components: {},
  props: {
    partId: {
      type: [Number, String],
      default: null,
    },
    updateRow: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      tableHeight: 0,
      form: {},
      treeLoading: false,
      modelLevelLoading: false,
      craftLoading: false,
      rank: '2',
      lastConfirmedRank: '2',
      data: [],
      rules: {
        prority: [{ required: true, message: '请选择', trigger: 'blur' }],
        qualityGradeCode: [{ required: true, message: '请选择', trigger: 'blur' }],
      },
      priorityList: [
        {
          label: '本次使用',
          value: 1,
        },
        {
          label: '正式工艺',
          value: 2,
        },
        {
          label: '临时工艺',
          value: 3,
        },
      ],
      rankList: [],
      activeName: '1',
      treeLeave: 1, //组织树选中层级
      processSetOption: [], //工序列表
      craftAbilityOption: [], //工艺能力列表
      modelOption: [], //模板列表
      modelLevel: null, //模板选择
      form1: {
        tableData1: [], //工序
        deleteIds: [],
        selectIds: [], //选中ID
      },
      form2: {
        tableData2: [], //项目
        deleteIds: [],
        selectIds: [], //选中ID
      },
      form3: {
        tableData3: [], //量具
        deleteIds: [],
        selectIds: [], //选中ID
      },
      form4: {
        tableData4: [], //工装
        deleteIds: [],
        selectIds: [], //选中ID
      },
      formRules1: {
        ppsId: [{ required: true, message: '请选择', trigger: ['change', 'submit'] }],
        caId: [{ required: true, message: '请选择', trigger: ['change', 'submit'] }],
        // proDes: [{ required: true, message: '请选择', trigger: ['change', 'submit'] }],
        isMain: [{ required: true, message: '请选择', trigger: ['change', 'submit'] }],
        processNo: [{ required: true, message: '请输入', trigger: ['change', 'submit'] }],
      },
      formRules2: {
        projectCode: [{ required: true, message: '请选择', trigger: ['change', 'submit'] }],
        projectStandard: [{ required: true, message: '请输入', trigger: ['change', 'submit'] }],
        proHours: [{ required: true, message: '请输入', trigger: ['change', 'submit'] }],
      },
      formRules3: {
        testType: [{ required: true, message: '请选择', trigger: ['change', 'submit'] }],
        tool: [{ required: true, message: '请选择', trigger: ['change', 'submit'] }],
      },
      formRules4: {
        moldCode: [{ required: true, message: '请输入', trigger: ['change', 'submit'] }],
      },
      treeNodes: {
        rawData: {},
      }, //选中组织树节点信息
      parentData: {}, //选中父节点的数据
      partInfoData: {}, //零件信息
      tempId: 0,
      projectOptions: [], //检验项目列表
      standardList: [], //检验标准列表
      filteredList: [],
      dictionaryData: [],
      // 右键菜单相关
      contextMenuVisible: false,
      contextMenuTop: 0,
      contextMenuLeft: 0,
      contextNodeData: null,
      contextTreeNode: null,
      defaultProps: {
        // 使用 label 属性（已在 transformCraftTree 中设置好）
        label: 'label',
        // 子节点字段
        children: 'children',
        // 节点是否禁用
        disabled: 'disabled',
      },
    };
  },

  mounted() {
    this.getModelList();
    this.getDetails();

    this.getProcessSetList();
    this.getCraftAbilityList();
    this.getPqList();
    this.getProject();
    this.getStandardList();
    this.getDictionary();
    document.addEventListener('click', this.closeContextMenu);
    document.addEventListener('contextmenu', this.closeContextMenu); // 右键其他地方也关闭
  },
  beforeUnmount() {
    document.removeEventListener('click', this.closeContextMenu);
    document.removeEventListener('contextmenu', this.closeContextMenu);
  },
  methods: {
    // 表格高度计算
    calculateTableHeight() {
      this.$nextTick(() => {
        const rightContainer = this.$el.querySelector('.process-right');
        if (!rightContainer) return;

        const formElement = this.$el.querySelector('.process-right > .el-form');
        const tabsElement = this.$el.querySelector('.process-right > .el-tabs');
        const btnElement = this.$el.querySelector('.process-right > .table-btn');

        const formHeight = formElement ? formElement.offsetHeight : 0;
        const tabsHeight = tabsElement ? tabsElement.offsetHeight : 0;
        const btnHeight = btnElement ? btnElement.offsetHeight : 0;

        const containerHeight = rightContainer.offsetHeight;

        const padding = 24;
        const marginBottom = 12;
        this.tableHeight =
          containerHeight - formHeight - tabsHeight - btnHeight - padding - marginBottom * 2;
        // 确保最小高度
        if (this.tableHeight < 200) {
          this.tableHeight = 200;
        }
      });
    },
    // 获取涂色标、涂色带、涂箭头的系数
    getDictionary() {
      getDictionary({ code: 'part_info' }).then(res => {
        this.dictionaryData = res.data.data;
      });
    },
    // 获取检验项目名字
    projectChange(row, index) {
      let selectName = this.projectOptions.find(item => item.id == row.projectCode);
      this.form2.tableData2[index].projectName = selectName.name;
      this.form2.tableData2[index].proHours =
        selectName.standardWorkMinute != -1 ? selectName.standardWorkMinute : 0;
    },
    // 获取检验标准名字
    standardChange(row, index) {
      let selectName = this.standardList.find(item => item.id == row.projectStandard);
      this.form2.tableData2[index].projectStandardName = selectName.name;
    },
    getStandardList() {
      getStandardList().then(res => {
        this.standardList = res.data.data;
      });
    },
    getProject() {
      getProject({ size: 999999, current: 1 }).then(res => {
        this.projectOptions = res.data.data.records;
      });
    },
    // 获取工序名字
    processChange(row, index) {
      let selectName = this.processSetOption.find(item => item.id == row.ppsId);
      this.form1.tableData1[index].processName = selectName.name;
      this.form1.tableData1[index].processCode = selectName.code;
      if (this.form1.tableData1[index].processName.indexOf('涂色标') > -1) {
        // tsbNum 涂色标个数  tsdNum 涂色带个数   涂箭头个数
        let sum_ = 0;
        if (this.partInfoData.tsbNum) {
          let tsb = this.dictionaryData.find(item => item.dictValue == '涂色标');
          sum_ += parseInt(this.partInfoData.tsbNum) * tsb.dictKey;
        }
        if (this.partInfoData.tsdNum) {
          let tsd = this.dictionaryData.find(item => item.dictValue == '涂色带');
          sum_ += parseInt(this.partInfoData.tsdNum) * tsd.dictKey;
        }
        if (this.partInfoData.tsjNum) {
          let tsj = this.dictionaryData.find(item => item.dictValue == '涂箭头');
          sum_ += parseInt(this.partInfoData.tsjNum) * tsj.dictKey;
        }
        this.form1.tableData1[index].proHours = parseFloat(sum_.toFixed(2));
      }
    },
    // 获取工艺能力名字
    craftChange(row, index) {
      let selectName = this.craftAbilityOption.find(item => item.id == row.caId);
      this.form1.tableData1[index].craftName = selectName.caName;
      this.form1.tableData1[index].craftCode = selectName.code;
    },
    // 获取生产标识列表
    getPqList() {
      getPqList().then(res => {
        this.rankList = res.data.data;
      });
    },
    handleFilter(keyword) {
      // 1. 无关键词时，显示全部数据
      if (!keyword) {
        this.filteredList = [...this.modelOption];
        return;
      }

      // 2. 统一转为小写，实现不区分大小写过滤
      const lowerKeyword = keyword;

      // 3. 同时匹配两个字段：name 或 pinyin 包含关键词即保留
      this.filteredList = this.modelOption.filter(item => {
        // 字段1：姓名（转小写）
        const matchName = item.name.includes(lowerKeyword);
        // 字段2：拼音（转小写）
        const matchPinyin = item.modelNameStr.includes(lowerKeyword);
        // 只要有一个字段匹配，就保留该选项
        return matchName || matchPinyin;
      });
    },
    // 工艺模板列表
    async getModelList() {
      await getModelList().then(res => {
        this.modelOption = res.data.data;
        this.filteredList = [...this.modelOption];
      });
    },
    // 工序列表查询
    getProcessSetList() {
      getProcessSetList().then(res => {
        this.processSetOption = res.data.data;
      });
    },
    // 工艺能力列表查询
    getCraftAbilityList() {
      getCraftAbilityList().then(res => {
        this.craftAbilityOption = res.data.data;
      });
    },
    // 导入模板
    modelLevelChange() {
      if (!this.treeNodes.rawData) {
        return this.$message.warning('请先选择工艺树节点');
      }
      this.modelLevelLoading = true;
      getModelDetailList({ Id: this.modelLevel }).then(res => {
        const templateData = res.data.data.proDetailVOList;
        const existing = [...this.form1.tableData1];
        const baseIndex = existing.length;

        // 将模板中的工序数据映射为表格所需格式
        const mappedData = templateData.map((item, index) => {
          // ✅ 映射检验项目列表
          const projectList = (item.modelProjectList || []).map(project => ({
            id: null,
            trialNo: this.getProcessNo([], index),
            projectCode: project.projectCode,
            projectName: project.projectName,
            projectStandard: project.projectStandard,
            projectStandardName: project.projectStandardName,
            proHours: project.proHours || 0,
            prepareHours: project.prepareHours || 0,
          }));

          // ✅ 映射量具列表
          const measuringToolList = (item.measuringToolList || []).map(tool => ({
            id: null,
            trialNo: this.getProcessNo([], index),
            testType: tool.testType,
            tool: tool.tool,
            toolSize: tool.toolSize,
            toolInfo: tool.toolInfo,
          }));

          // ✅ 映射工装列表
          const moldToolList = (item.moldToolList || []).map(mold => ({
            id: null,
            trialNo: this.getProcessNo([], index),
            moldCode: mold.moldCode,
            moldName: mold.moldName,
            isPrint: mold.isPrint,
            printNo: mold.printNo,
            testFixtureNo: mold.testFixtureNo,
          }));

          return {
            id: null,
            _tempId: `temp_${Date.now()}_${index}`, // 临时唯一标识
            processNo: this.getProcessNo(existing, index),
            ppsId: item.ppsId + '',
            processName: item.processName,
            caId: item.caId + '',
            craftName: item.craftName,
            proDes: item.proDes,
            proHours: item.proHours || '',
            setoutHours: item.setoutHours || '',
            isMain: item.isMain || '0',
            // ✅ 将子数据关联到工序
            processProjectList: projectList,
            measuringToolList: measuringToolList,
            moldToolList: moldToolList,
          };
        });

        // 追加模式
        this.form1.tableData1 = [...existing, ...mappedData];
        this.modelLevelLoading = false;

        // ✅ 更新左侧树形结构（不调用接口）
        this.updateTreeStructure(mappedData);

        this.$message.success('模板导入成功，请检查后手动保存');
      });
    },
    // ✅ 新增：更新树形结构方法
    updateTreeStructure(mappedData) {
      // 1. 更新当前选中节点的 processList
      if (this.treeLeave === 2) {
        this.treeNodes.processList = this.form1.tableData1;
      }

      // 2. 更新 data 树形结构中对应的工艺节点
      const updateTreeNode = nodes => {
        for (let node of nodes) {
          if (node.level === 2 && node.id === this.treeNodes.id) {
            // 更新工艺节点的 processList
            node.processList = this.form1.tableData1;

            // 更新子节点（工序）
            node.children = this.form1.tableData1.map(process => ({
              id: process.id || process._tempId || `process_${Date.now()}_${Math.random()}`,
              label: process.processName || '未知工序',
              level: 3,
              rawData: {
                processInfo: process,
                projectList: process.processProjectList || [],
                measuringToolList: process.measuringToolList || [],
                moldToolList: process.moldToolList || [],
              },
              children: (process.processProjectList || []).map(project => ({
                id: project.id || `project_${Date.now()}_${Math.random()}`,
                label: project.projectName || '未知项目',
                level: 4,
                disabled: true,
                rawData: project,
              })),
            }));
            break;
          }
          if (node.children && node.children.length > 0) {
            updateTreeNode(node.children);
          }
        }
      };
      updateTreeNode(this.data);
    },
    // 获取零件信息详情数据
    async getDetails() {
      this.treeLoading = true;
      let query_ = {};
      if (!this.updateRow.partVersion) {
        query_ = {
          partId: this.partId,
          taskId: this.updateRow.id,
          rank: this.lastConfirmedRank,
          version: this.updateRow.version,
        };
      } else {
        query_ = {
          version: this.updateRow.partVersion,
          partCode: this.updateRow.partCode,
          rank: this.lastConfirmedRank,
        };
      }
      await getProcessAuthorized(query_)
        .then(res => {
          this.treeLoading = false;
          this.data = this.transformCraftTree(res.data.data);
          this.partInfoData = res.data.data.partInfo;
          this.$nextTick(() => {
            this.autoSelectFirstProcess();
            this.calculateTableHeight();
          });
          if (this.partInfoData.partName == '石墨模') {
            let graphite = this.modelOption.find(item => item.name == '石墨模');
            this.modelLevel = graphite.id;
            this.modelLevelChange();
          }
        })
        .catch(err => {
          this.treeLoading = false;
        });
    },
    autoSelectFirstProcess() {
      if (!this.data || this.data.length === 0) return;
      const rootNode = this.data[0];
      this.handleNodeClick(rootNode, {
        level: 1,
        parent: {
          data: null,
          isRoot: true,
        },
      });
      this.$nextTick(() => {
        if (this.$refs.tree) {
          this.$refs.tree.setCurrentKey(rootNode.id);
        }
      });
    },
    // 组织树转换
    transformCraftTree(responseData) {
      const { partInfo, craftList } = responseData;
      const partCode = partInfo.partCode;

      const generateId = (prefix, id, fallback) => {
        return (
          id || `${prefix}_${fallback}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
        );
      };

      const formatCraftLabel = craftInfo => {
        return `${craftInfo.roamNo || '临时工艺'}-${craftInfo.craftNo || 'C000000'}`;
      };

      const tree = [
        {
          id: generateId('part', partInfo.id, partCode),
          label: partCode,
          disabled: false,
          level: 1,
          rawData: {
            partCode: partInfo.partCode,
            partId: partInfo.id,
            rank: this.rank,
            version: partInfo.version,
            craftNo: 'C000000',
          },

          children: (craftList || []).map(craft => {
            const { craftInfo, processList } = craft;

            return {
              ...craftInfo,
              id: generateId('craft', craftInfo.id, craftInfo.craftNo),
              label: formatCraftLabel(craftInfo),
              level: 2,
              rawData: craftInfo,
              // ✅ 工序列表
              processList: (processList || []).map(process => ({
                ...process.processInfo,
                projectList: process.projectList || [],
                measuringToolList: process.measuringToolList || [],
                moldToolList: process.moldToolList || [],
              })),
              // ✅ 子节点（工序）
              children: (processList || []).map(process => {
                const { processInfo, projectList, measuringToolList, moldToolList } = process;

                return {
                  ...processInfo,
                  id: generateId('process', processInfo.id, processInfo.processNo),
                  label: processInfo.processNo+'-'+processInfo.processName,
                  level: 3,
                  rawData: {
                    processInfo,
                    projectList: projectList || [],
                    measuringToolList: measuringToolList || [],
                    moldToolList: moldToolList || [],
                  },
                  // ✅ 子节点（项目）
                  children: (projectList || []).map(project => ({
                    id: generateId('project', project.id, project.projectCode),
                    label: project.trialNo+'-'+project.projectName || '未知项目',
                    level: 4,
                    disabled: true,
                    rawData: project,
                  })),
                };
              }),
            };
          }),
        },
      ];

      return tree;
    },
    // 组织树点击
    handleNodeClick(nodes, node, self) {
      if (nodes.disabled && node.level !== 1) {
        return false;
      }
      // console.log(node.level, nodes, 'node.level');
      this.calculateTableHeight();
      this.treeLoading = true;

      this.treeNodes = nodes;
      const parentNode = node.parent;

      if (parentNode && parentNode.data && !parentNode.isRoot) {
        this.parentData = parentNode.data;
      }

      this.treeLeave = node.level;

      // 清空现有表格数据
      this.clearTableData();

      // 根据节点层级加载对应数据
      if (this.treeLeave === 1) {
        // 🟢 零件节点：加载该零件下所有工艺的工序数据（只读）
        this.activeName = '1';
        const allProcesses = [];
        this.form1.tableData1 = allProcesses;
      }

      if (this.treeLeave === 2) {
        // 🟢 工艺节点：加载工序列表
        this.activeName = '1';
        this.form1.tableData1 = nodes.processList || [];
      }

      if (this.treeLeave === 3) {
        // 🟢 工序节点：加载项目、量具、工装
        this.activeName = '2';
        const { projectList, measuringToolList, moldToolList } = nodes.rawData;
        this.form2.tableData2 = projectList || [];
        this.form3.tableData3 = measuringToolList || [];
        this.form4.tableData4 = moldToolList || [];
      }
      setTimeout(() => {
        this.treeLoading = false;
      }, 1000);
    },
    // 清空表格数据
    clearTableData() {
      this.form1.tableData1 = [];
      this.form2.tableData2 = [];
      this.form3.tableData3 = [];
      this.form4.tableData4 = [];
      this.form1.deleteIds = [];
      this.form2.deleteIds = [];
      this.form3.deleteIds = [];
      this.form4.deleteIds = [];
    },
    // 右键点击树节点
    handleNodeRightClick(event, nodeData, node, component) {
      event.preventDefault();

      if (node.level !== 2) {
        this.$message.warning('仅工艺节点支持右键操作');
        this.contextMenuVisible = false;
        return;
      }

      // 记录节点信息
      this.contextNodeData = nodeData;
      this.contextTreeNode = node;

      // 设置菜单位置（防止超出视口）
      const x = event.clientX;
      const y = event.clientY;

      // 可选：简单防越界（可根据需要增强）
      this.contextMenuLeft = Math.min(x, window.innerWidth - 130); // 130 是菜单宽度
      this.contextMenuTop = Math.min(y, window.innerHeight - 60); // 60 是菜单高度

      this.contextMenuVisible = true;
    },
    closeContextMenu() {
      this.contextMenuVisible = false;
      this.contextNodeData = null;
      this.contextTreeNode = null;
    },
    async handleDeleteNode() {
      if (!this.contextTreeNode) {
        this.closeContextMenu();
        return;
      }

      const node = this.contextTreeNode;
      const nodeId = node.data.id;
      try {
        // 弹出确认框
        await this.$confirm('此操作将删除该工艺及所有子工序，是否继续？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        // 调用删除API（替换为你的实际API）
        await craftBatchRemoval({ id: node.data.id }).then(res => {
          this.$message.success('删除成功');
          this.getDetails();
        });
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败，请重试');
        }
      } finally {
        this.closeContextMenu();
      }
    },

    // 右侧tab切换
    handleClick(value) {
      this.form1.deleteIds = [];
      this.form2.deleteIds = [];
      this.form3.deleteIds = [];
      this.form4.deleteIds = [];
    },
    // 切换等级
    async leavelChange(newVal) {
      // 弹出确认框
      try {
        await this.$confirm('确定要切换工艺级别吗？切换后当前编辑内容将丢失。', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });

        // 用户确认：更新已确认的值，并加载数据
        this.lastConfirmedRank = newVal;
        // 清空表格选择状态（可选）
        this.form1.deleteIds = [];
        this.form2.deleteIds = [];
        this.form3.deleteIds = [];
        this.form4.deleteIds = [];
        // 清空表格选择状态（可选）
        this.form1.tableData1 = [];
        this.form2.tableData2 = [];
        this.form3.tableData3 = [];
        this.form4.tableData4 = [];
        this.getDetails();
      } catch (error) {
        // 用户取消：恢复为上一次确认的值
        this.rank = this.lastConfirmedRank;
      }
    },
    // 获取工序号
    getProcessNo(table, index = 0) {
      const len = table.length;
      let processNo = (len + index + 1) * 5;

      if (processNo.toString().length === 1) {
        processNo = '000' + processNo;
      } else if (processNo.toString().length === 2) {
        processNo = '00' + processNo;
      } else if (processNo.toString().length === 3) {
        processNo = '0' + processNo;
      } else if (processNo.toString().length === 4) {
        processNo = '' + processNo;
      }
      return processNo;
    },
    // 插入一行
    addTable() {
      this.tempId++;
      if (this.activeName == '1') {
        this.form1.tableData1.push({
          _tempId: this.tempId, // 临时唯一标识
          id: null,
          processNo: this.getProcessNo(this.form1.tableData1),
          isMain:'0'
        });
      }
      if (this.activeName == '2') {
        this.form2.tableData2.push({
          _tempId: this.tempId, // 临时唯一标识
          id: null,
          trialNo: this.treeNodes.processNo + '-' + this.getProcessNo(this.form2.tableData2),
        });
      }
      if (this.activeName == '3') {
        let trialNo_ = '';
        if (this.treeNodes.children.length <= 0) {
          trialNo_ = this.treeNodes.processNo;
        }else{
          let projectInfo = this.treeNodes.children.filter(item => item.rawData.projectName.indexOf('尺寸检测')>-1);
          if(projectInfo.length>0){
            trialNo_ = projectInfo[0].rawData.trialNo;
          }else{
            trialNo_ = this.treeNodes.processNo;
          }
        }

        this.form3.tableData3.push({
          _tempId: this.tempId, // 临时唯一标识
          id: null,
          trialNo: trialNo_,
        });
      }
      if (this.activeName == '4') {
        this.form4.tableData4.push({
          _tempId: this.tempId, // 临时唯一标识
          id: null,
          trialNo: this.getProcessNo(this.form4.tableData4),
        });
      }
    },
    handleSelectionChange1(val) {
      this.form1.selectIds = val.map(row => row.id || row._tempId);
    },
    handleSelectionChange2(val) {
      this.form2.selectIds = val.map(row => row.id || row._tempId);
    },
    handleSelectionChange3(val) {
      this.form3.selectIds = val.map(row => row.id || row._tempId);
    },
    handleSelectionChange4(val) {
      this.form4.selectIds = val.map(row => row.id || row._tempId);
    },
    // 删除选择行
    delTable() {
      const active = this.activeName;
      let message = '请至少选择一条数据进行删除';

      if (active === '1') {
        if (this.form1.selectIds.length === 0) {
          this.$message.warning(message);
          return;
        }
        this.form1.deleteIds = this.form1.tableData1
          .filter(row => this.form1.selectIds.includes(row.id || row._tempId))
          .filter(row => row.id != null && row.id !== '') // 只保留有真实 id 的行
          .map(row => row.id);
        this.form1.tableData1 = this.form1.tableData1.filter(row => {
          const key = row.id || row._tempId;
          return !this.form1.selectIds.includes(key);
        });

        this.form1.selectIds = []; // 清空选中
      } else if (active === '2') {
        if (this.form2.selectIds.length === 0) {
          this.$message.warning(message);
          return;
        }
        this.form2.deleteIds = this.form2.tableData2
          .filter(row => this.form2.selectIds.includes(row.id || row._tempId))
          .filter(row => row.id != null && row.id !== '')
          .map(row => row.id);

        this.form2.tableData2 = this.form2.tableData2.filter(row => {
          const key = row.id || row._tempId;
          return !this.form2.selectIds.includes(key);
        });
        this.form2.selectIds = [];
      } else if (active === '3') {
        if (this.form3.selectIds.length === 0) {
          this.$message.warning(message);
          return;
        }
        this.form3.deleteIds = this.form3.tableData3
          .filter(row => this.form3.selectIds.includes(row.id || row._tempId))
          .filter(row => row.id != null && row.id !== '')
          .map(row => row.id);
        this.form3.tableData3 = this.form3.tableData3.filter(row => {
          const key = row.id || row._tempId;
          return !this.form3.selectIds.includes(key);
        });
        this.form3.selectIds = [];
      } else if (active === '4') {
        if (this.form4.selectIds.length === 0) {
          this.$message.warning(message);
          return;
        }
        this.form4.deleteIds = this.form4.tableData4
          .filter(row => this.form4.selectIds.includes(row.id || row._tempId))
          .filter(row => row.id != null && row.id !== '')
          .map(row => row.id);

        this.form4.tableData4 = this.form4.tableData4.filter(row => {
          const key = row.id || row._tempId;
          return !this.form4.selectIds.includes(key);
        });
        this.form4.selectIds = [];
      }

      this.$message.success('删除成功');
    },
    checkingProNo(table) {
      // 验证工序号是否重复
      const tableData = table;
      const proNoList = [];
      tableData.forEach(item => {
        proNoList.push(item.processNo);
      });
      const list = Array.from(new Set(proNoList));
      if (tableData.length !== list.length) {
        // return this.$message.warning('工序号重复,请修改！');
        return true;
      } else {
        return false;
      }
    },
    saveInfo() {
      if (this.activeName == '1') {
        // 调用单个 Form 的校验方法
        this.$refs.tableForm1.validate(async (isValid, invalidFields) => {
          if (isValid) {
            if (Object.keys(this.treeNodes).length == 0) {
              return this.$message.warning('请先选择左侧组织树数据');
            }
            if (this.checkingProNo(this.form1.tableData1)) {
              return this.$message.warning('工序号重复,请修改！');
            }
            // 验证涂色标的工时是否大于0
            let isReturn = 0;
            this.form1.tableData1.forEach(item => {
              if (item.processName === '涂色标' && item.hourQuota <= 0) {
                isReturn = 1;
              }
            });
            // 验证主工序 是否设置
            let noMainPro = false;
            const arr = [];
            const pidList = [];
            const tableData = this.form1.tableData1;
            tableData.forEach(item => {
              if (item.isMain) {
                noMainPro = true;
              }
              arr.push(item.processName);
              if (item.processName == '镀后检验') {
                pidList.push(item.pid);
              }
            });

            if (!noMainPro) {
              return this.$message.error('此套工艺未含主工序，请设置主工序!!!');
            }
            if (isReturn == 1) {
              return this.$message.warning('涂色标的工时定额必须大于0,请修改！');
            }
            // const res = await getPartDetail(this.partId);
            let dsCraftMold = this.partInfoData;

            if (dsCraftMold.markingsTest == '1') {
              if (!arr.includes('涂色标')) {
                return this.$message.warning('该工艺包含的工序必须包含涂色标');
              }
            }

            // 验证热处理工序是否存在
            if (dsCraftMold.hardness == '1') {
              if (!arr.includes('热处理检验')) {
                this.$message({
                  dangerouslyUseHTMLString: true,
                  message:
                    '<strong style="font-size:22px" >' +
                    '该零件硬度为 ' +
                    dsCraftMold.hardness +
                    ', 没有热处理检验工序。' +
                    '</strong>',
                  showClose: true,
                  duration: 7000,
                  type: 'warning',
                });
              } else {
                this.$message({
                  dangerouslyUseHTMLString: true,
                  message:
                    '<strong style="font-size:22px" >' +
                    '该零件硬度为 ' +
                    dsCraftMold.hardness +
                    ', 存在热处理检验工序。' +
                    '</strong>',
                  showClose: true,
                  duration: 7000,
                  type: 'success',
                });
              }
            }

            // 验证镀种存在 SB 判断工序是否存在喷砂
            if (dsCraftMold.plate != null && dsCraftMold.plate.indexOf('SB') != -1) {
              if (!arr.includes('喷砂')) {
                this.$message({
                  dangerouslyUseHTMLString: true,
                  message:
                    '<strong style="font-size:22px" >' +
                    '该镀种存在 SB  ' +
                    dsCraftMold.plate +
                    ', 没有喷砂工序。' +
                    '</strong>',
                  showClose: true,
                  duration: 7000,
                  type: 'warning',
                });
              }
            }

            // 判断镀种中是否包含 不钝化
            if (dsCraftMold.plate != null && dsCraftMold.plate.indexOf('不钝化') != -1) {
              // 如果存在镀后检验工序
              if (pidList.length > 0) {
                // 拿出所有镀后检验工序对应的实验项目
                let isExist = 0;
                const res1 = await this.$ajax.post('dsMatingInfo/loadMatingInfoByPidList', {
                  pidList: pidList,
                  miType: 1,
                });
                res1.data.forEach(item => {
                  if (item.trialItem.indexOf('可焊性') != -1) {
                    // 如果其中存在可焊性实验项目
                    isExist = 1;
                  }
                });
                if (isExist != 1) {
                  this.$message({
                    dangerouslyUseHTMLString: true,
                    message:
                      '<strong style="font-size:22px" >' +
                      '该零件镀种包含不钝化 ' +
                      dsCraftMold.plate +
                      ', 镀后检验中未设置可焊性检测试验项目。' +
                      '</strong>',
                    showClose: true,
                    duration: 7000,
                    type: 'warning',
                  });
                }
              }
            }
            // // yingGuangJian  荧光检验证
            if (dsCraftMold.fluorescenceCheck == '1') {
              let flag = false;
              arr.forEach(item => {
                if (item.indexOf('荧光检') !== -1) {
                  flag = true;
                }
              });
              if (!flag) {
                return this.$message({
                  dangerouslyUseHTMLString: true,
                  message:
                    '<strong style="font-size:22px" >' +
                    '该工艺包含的工序必须包含荧光检工序' +
                    '</strong>',
                  showClose: true,
                  duration: 7000,
                  type: 'warning',
                });
              }
            }
            // // heatTreatmentTest  热处理检验验证
            if (dsCraftMold.hotDispose == '1') {
              if (!arr.includes('热处理检验')) {
                return this.$message({
                  dangerouslyUseHTMLString: true,
                  message:
                    '<strong style="font-size:22px" >' +
                    '该工艺包含的工序必须包含热处理检验工序' +
                    '</strong>',
                  showClose: true,
                  duration: 7000,
                  type: 'warning',
                });
              }
            }

            // // penmark  喷码验证
            if (dsCraftMold.inkjetPrinting == '1') {
              let flag = false;
              arr.forEach(item => {
                if (item.indexOf('喷码') !== -1) {
                  flag = true;
                }
              });
              if (!flag) {
                return this.$message({
                  dangerouslyUseHTMLString: true,
                  message:
                    '<strong style="font-size:22px" >' +
                    '该工艺包含的工序必须包含喷码工序' +
                    '</strong>',
                  showClose: true,
                  duration: 7000,
                  type: 'warning',
                });
              }
            }
            this.craftLoading = true;

            // 处理传参
            if (this.treeNodes.rawData.qualityGradeCode) {
              let qualityInfo = this.rankList.find(
                item => item.code == this.treeNodes.rawData.qualityGradeCode
              );
              // this.treeNodes.rawData.qualityGradeName = qualityInfo.name;
            }
            let query_ = {
              dsPart: this.partInfoData, //零件信息
              craft: this.treeNodes.rawData, //工艺信息
              processList: this.form1.tableData1, //工序集合
              processDeleteIds: this.form1.deleteIds, //删除ids
            };

            authorizedAccomplish2(query_)
              .then(res => {
                this.$message.success('保存成功');
                this.craftLoading = false;
                if (this.treeLeave == 1) {
                  this.getDetails();
                }

                this.updateTreeAfterSave(res.data.data);
              })
              .catch(err => {
                this.craftLoading = false;
              });
          }
        });
      }
      if (this.activeName == '2') {
        this.$refs.tableForm2.validate((isValid, invalidFields) => {
          if (isValid) {
            // 🔍 新增：校验是否包含“耐蚀性检测”
            const hasCorrosionTest = this.form2.tableData2.some(
              item =>
                item.projectName?.includes('耐蚀性检测') ||
                (item.projectCode &&
                  this.projectOptions
                    .find(p => p.id === item.projectCode)
                    ?.name?.includes('耐蚀性检测'))
            );

            // 如果父节点备注包含 'HTBY' 且未设置耐蚀性检测，则报错
            if (this.parentData.rawData?.remarks?.includes('HTBY') && !hasCorrosionTest) {
              this.$message.error('备注包含 HTBY 时，检测项目必须包含耐蚀性检测！');
              return;
            }
            this.craftLoading = true;
            let query_ = {
              processEntity: this.treeNodes.rawData.processInfo, //工序
              processProjectEntityList: this.form2.tableData2, //项目
              deleteIds: this.form2.deleteIds, //删除ids
            };

            saveProcessProjectSave(query_).then(res => {
              this.$message.success('保存成功');
              this.craftLoading = false;
              // ✅ 更新工序节点下的项目数据
              if (this.treeLeave === 3) {
                this.treeNodes.rawData.projectList = this.form2.tableData2;
                this.updateTreeNodeProject();
                this.refreshTableData(); // ✅ 刷新右侧表格
              }
            });
          }
        });
      }
      if (this.activeName == '3') {
        this.$refs.tableForm3.validate((isValid, invalidFields) => {
          if (isValid) {
            this.craftLoading = true;
            let query_ = {
              processEntity: this.treeNodes.rawData.processInfo, //工序
              processMeasuringToolEntities: this.form3.tableData3, //尺寸量具
              deleteIds: this.form3.deleteIds, //删除ids
            };
            saveProcessMeasuringTool(query_).then(res => {
              this.$message.success('保存成功');
              this.craftLoading = false;
              // ✅ 更新工序节点下的量具数据
              if (this.treeLeave === 3) {
                this.treeNodes.rawData.measuringToolList = this.form3.tableData3;
                this.updateTreeNodeProject();
                this.refreshTableData(); // ✅ 刷新右侧表格
              }
            });
          }
        });
      }
      if (this.activeName == '4') {
        this.$refs.tableForm4.validate((isValid, invalidFields) => {
          if (isValid) {
            this.craftLoading = true;
            let query_ = {
              processEntity: this.treeNodes.rawData.processInfo, //工序
              processMoldToolEntities: this.form4.tableData4, //尺寸量具
              deleteIds: this.form4.deleteIds, //删除ids
            };
            saveProcessMoldTool(query_).then(res => {
              this.$message.success('保存成功');
              this.craftLoading = false;
              // ✅ 更新工序节点下的工装数据
              if (this.treeLeave === 3) {
                this.treeNodes.rawData.moldToolList = this.form4.tableData4;
                this.updateTreeNodeProject();
                this.refreshTableData(); // ✅ 刷新右侧表格
              }
            });
          }
        });
      }
    },
    // ✅ 保存后更新树结构（不调用接口）
    updateTreeAfterSave(saveData) {
      // 1. 更新当前选中节点的 rawData
      if (this.treeLeave === 1 && saveData) {
        console.log('updateTreeAfterSave', this.treeNodes);
        // this.treeNodes.rawData = { ...this.treeNodes.rawData, ...saveData };
      }
      if (this.treeLeave === 2 && saveData) {
        this.treeNodes.rawData = { ...this.treeNodes.rawData, ...saveData };
        this.treeNodes.processList = this.form1.tableData1;
      }

      // 2. 更新 data 树形结构中对应的工艺节点
      const updateTreeNode = nodes => {
        for (let node of nodes) {
          if (node.level === 2 && node.id === this.treeNodes.id) {
            // 更新工艺节点信息
            if (saveData) {
              node.rawData = { ...node.rawData, ...saveData };
              node.label = `${saveData.roamNo || '临时工艺'}-${saveData.craftNo || '工艺文件'}`;
            }

            // 更新工序子节点
            node.processList = this.form1.tableData1;
            node.children = this.form1.tableData1.map(process => ({
              id: process.id || `process_${Date.now()}_${Math.random()}`,
              label: process.processName || '未知工序',
              level: 3,
              rawData: {
                processInfo: process,
                projectList: process.processProjectList || [],
                measuringToolList: process.measuringToolList || [],
                moldToolList: process.moldToolList || [],
              },
              children: (process.processProjectList || []).map(project => ({
                id: project.id || `project_${Date.now()}_${Math.random()}`,
                label: project.projectName || '未知项目',
                level: 4,
                disabled: true,
                rawData: project,
              })),
            }));
            break;
          }
          if (node.children && node.children.length > 0) {
            updateTreeNode(node.children);
          }
        }
      };

      updateTreeNode(this.data);

      // ✅ 3. 刷新右侧表格数据（从树结构同步）
      this.refreshTableData();
    },
    refreshTableData() {
      this.$nextTick(() => {
        if (this.treeLeave === 2) {
          // 工艺节点：刷新工序表格
          this.form1.tableData1 = [...(this.treeNodes.processList || [])];
        } else if (this.treeLeave === 3) {
          // 工序节点：刷新项目、量具、工装表格
          const { projectList, measuringToolList, moldToolList } = this.treeNodes.rawData;
          this.form2.tableData2 = [...(projectList || [])];
          this.form3.tableData3 = [...(measuringToolList || [])];
          this.form4.tableData4 = [...(moldToolList || [])];
        }
      });
    },
    // ✅ 更新工序节点下的项目数据
    updateTreeNodeProject() {
      const updateTreeNode = nodes => {
        for (let node of nodes) {
          if (node.level === 3 && node.id === this.treeNodes.id) {
            node.rawData = {
              ...node.rawData,
              projectList: this.form2.tableData2,
              measuringToolList: this.form3.tableData3,
              moldToolList: this.form4.tableData4,
            };
            // 更新项目子节点
            node.children = (this.form2.tableData2 || []).map(project => ({
              id: project.id || `project_${Date.now()}_${Math.random()}`,
              label: project.projectName || '未知项目',
              level: 4,
              disabled: true,
              rawData: project,
            }));
            break;
          }
          if (node.children && node.children.length > 0) {
            updateTreeNode(node.children);
          }
        }
      };

      updateTreeNode(this.data);

      // ✅ 刷新右侧表格
      this.refreshTableData();
    },
  },
};
</script>
<style lang="scss" scoped>
.box-card {
  display: flex;
  flex-direction: row;
  height: calc(100vh - 200px);
  overflow: hidden;
  border: 1px solid #ccc;

  .process-left {
    width: 240px;
    min-width: 240px;
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    // border: 1px solid #ccc;
    background: #fff;
    border-right: 1px solid #ccc;

    .process-select {
      padding: 12px;
      background: #e4e7ed;
      position: sticky;
      top: 0;
      z-index: 10;
      border-bottom: 1px solid #dcdfe6;
    }

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #c1c1c1;
      border-radius: 3px;

      &:hover {
        background-color: #a8a8a8;
      }
    }

    &::-webkit-scrollbar-track {
      background-color: #f1f1f1;
    }
  }

  :deep(.el-form-item) {
    margin-bottom: 0px !important;
  }

  .process-right {
    flex: 1;
    // height: 100%;
    overflow-y: auto;
    padding: 12px;
    // border: 1px solid #ccc;
    border-left: 0;
    background: #fff;

    .table-btn {
      width: 100%;
      height: 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .table-btn-left {
        display: flex;
        gap: 8px;
      }

      .table-btn-right {
        display: flex;
        gap: 8px;
      }
    }

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #c1c1c1;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
      background-color: #f1f1f1;
    }
  }
}

:deep(.el-tree) {
  height: auto;
  padding: 0px 0;

  .el-tree-node__content {
    height: 26px;

    &:hover {
      // background-color: #f5f7fa;
    }
  }
  .el-tree-node__label {
    font-size: 14px;
  }
}
:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: rgba(40, 76, 135, 0.9) !important;

  .el-tree-node__label {
    color: #fff;
  }
}
:deep(.el-table__header th.el-table__cell) {
  height: 40px !important;
  min-height: 40px !important;
  line-height: 40px !important;
  padding: 0 10px !important;
  background-color: #f5f7fa;
  font-weight: 600;
}

:deep(.el-table__body td.el-table__cell) {
  height: 50px !important;
  min-height: 50px !important;
  line-height: 50px !important;
  padding: 0 10px !important;
}

:deep(.el-table .cell) {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-table .el-form-item) {
  margin-bottom: 0 !important;
  height: 100%;
  display: flex;
  align-items: center;

  .el-input,
  .el-select {
    width: 100%;
  }
}

.custom-context-menu {
  position: fixed;
  z-index: 2000;
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 4px 0;
}

.context-menu .el-button {
  display: block;
  width: 100%;
  text-align: left;
  padding: 6px 12px;
  margin: 0;
}
:deep(.el-table thead) {
  height: 36px !important; /* 设置你想要的高度 */
  line-height: 36px !important;
}
</style>
