<template>
  <div class="box-card">
    <div class="process-left">
      <el-tree
        style="width: 240px"
        :data="data"
        :props="defaultProps"
        @node-click="handleNodeClick"
        :default-expand-all="true"
        :expand-on-click-node="false"
      />
    </div>
    <div class="process-right">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="工序" name="1" v-if="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">
          <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="submit()" :loading="craftLoading">保存</el-button>
          </div>
        </div>
        <div class="table-btn-right" v-if="activeName == '1'">
          <div class="table-btn-right-box">
            <!-- <el-input v-model="reworkNoNum" type="number" placeholder="请输入" style="width: 220px; margin-right: 12px"></el-input>
            <el-button type="primary" @change="reworkNoNumSave()">保存</el-button> -->
            <el-input placeholder="请输入内容" v-model="reworkNoNum">
              <template #append>
                <el-button @click="reworkNoNumSave()">保存</el-button>
              </template>
            </el-input>
          </div>
          <div class="table-btn-right-box">
            <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()">导入模板</el-button>
          </div>
          <!-- <div class="table-btn-right-box">
            <el-select
              v-model="processLevel"
              placeholder="选择零件"
              style="width: 220px; margin-right: 12px"
              clearable
              filterable
            >
              <el-option label="模板一" value="1" />
              <el-option label="模板二" value="2" />
              <el-option label="模板三" value="3" />
            </el-select>
            <el-button type="primary" @click="getProcessList()">零件导入</el-button>
          </div> -->
          <!-- <div class="table-btn-right-box">
            <el-button type="primary">历史工序</el-button>
          </div> -->
        </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%"
          v-if="activeName == '1'"
          @selection-change="handleSelectionChange1"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="processInfo.reworkNo" label="返工序号">
            <template #header>
              <span><i style="color: red">*</i>返工序号</span>
            </template>
            <template #default="scope">
              <el-form-item
                :prop="`tableData1[${scope.$index}].processInfo.reworkNo`"
                :rules="formRules1.reworkNo"
              >
                <el-input
                  v-model="scope.row.processInfo.reworkNo"
                  placeholder="请输入"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
            </template>
          </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}].processInfo.processNo`"
                :rules="formRules1.processNo"
              >
                <el-input
                  v-model="scope.row.processInfo.processNo"
                  placeholder="请输入"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="工序">
            <template #header>
              <span><i style="color: red">*</i>工序</span>
            </template>
            <template #default="scope">
              <el-form-item
                :prop="`tableData1[${scope.$index}].processInfo.ppsId`"
                :rules="formRules1.ppsId"
              >
                <el-select
                  v-model="scope.row.processInfo.ppsId"
                  placeholder="请选择"
                  clearable
                  filterable
                  @change="processChange(scope.row, scope.$index)"
                >
                  <el-option
                    v-for="(item, index) in processSetOption"
                    :key="index"
                    :label="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}].processInfo.caId`"
                :rules="formRules1.caId"
              >
                <el-select
                  v-model="scope.row.processInfo.caId"
                  placeholder="请选择"
                  clearable
                  filterable
                  @change="craftChange(scope.row, scope.$index)"
                >
                  <el-option
                    v-for="(item, index) in craftAbilityOption"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="makeMemo" label="工序描述">
            <template #header>
              <span><i style="color: red">*</i>工序描述</span>
            </template>
            <template #default="scope">
              <el-form-item
                :prop="`tableData1[${scope.$index}].processInfo.makeMemo`"
                :rules="formRules1.makeMemo"
              >
                <el-input
                  v-model="scope.row.processInfo.makeMemo"
                  placeholder="请输入"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="makeTeam" label="加工班组">
            <template #default="scope">
              <el-select
                v-model="scope.row.processInfo.makeTeam"
                placeholder="请选择"
                clearable
                filterable
              >
                <el-option
                  v-for="(item, index) in teamOptions"
                  :label="item.tsName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="ocId" label="外协厂商">
            <template #default="scope">
              <el-input
                v-model="scope.row.processInfo.ocId"
                placeholder="请输入"
                style="width: 100%"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="cruxProcess" label="主工序">
            <template #header>
              <span><i style="color: red">*</i>主工序</span>
            </template>
            <template #default="scope">
              <el-form-item
                :prop="`tableData1[${scope.$index}].processInfo.cruxProcess`"
                :rules="formRules1.cruxProcess"
              >
                <el-select
                  v-model="scope.row.processInfo.cruxProcess"
                  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"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="date" label="工序号">
            <template #header>
              <span><i style="color: red">*</i>工序号</span>
            </template>
            <template #default="scope">
              <el-form-item
                :prop="`tableData2[${scope.$index}].trialNo`"
                :rules="formRules2.trialNo"
              >
                <el-input
                  v-model="scope.row.trialNo"
                  placeholder="请输入"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="date" 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"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="date" 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"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="date" label="标准值">
            <template #default="scope">
              <el-input
                v-model="scope.row.projectStandard"
                placeholder="请输入"
                style="width: 100%"
              ></el-input>
            </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"
          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="date" 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="date" 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="date" 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="date" label="图纸尺寸">
            <template #default="scope">
              <el-input
                v-model="scope.row.toolInfo"
                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"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="date" 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="date" 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="date" 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="date" 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="date" 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="date" 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 {
  getList,
  getPartDetail,
  getProcessAuthorized,
  getModelList,
  getModelDetailList,
  reworkAuthorizedAccomplish,
  getProcessList,
  getProcessSetList,
  getCraftAbilityList,
  getProject,
  getTeamSetList,
  getStandardList,
} from '@/api/processManagement/taskProcessing';
// import {getPartList} from '@/api/orderManagement/getPartList';
import { getDictionary } from '@/api/system/dict';

export default {
  name: 'CraftIndex',
  components: {},
  props: {
    height: {
      type: Number,
      default: 600,
    },
    partId: {
      type: [Number, String],
      default: null,
    },
    dialogType: {
      type: String,
      default: '',
    },
    updateRow: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      craftLoading: false,
      processLevel: null,
      data: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      form: {
        zhongyaodu: '',
        qualityGrade: '', //生产标识
        beizhu: '', //备注
      },
      rules: {
        zhongyaodu: [{ required: true, message: '请选择', trigger: 'blur' }],
      },
      priorityList: [
        {
          label: '本次使用',
          value: 1,
        },
        {
          label: '正式工艺',
          value: 2,
        },
        {
          label: '临时工艺',
          value: 3,
        },
      ],
      rankList: [
        {
          label: '一级',
          value: 1,
        },
        {
          label: '二级',
          value: 2,
        },
        {
          label: '三级',
          value: 3,
        },
      ],
      activeName: '1',
      treeLeave: 2, //组织树选中层级

      modelLevel: null,
      modelOption: [], //工艺模板列表数据
      partInfoData: {}, //零件信息

      form1: {
        tableData1: [], //工序
        deleteIds: [],
        selectIds: [], //选中ID
      },
      form2: {
        tableData2: [], //项目
        deleteIds: [],
        selectIds: [], //选中ID
      },
      form3: {
        tableData3: [], //量具
        deleteIds: [],
        selectIds: [], //选中ID
      },
      form4: {
        tableData4: [], //工装
        deleteIds: [],
        selectIds: [], //选中ID
      },
      formRules1: {
        reworkNo: [{ required: true, message: '请输入', trigger: ['change', 'submit'] }],
        processNo: [{ required: true, message: '请输入', trigger: ['change', 'submit'] }],
        ppsId: [{ required: true, message: '请选择', trigger: ['change', 'submit'] }],
        craftName: [{ required: true, message: '请选择', trigger: ['change', 'submit'] }],
        proDes: [{ required: true, message: '请选择', trigger: ['change', 'submit'] }],
        proHours: [{ required: true, message: '请输入', trigger: ['change', 'submit'] }],
        cruxProcess: [{ required: true, message: '请选择', trigger: ['change', 'submit'] }],
        makeMemo: [{ required: true, message: '请选择', trigger: ['change', 'submit'] }],
      },
      formRules2: {
        trialNo: [{ required: true, message: '请输入', trigger: ['change', 'submit'] }],
        projectCode: [{ required: true, message: '请选择', trigger: ['change', 'submit'] }],
        projectStandard: [{ required: true, message: '请输入', trigger: ['change', 'submit'] }],
        proHours: [{ required: true, message: '请输入', trigger: ['change', 'submit'] }],
      },
      formRules3: {
        trialNo: [{ required: true, message: '请输入', trigger: ['change', 'submit'] }],
        testType: [{ required: true, message: '请选择', trigger: ['change', 'submit'] }],
        tool: [{ required: true, message: '请选择', trigger: ['change', 'submit'] }],
      },
      formRules4: {
        trialNo: [{ required: true, message: '请输入', trigger: ['change', 'submit'] }],
        moldCode: [{ required: true, message: '请输入', trigger: ['change', 'submit'] }],
      },
      processSetOption: [],
      craftAbilityOption: [],
      treeNodes: {},
      reworkNoNum: null, //返工序号
      projectOptions: [], //检验项目维护
      teamOptions: [], //班组
      standardList: [], //标准
      tempId: 0,
      filteredList: [],
      dictionaryData: [],
    };
  },
  mounted() {
    this.getDetails();
    this.getModelList();
    this.getProcessSetList();
    this.getCraftAbilityList();
    this.getProject();
    this.getTeamSetList();
    this.getStandardList();
    this.getDictionary();
  },
  methods: {
    // getPartList(){
    //   getPartList().then(res => {
    //     this.partInfoData = res.data.data;
    //   });
    // },
    // 获取涂色标、涂色带、涂箭头的系数
    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;
      });
    },
    getTeamSetList() {
      getTeamSetList().then(res => {
        this.teamOptions = 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.processInfo.ppsId);
      this.form1.tableData1[index].processInfo.ppsName = selectName.name;
      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 = sum_;
      }
    },
    // 获取工艺能力名字
    craftChange(row, index) {
      let selectName = this.craftAbilityOption.find(item => item.id == row.processInfo.caId);
      this.form1.tableData1[index].processInfo.craftName = selectName.name;
    },
    reworkNoNumSave() {
      this.form1.tableData1.forEach(item => {
        item.reworkNo = this.reworkNoNum;
      });
    },
    // 工序列表查询
    getProcessSetList() {
      getProcessSetList().then(res => {
        this.processSetOption = res.data.data;
      });
    },
    // 工艺能力列表查询
    getCraftAbilityList() {
      getCraftAbilityList().then(res => {
        this.craftAbilityOption = res.data.data;
      });
    },
    // 工艺模板列表
    getModelList() {
      getModelList().then(res => {
        this.modelOption = res.data.data;
        this.filteredList = [...this.modelOption];
      });
    },
    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;
      });
    },
    // 导入模板
    modelLevelChange() {
      getModelDetailList({ Id: this.modelLevel }).then(res => {
        const templateData = res.data.data.proDetailVOList;
        const existing = [...this.form1.tableData1];
        // 将模板中的工序数据映射为表格所需格式
        const mappedData = templateData.map((item, index) => {
          // 如果模板中的字段和表格字段一致，可直接使用；否则需转换
          return {
            processInfo: {
              id: null, // 新增时通常设为 null
              processNo: this.getProcessNo(this.form1.tableData1), // 自动生成工序号
              processCode: item.processCode, // 假设模板中有 processCode 或 id
              processName: item.processName,
              craftCode: item.craftCode,
              craftName: item.craftName,
              proDes: item.proDes,
              proHours: item.proHours || '',
              setoutHours: item.setoutHours || '',
              isMain: item.isMain || '0',
            },
            // 其他字段按需补充...
          };
        });
        // 赋值（方式1）或追加（方式2）
        this.form1.tableData1 = [...existing, ...mappedData]; // 追加模式

        // 先保存工序信息
        this.saveProcessInfo().then(() => { 
        });

        this.$message.success('模板导入成功');
      });
    },
    // 导入零件信息
    getProcessList() {
      getProcessList().then(res => {});
    },
    // 获取零件信息详情数据
    getDetails() {
      getProcessAuthorized({
        partId: this.partId,
        taskId: this.updateRow.id,
        version: this.updateRow.version,
      }).then(res => {
        this.data = this.transformCraftTree(res.data.data);
        this.partInfoData = res.data.data;
      });
    },
    // 组织树转换
    transformCraftTree(responseData) {
      const { partInfo, craftList } = responseData;
      const partCode = partInfo?.partCode || '未知零件';

      const tree = [
        {
          label: partCode,
          disabled: true,
          rawData: partInfo,
          children: (craftList || []).map(craft => {
            const { craftInfo, processList = [] } = craft;
            return {
              ...craft,
              label: `${craftInfo?.reworkOrder || '返工单'}`,
              children: processList.map(process => {
                const ppsName =
                  process.processInfo.ppsName || process.processInfo.name || process.processInfo.processName || '未知工序';

                // 将 projectList 转为第四级子节点
                const projectChildren = (process.projectList || []).map(project => ({
                  ...project,
                  label: project.projectName || '未知检验项目', // 👈 显示项目名称
                  disabled: true, // 通常项目不可点击
                  isProjectNode: true, // 可选：标记类型，便于后续处理
                }));

                return {
                  ...process,
                  label: ppsName,
                  // 关键：把 projectList 作为 children
                  children: projectChildren.length > 0 ? projectChildren : undefined,
                  // 如果还需要保留原始列表供其他逻辑使用（如提交），可额外保留
                  projectList: process.projectList || [],
                  measuringToolList: process.measuringToolList || [],
                  moldToolList: process.moldToolList || [],
                };
              }),
            };
          }),
        },
      ];

      return tree;
    },
    // 组织树点击
    handleNodeClick(nodes, node, self) {
      if (nodes.disabled) {
        return false;
      }
      this.treeNodes = nodes;
      this.treeLeave = node.level;
      // 清空现有表格数据
      this.form1.tableData1 = [];
      this.form2.tableData2 = [];
      this.form3.tableData3 = [];
      this.form4.tableData4 = [];
      // 根据节点层级切换标签页
      if (this.treeLeave === 2) {
        this.activeName = '1';
        this.form1.tableData1 = nodes.processList;
      }
      // 根据节点层级加载对应数据
      if (this.treeLeave === 3) {
        this.activeName = '2';
        // 三级节点：工序级，加载工序相关数据
        const { processInfo, projectList, measuringToolList, moldToolList } = nodes;
        // 加载项目表格数据
        this.form2.tableData2 = projectList;
        // 加载量具表格数据
        this.form3.tableData3 = measuringToolList;
        // 加载工装表格数据
        this.form4.tableData4 = moldToolList;
      }
    },
    // 右侧tab切换
    handleClick(value) {
      this.form1.deleteIds = [];
      this.form2.deleteIds = [];
      this.form3.deleteIds = [];
      this.form4.deleteIds = [];
    },
    // 切换等级
    leavelChange() {
      this.getDetails();
      this.form1.deleteIds = [];
      this.form2.deleteIds = [];
      this.form3.deleteIds = [];
      this.form4.deleteIds = [];
    },
    // 获取工序号
    getProcessNo(table) {
      const len = table;
      let processNo = (len.length + 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({
          processInfo: {
            _tempId: this.tempId, // 临时唯一标识
            id: null,
            processNo: this.getProcessNo(this.form1.tableData1),
          },
        });
      }
      if (this.activeName == '2') {
        this.form2.tableData2.push({
          _tempId: this.tempId, // 临时唯一标识
          id: null,
          trialNo: this.getProcessNo(this.form2.tableData2),
        });
      }
      if (this.activeName == '3') {
        this.form3.tableData3.push({
          _tempId: this.tempId, // 临时唯一标识
          id: null,
          trialNo: this.getProcessNo(this.form3.tableData3),
        });
      }
      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.processInfo.id || row.processInfo._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;
        }

        // 收集需要通过 API 删除的真实 ID（已保存的工序）
        this.form1.deleteIds = this.form1.tableData1
          .filter(row => {
            const key = row.processInfo.id || row.processInfo._tempId;
            return this.form1.selectIds.includes(key);
          })
          .filter(row => row.processInfo.id != null && row.processInfo.id !== '') // 仅已保存的有 id
          .map(row => row.processInfo.id);

        // 从表格中移除所有选中行（包括临时行）
        this.form1.tableData1 = this.form1.tableData1.filter(row => {
          const key = row.processInfo.id || row.processInfo._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('删除成功');
    },
    submit() {
      if (this.activeName == '1') {
        // 调用单个 Form 的校验方法
        this.$refs.tableForm1.validate((isValid, invalidFields) => {
          if (isValid) {
            this.craftLoading = true;
            this.submitData();
          }
        });
      }
      if (this.activeName == '2') {
        this.$refs.tableForm2.validate((isValid, invalidFields) => {
          if (isValid) {
            this.craftLoading = true;
            this.submitData();
          }
        });
      }
      if (this.activeName == '3') {
        this.$refs.tableForm3.validate((isValid, invalidFields) => {
          if (isValid) {
            this.craftLoading = true;
            this.submitData();
          }
        });
      }
      if (this.activeName == '4') {
        this.$refs.tableForm4.validate((isValid, invalidFields) => {
          if (isValid) {
            this.craftLoading = true;
            this.submitData();
          }
        });
      }
    },
    submitData() {
      let newArr = [];

      if (this.treeLeave == 2) {
        this.form1.tableData1.forEach(item => {
          newArr.push({
            ...item.processInfo,
            processProjectVOList: item.projectList || [],
            processMeasuringToolVOList: item.measuringToolList || [],
            processMoldToolVOList: item.moldToolList || [],
          });
        });
      } else {
        newArr.push({
          ...this.treeNodes.processInfo,
          processProjectVOList: this.treeNodes.projectList || [],
          processMeasuringToolVOList: this.treeNodes.measuringToolList || [],
          processMoldToolVOList: this.treeNodes.moldToolList || [],
        });
      }
      let query_ = {
        craft: {
          partId: this.partId,
          reworkOrder: this.partInfoData.craftList[0].craftInfo.reworkOrder,
          partVersions: this.partInfoData.craftList[0].craftInfo.partVersions,
          id: this.partInfoData.craftList[0].craftInfo.id,
        }, //工艺信息
        reworkProcessVOList: newArr,
        reworkProcessDeleteIds: this.form1.deleteIds, //工序删除id
        processProjectDeleteIds: this.form2.deleteIds, //项目删除id
        processMeasuringToolDeleteIds: this.form3.deleteIds, //量具删除id
        processMoldToolDeleteIds: this.form4.deleteIds, //工装删除合集
      };
      reworkAuthorizedAccomplish(query_).then(res => {
        // this.$emit('cancel');
        this.$message.success('保存成功');
        this.craftLoading = false;
        this.getDetails();
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.box-card {
  display: flex;
  flex-direction: row;
  height: calc(100vh - 200px);

  .process-left {
    // padding: 20px;
    border: 1px solid #ccc;

    .process-select {
      padding: 12px;
      background: #e4e7ed;
    }
  }
  :deep(.el-form-item) {
    margin-bottom: 0px !important;
  }
  .process-right {
    padding: 12px;
    flex: 1;
    border: 1px solid #ccc;
    border-left: 0;

    .table-btn {
      width: 100%;
      height: 50px;

      .table-btn-left {
        float: left;
      }

      .table-btn-right {
        float: right;
        display: flex;
        margin-right: 40px;
        .table-btn-right-box {
          margin-right: 12px;
        }
      }
    }
  }
}
:deep(.el-table .el-table__cell) {
  height: 50px !important;
  padding: 0 !important;
  line-height: 50px !important;
}
</style>
