<template>
  <Dialog
    v-model="dialogVisible"
    diaTitle="任务创建"
    width="90%"
    height="800"
    :loading="loadingInterface"
    @close="closeFun"
    show-footer
  >
    <div class="task-content">
      <div class="select-method">
        <span @click="selectMethod = 'template'" :class="selectMethod === 'template'?'current-method':''">从任务模板选择</span>
        <span @click="selectMethod = 'project'" :class="selectMethod === 'project'?'current-method':''">从历史项目选择</span>
      </div>
      <!-- 主内容区（左右分栏） -->
      <div class="main-content">
        <!-- 左侧任务库列表 -->
        <div class="left-panel" v-if="selectMethod === 'template'">
          <div class="top-bar">
            <el-form :inline="true" class="left-form-inline">
              <el-form-item label="工况清单库：">
                <el-select
                  class="loadcase-lib"
                  :teleported="false"
                  v-model='currentLoadcaseLib'
                  :props="{label:'poolName', value:'value'}"
                  value-key="poolName"
                  :fit-input-width="true"
                  @change="changeLoadcaseLibFun"
                >
                  <el-option v-for="item in loadcaseLibList" :key="item.value" :label="item.poolName" :value="item" />
                </el-select>
              </el-form-item>
              <el-form-item label="版本：">
                <el-select
                  class="version"
                  :teleported="false"
                  v-model='currentLoadcaseLibVersionInfo'
                  :props="{label:'poolVersion', value:'value'}"
                  value-key="poolVersion"
                  :fit-input-width="true"
                  @change="changeLoadcaseVersionFun"
                >
                  <el-option v-for="item in loadcaseLibVersionList" :key="item.value" :label="item.poolVersion" :value="item" />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          <div class="left-table">
            <loadCaseTable
              ref="leftPoolTableRef"
              :tableName="TABLE_NAME.TASK_POOL"
              :data="leftPoolTableDataList"
              readonly
              :loading="leftTableLoading"
            >
            </loadCaseTable>
          </div>
        </div>
        <!-- 左侧项目列表 -->
        <div class="left-panel" v-else>
          <div class="top-bar">
            <el-form :inline="true" class="left-form-inline" >
              <el-form-item label="项目：">
                <ProjectSelect
                  v-model="leftCurrentProjectUuid"
                ></ProjectSelect>
              </el-form-item>
              <el-form-item label="阶段：">
                <nodeLevel2Select
                  :projectUuid="leftCurrentProjectUuid"
                  :phaseUuid="leftCurrentPhaseUuid"
                  @change="changeLeftPhaseFun"
                ></nodeLevel2Select>
              </el-form-item>
            </el-form>
          </div>
          <div class="left-table">
            <loadCaseTable
              ref="leftProjectTableRef"
              tableName="PROJECT_TASK_PLANNING"
              :data="leftProjectTableDataList"
              readonly
              :loading="rightTableLoading"
            >
            </loadCaseTable>
          </div>
        </div>

        <!-- 中间箭头按钮 -->
        <div class="arrow-btn">
          <el-button icon="arrow-right" circle @click="transferTask"></el-button>
        </div>

        <!-- 右侧项目任务列表 -->
        <div class="right-panel">
          <div class="right-top-bar">
            <el-form :inline="true" class="right-form-inline">
              <el-form-item label="项目：">
                {{ nodeLevel1Name }}
              </el-form-item>
              <el-form-item label="阶段：">
                <!-- {{ nodeLevel2Uuid }} -->
                <el-select v-if="props.dialogType === 'create'" @change="updateNodeLevel2Uuid" v-model="nodeLevel2Uuid" placeholder="阶段">
                  <el-option
                    v-for="item in nodeLevel2List"
                    :key="item.uuid"
                    :label="item.nodeName"
                    :value="item.uuid"
                  />
                </el-select>
                <nodeLevel2Select
                  v-else
                  ref="nodeLevel2SelectRef"
                  class="phase"
                  :projectUuid="nodeLevel1Uuid"
                  :phaseUuid="nodeLevel2Uuid"
                  @change="updateNodeLevel2Uuid"
                ></nodeLevel2Select>
              </el-form-item>
            </el-form>
          </div>
          <div class="right-table">
            <!-- :loading="rightTableLoading" -->
            <loadCaseTable
              ref="rightTableRef"
              tableName="PROJECT_TASK_PLANNING"
              :modalTableNameList="[TABLE_NAME.TASK_POOL_CATEGORY,TABLE_NAME.PROJECT_TASK_MODAL,TABLE_NAME.TASK_POOL_PERFORMANCE]"
              :data="rightTableData"
              :loading="rightTableLoading"
              :projectUuid="nodeLevel1Uuid"
              :phaseUuid="nodeLevel2Uuid"
              :editMode="true"
              :belongProject="true"
            >
            </loadCaseTable>
            <!-- <loadcase-pro-table
              ref="rightTableRef"
              :columns="rightTableColumns"
              :dataSource="rightTableData"
              :checkStrictly="true"
              :leftVisible="true"
              :needTranslateTag="true"
              :toolbarConfig="{
                enabled: true,
                custom: true,
              }"
              :isRealTimeUpdate="false"
              :showHeader="false"
              :projectUuid="nodeLevel1Uuid"
              :phaseUuid="nodeLevel2Uuid"
            ></loadcase-pro-table> -->
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <div>
        <el-button @click="closeFun">取消</el-button>
        <el-button @click="prePageFun" v-if="props.dialogType === 'create'">上一步</el-button>
        <el-button @click="addOrEditTaskFun">完成</el-button>
      </div>
    </template>
  </Dialog>
</template>
<script lang='ts' setup>
import Dialog from '@/components/common/dialog/index.vue';
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { canAddChild, transformPoolNodesToTree } from '@/utils/node';
import { ElMessage, ElMessageBox } from 'element-plus';
import { cloneDeep } from 'lodash-es';
import { v4 as uuidv4 } from 'uuid';
import { getAllTaskPoolApi, getTaskPoolApi, getTaskPoolVersionsApi } from '@/api/task/taskpool';
import { NODE_TYPE, getTagKeyMap, tagSortList } from '@/utils/enum/node';
import nodeLevel2Select from '@/components/project/nodeLevel2Select.vue';
import { getTaskTreeFun } from '../../projectDetail/components/projectApi';
import { disposeTagKey } from '../../projectDetail/components/project';
import { getTagMapList } from '@/utils/task';
import { modifyNodeTaskPerformanceApi } from '@/api/project/node';
import { TASK_CALCULATE_STATUS, TASK_PROCESS_STATUS } from '@/utils/enum/task';
import dayjs from 'dayjs';
import loadCaseTable from '@/components/common/treeCaseTable/loadCaseTable.vue';
import { getMemberListIds } from '@/utils/task';
import { getUserTenantId } from '@/utils/user';
import ProjectSelect from '@/components/common/projectSelect/index.vue';
import { TABLE_NAME } from '@/utils/enum/tableName';

const props = defineProps<{
  showTaskDialog: boolean;
  dialogType: string;
  nodeLevel1Name: string;
  nodeLevel1Info?: object;
  nodeLevel1Uuid: string;
  nodeLevel2List?: Array<any>;
  projectBeginTime: string;
  projectEndTime: string;
}>();

const dialogVisible = computed(() => {
  return props.showTaskDialog;
});

const getRightVxeRef = () => {
  return rightTableRef?.value?.loadcaseTableRef?.TreeTableRef?.treeTableRef;
};

const getLeftVxeRef = () => {
  if (selectMethod.value === 'template') {
    return leftPoolTableRef?.value?.loadcaseTableRef?.TreeTableRef?.treeTableRef;
  } else {
    return leftProjectTableRef?.value?.loadcaseTableRef?.TreeTableRef?.treeTableRef;
  }
};

const loadingInterface = ref(false);

const emits = defineEmits(['update:showTaskDialog', 'prePageFun', 'completeFun', 'taskComplete']);

const rightTableData = ref<any[]>();

const leftProjectTableRef = ref();

const leftCurrentProjectUuid = ref<string>('');
const leftCurrentPhaseUuid = ref<string>('');

const changeLeftPhaseFun = async(data:any) => {
  // console.log('changeLeftPhaseFun data', data);
  leftCurrentPhaseUuid.value = data.phaseUuid;
  leftProjectTableDataList.value = await getTaskTreeFun(leftCurrentProjectUuid.value, leftCurrentPhaseUuid.value);
  expandTree(leftProjectTableRef.value);
};

const nodeLevel2Uuid = ref('');

const nodeLevel2SelectRef = ref();

const updateNodeLevel2Uuid = async ({ phaseUuid, type }:any) => {
  if (type === 'rollBack') {
    return ;
  }
  const { insertRecords, removeRecords, updateRecords }: any =
    await getRightVxeRef().getRecordset();

  if (removeRecords?.length > 0 || insertRecords?.length > 0 || updateRecords?.length > 0) {
    ElMessageBox.confirm('当前数据有变更，切换后变更数据会丢失，是否继续切换阶段？', '提示', {
      confirmButtonText: '继续切换',
      cancelButtonText: '放弃',
      type: 'warning',
    })
      .then(async () => {
        nodeLevel2Uuid.value = phaseUuid;
        await getNodeLevel3TreeByLevel2Uuid();
      })
      .catch(() => {
        nodeLevel2SelectRef.value.rollBackValue(nodeLevel2Uuid.value);
      });
  } else {
    nodeLevel2Uuid.value = phaseUuid;
    await getNodeLevel3TreeByLevel2Uuid();
  }
  expandTree(rightTableRef.value);
};

const getNodeLevel3TreeByLevel2Uuid = async() => {
  // 创建的场景下不用调接口查询
  if (props.dialogType !== 'create') {
    rightTableLoading.value = true;
    rightTableData.value = await getTaskTreeFun(props.nodeLevel1Uuid, nodeLevel2Uuid.value);
    rightTableLoading.value = false;
  } else {
    rightTableData.value = [];
  }
  nextTick(() => {
    // 待修改
    // rightTableRef.value.changeLevel('全部展开');
  });
};

const expandTree = (treeRef:any) => {
  setTimeout(() => {
    treeRef.loadcaseTableRef.TreeTableRef.treeTableRef.setAllTreeExpand(true);
  }, 200);
};

const selectMethod = ref('template'); // template 模板库 project 历史项目

const transferTask = async () => {
  console.log('getLeftVxeRef()', rightTableRef?.value?.loadcaseTableRef, getLeftVxeRef().getCheckboxRecords());
  if (getLeftVxeRef().getCheckboxRecords().length === 0) {
    ElMessage.warning('请先选择左侧任务节点！');
    return;
  }

  // 右侧表格没数据，左侧只能导入顶层节点
  // if (rightTableRef.value.multipleSelection.length === 0 && rightTableData.value?.length === 0) {
  //   ElMessage.warning('左侧只能勾选顶层节点进行导入！');
  //   return;
  // }

  const rightSelection = getRightVxeRef().getCheckboxRecords();

  if (rightSelection.length > 1) {
    ElMessage.warning('右侧只能选择一个节点进行导入！');
    return;
  }

  const leftMultipleSelection = clearLeftSelectRepeat(getLeftVxeRef().getCheckboxRecords());

  console.log('leftMultipleSelection', leftMultipleSelection);
  const leftInsertArr: any[][] = [];
  for (let index = 0; index < leftMultipleSelection.length; index++) {
    // 右边没勾选时,判断左边选中节点能否放在第一层
    if (rightSelection.length === 0) {
      if ((leftMultipleSelection[index].nodeType !== NODE_TYPE.TASK && leftMultipleSelection[index].nodeType !== NODE_TYPE.PERFORMANCE) || canAddChild({ nodeType: NODE_TYPE.ROOT }, leftMultipleSelection[index].nodeType)) {
        // const rightList = rightTableRef.value.loadcaseTableRef.getTableData().fullData;
        // const rightSelectIndex = rightList.findIndex((item: { nodeName: any; nodeType: any; }) => {
        //   return item.nodeName === leftMultipleSelection[index].nodeName && item.nodeType === leftMultipleSelection[index].nodeType;
        // });
        // // 子节点导入
        // if (rightSelectIndex !== -1) {
        //   rightSelection.push(rightList[rightSelectIndex]);
        // } else {
        //   console.log('左侧完整插入到右侧children中');
        //   // 将左侧选中数据平铺再插入到右侧table
        // leftInsertArr.push(...(await flattenTreeData([leftMultipleSelection[index]], nodeLevel2Uuid.value, nodeLevel2Uuid.value)));
        // }
        console.log('右侧没勾选时，直接导入到右侧顶层');
        // 右侧没勾选时，直接导入到右侧顶层
        leftInsertArr.push(...(flattenTreeData([leftMultipleSelection[index]], nodeLevel2Uuid.value, nodeLevel2Uuid.value)));
      } else {
        ElMessage.warning('右侧需要选择一个节点才能进行导入！');
        return;
      }
    }
    else {
      console.log(' 同类型的可以从左往右导入，不同类型的需要判断能否作为子节点导入');
      // 同类型的可以从左往右导入，不同类型的需要判断能否作为子节点导入
      if (
        rightSelection[0].nodeType === leftMultipleSelection[index].nodeType
        ||
      canAddChild(rightSelection[0], leftMultipleSelection[index].nodeType)
      ) {
        await leftInsertToRight([leftMultipleSelection[index]], rightSelection[0]);
      } else {
        ElMessage.warning('左右表格选中的数据不符合导入逻辑，无法导入！');
        return;
      }
    }

    // if(canAddChild({ nodeType: NODE_TYPE.ROOT }, leftMultipleSelection[index].nodeType)){
    //   await leftInsertToRight([leftMultipleSelection[index]], { nodeType: NODE_TYPE.PHASE, fakeId: nodeLevel2Uuid.value, uuid: nodeLevel2Uuid.value });
    // }else {
    //   ElMessage.warning(leftMultipleSelection[index].nodeName + '无法直接导入到右侧！');
    //   return;
    // }
  }
  console.log('leftInsertArr', leftInsertArr);
  if (leftInsertArr.length > 0 && rightSelection.length === 0) {
    // 右边没勾选时一次性插入数据
    await getRightVxeRef().insertAt(leftInsertArr, -1);
  }

  // setTimeout(() => {
  nextTick( async () => {
    // 展开右侧选中的节点
    await getRightVxeRef()?.setTreeExpand(rightSelection[0], true);
    // 展开左侧插入的节点
    await getRightVxeRef()?.setTreeExpand(leftInsertArr, true);
    await getRightVxeRef().clearCheckboxRow();
    await getLeftVxeRef().clearCheckboxRow();

    // rightTableRef.value.changeLevel('全部展开');
  });
  // }, 2000);
  // rightTableData.value = rightTableRef.value.loadcaseTableRef.getTableData().fullData;
  // console.log('左侧选中的数据', leftMultipleSelection);
  // console.log('导入完成后右侧的数据：', rightTableRef.value.loadcaseTableRef.getTableData());

};
const leftInsertToRight = async(leftSelectList:any[], rightData:any) => {

  for (let i = 0; i < leftSelectList.length; i++) {
    // 同层级数据导入，将选中数据的子节点数据导入右边的children中
    if (leftSelectList[i].nodeType === rightData.nodeType) {
      console.log('同层级数据导入，将选中数据的子节点数据导入右边的children中');
      const insertArr = await mergeArrays(cloneDeep(leftSelectList[i].children), cloneDeep(rightData.children), rightData.fakeId, rightData.uuid, [], rightData.tagKeyList);

      console.log('最终插入的平铺list：', insertArr);
      getRightVxeRef().insertAt(insertArr, -1);
    }
    // 非同层级导入，将选中数据作为子节点数据导入右边
    else {
      console.log('非同层级导入，将选中数据作为子节点数据导入右边');
      const insertArr = flattenTreeData([leftSelectList[i]], rightData.fakeId, rightData.uuid, rightData.tagKeyList);
      console.log('不同层级insertAtArr', insertArr);
      getRightVxeRef().insertAt(insertArr, -1);
    }
  }
};

const mergeArrays = async (leftList:any[], rightList:any[], parentId: string, uuid:string, insertArr:any[], tagKeyList:string[] = []) => {
  // 遍历leftArr中的每一项
  for (let index = 0; index < leftList.length; index++) {
    // 在rightArr中查找nodeName、nodeType相同的项
    const foundIndex = rightList.findIndex(
      rightItem => rightItem.nodeName === leftList[index].nodeName && rightItem.nodeType === leftList[index].nodeType
    );

    if (foundIndex === -1) {
      // 如果nodeName不存在，插入到rightArr中
      const leftInsertArr = flattenTreeData(cloneDeep([leftList[index]]), parentId, uuid, tagKeyList);
      console.log('整体插入list:', leftList[index].nodeName, '插入的数组:', leftInsertArr);
      insertArr.push(...leftInsertArr);
    } else {
      const newObj = { ...rightList[foundIndex] };
      const updateRow = getRightVxeRef().getRowById(rightList[foundIndex].fakeId);
      // 如果nodeName存在，更新rightArr中的其他属性（除了children）
      Object.keys(leftList[index]).forEach(key => {
        if (key !== 'children' && key !== 'nodeName' && key !== 'fakeId' && key !== 'uuid' && key !== 'pid' && key !== '_X_ROW_CHILD') {
          updateRow[key] = leftList[index][key];
        }
      });
      console.log('updateRow', updateRow);

      console.log('更新行数据', rightList[foundIndex].englishName, newObj.englishName, 'rightOld:', rightList[foundIndex], 'rightNew:', newObj);
      await getRightVxeRef().updateRow(rightList[foundIndex], newObj);

      // 如果nodeName存在，递归处理children
      if (leftList[index].children && Array.isArray(leftList[index].children)) {
        await mergeArrays(
          leftList[index].children,
          rightList[foundIndex].children || [],
          rightList[foundIndex].fakeId,
          rightList[foundIndex].uuid,
          insertArr,
          rightList[foundIndex].tagKeyList
        );
        // 确保rightItem的children是数组（防止初始值为undefined）
      }
    }
  }
  return insertArr;
};

// 将左侧选中数据中，选了父节点又选了子节点，把子节点去掉，避免重复导入到右侧
const clearLeftSelectRepeat = (list:any[]) => {
  const listClone = cloneDeep(list);
  const fakeIdMap = new Map();
  const repeatIdList:string[] = [];
  for (let index = 0; index < listClone.length; index++) {
    fakeIdMap.set(listClone[index].fakeId, index);
  }
  for (let i = 0; i < listClone.length; i++) {
    const flatArr = flatNormalTreeData(listClone[i].children);
    for (let j = 0; j < flatArr.length; j++) {
      if (fakeIdMap.has(flatArr[j].fakeId)) {
        repeatIdList.push(flatArr[j].fakeId);
      }
    }
  }
  return listClone.filter(item => !repeatIdList.includes(item.fakeId));
};

// 正常的将树形数据扁平化
function flatNormalTreeData(treeData: any[]): any[] {
  let result: any[] = [];
  // 遍历树结构数组中的每一项
  treeData.forEach(item => {
    // 为当前项添加 parentId 属性
    const flatItem = { ...item, children: [], _X_ROW_CHILD: [] };
    delete flatItem._X_ROW_CHILD;
    delete flatItem._X_ROW_KEY;
    // 将当前项添加到结果数组中
    result.push(flatItem);
    // 如果当前项有子节点（children 存在且为数组），则递归处理子节点
    if (item.children && Array.isArray(item.children)) {
      const childrenResult = flatNormalTreeData(item.children);
      // 将子节点处理后的结果合并到结果数组中
      result = result.concat(childrenResult);
    }
  });
  return result;
}
const tagKeyMap:any = ref(getTagKeyMap());
// 将树形数据扁平化，并设置parentId和fakeId
function flattenTreeData(treeData: any[], parentId = '', pUuid = '', pTagKeyList:string[] = []) {
  let result: any[] = [];
  // 遍历树结构数组中的每一项
  for (let index = 0; index < treeData.length; index++) {
    const item = treeData[index];
    // 为当前项添加 parentId 和pid属性
    const flatItem = { ...item, parentId, pid: pUuid, children: [], _X_ROW_CHILD: [], uuid: undefined, fakeId: 'fakeUuid' + uuidv4() };
    delete flatItem._X_ROW_CHILD;
    delete flatItem._X_ROW_KEY;
    if (flatItem.nodeType === NODE_TYPE.TASK) {
      if (nodeLevel2SelectRef.value?.nodeInfo) {
        if (nodeLevel2SelectRef.value?.nodeInfo?.beginTime) {
          flatItem.beginTime = nodeLevel2SelectRef.value?.nodeInfo.beginTime;
        } else if (props.projectBeginTime) {
          flatItem.beginTime = props.projectBeginTime;
        } else {
          flatItem.beginTime = dayjs().format('YYYY-MM-DD');
        }
        if (nodeLevel2SelectRef.value?.nodeInfo?.endTime) {
          flatItem.endTime = nodeLevel2SelectRef.value?.nodeInfo.endTime;
        } else if (props.projectEndTime) {
          flatItem.endTime = props.projectEndTime;
        } else {
          flatItem.endTime = dayjs().format('YYYY-MM-DD');
        }
      }
      if (!flatItem.exeStatus) {
        flatItem.exeStatus = TASK_PROCESS_STATUS.NO_STARTED;
      }
      if (! flatItem.achieveStatus) {
        flatItem.achieveStatus = TASK_CALCULATE_STATUS.NO_CALCULATE;
      }
    }
    disposeTagKey(flatItem, pTagKeyList, tagKeyMap.value);
    console.log('flatItem', flatItem, flatItem._X_ROW_CHILD, flatItem.children);
    // 将当前项添加到结果数组中

    result.push(flatItem);
    // 如果当前项有子节点（children 存在且为数组），则递归处理子节点
    if (item.children && Array.isArray(item.children)) {
      // 递归调用  处理子节点，父级 id 为当前项的 pid
      const childrenResult = flattenTreeData(item.children, flatItem.fakeId, flatItem.uuid, flatItem.tagKeyList);
      // 将子节点处理后的结果合并到结果数组中
      result = result.concat(childrenResult);
    }
  }
  return result;
}

const addOrEditTaskFun = async() => {
  loadingInterface.value = true;
  const { insertRecords, removeRecords, updateRecords }: any =
    await getRightVxeRef().getRecordset();
  console.log('getRecords ', insertRecords, removeRecords, updateRecords);
  const insertList = cloneDeep(insertRecords).map((item: any) => {
    return {
      ...item,
      beginTime: item.planTime?.length > 0 ? item.planTime[0] : '',
      endTime: item.planTime?.length > 0 ? item.planTime[1] : '',
      tenantId: getUserTenantId(),
      eMemberList: getMemberListIds(item.eMemberList),
      pMemberList: getMemberListIds(item.pMemberList),
      analyseSoftware: Array.isArray(item.analyseSoftware) ? item.analyseSoftware?.join() : item.analyseSoftware,
    };
  });
  const insertTreeList = flatArrayToTree(insertList);
  const updateList = cloneDeep(updateRecords).map((item: any) => {
    return {
      ...item,
      beginTime: item.planTime?.length > 0 ? item.planTime[0] : '',
      endTime: item.planTime?.length > 0 ? item.planTime[1] : '',
      tenantId: getUserTenantId(),
      eMemberList: getMemberListIds(item.eMemberList),
      pMemberList: getMemberListIds(item.pMemberList),
      analyseSoftware: Array.isArray(item.analyseSoftware) ? item.analyseSoftware?.join() : item.analyseSoftware,
    };
  });
  console.log('insertTreeList', insertTreeList);
  // if (props.dialogType === 'create') {
  //   // 创建时就将所有数据拼成一个数结构给到后端
  //   const nodeLevel2Tree = props.nodeLevel2List?.map(item => {
  //     if (item.uuid === nodeLevel2Uuid.value) {
  //       item.children = insertTreeList;
  //     }
  //     return item;
  //   });
  //   await updateTreeDataApi([{ ...props.nodeLevel1Info, children: nodeLevel2Tree }], [], []);
  // } else {
  await updateTreeDataApi(insertTreeList, removeRecords, updateList);
  // }
  loadingInterface.value = false;
  console.log('taskDialog completeFun', 'taskPlanPage1111');
  emits('taskComplete', 'taskPlanPage');
  console.log('taskDialog completeFun', 'taskPlanPage111122222');
  closeFun();
};
// 调接口更新任务树的数据
const updateTreeDataApi = async (insertList: any[], deleteList: any[], updateList: any[]) => {
  const deleteNodeList = getDeleteListIds(deleteList, []);
  const addList = disposeTreeTagKey(insertList);

  console.log('updateTreeDataApi', {
    addNodeList: addList,
    editNodeList: updateList,
    deleteNodeList,
    deleteList,
  });

  if (insertList.length === 0 && updateList.length === 0 && deleteNodeList.length === 0) {
    return;
  }
  try {
    const res:any = await modifyNodeTaskPerformanceApi({
      addNodeList: insertList,
      editNodeList: updateList,
      deleteNodeList,
      ownRootNodeUuid: props.nodeLevel1Uuid,
      tagMap: getTagMapList(),
    });
    if (res.code === 200) {
      ElMessage.success('数据更新成功');
    } else {
      ElMessage.error('数据更新失败');
    }
  } catch (error) {
    ElMessage.error('接口调用异常' + error);
  }
};

const getDeleteListIds = (deleteList:any[], uuids: { uuid: string; nodeType: string; }[]) => {
  for (let index = 0; index < deleteList.length; index++) {
    uuids.push({ uuid: deleteList[index].uuid, nodeType: deleteList[index].nodeType });
    if (deleteList[index]?.children?.length > 0) {
      getDeleteListIds(deleteList[index]?.children, uuids);
    }
  }
  return uuids;
};

const disposeTreeTagKey = (treeList: any[]) => {
  for (let index = 0; index < treeList.length; index++) {
    if (treeList[index].nodeType !== NODE_TYPE.PERFORMANCE) {
      const tagObj:{ [key: string]: string[] } = {};
      tagSortList.forEach((tagName: string) => {
        tagObj[tagName] = [];
        // console.log('tagKeyMap', tagKeyMap.value);
        // 给task的tag赋值项目的uuid
        if (tagName === tagKeyMap.value.get(NODE_TYPE.PROJECT)) {
          tagObj[tagName].push(props.nodeLevel1Uuid || '');
        }
        // 给task的tag赋值阶段的uuid
        if (tagName === tagKeyMap.value.get(NODE_TYPE.PHASE)) {
          tagObj[tagName].push(nodeLevel2Uuid.value || '');
        }
      });
      treeList[index].tagKeyList.forEach((item: { [x: string]: string; }) => {
        const key = Object.getOwnPropertyNames(item)[0];
        tagObj[key].push(item[key]);
      });
      treeList[index] = {
        ...treeList[index],
        ...tagObj,
      };
      if (treeList[index].children) {
        disposeTreeTagKey(treeList[index].children);
      }
    }
    // } else {
    // }
  }
  return treeList;
};

/**
 * 将一维数组转换为树形结构
 * @param {Array} flatArray - 一维数组，每项需包含id和parentId
 * @param {string|number|null} [rootParentId=null] - 根节点的parentId值，默认为null
 * @returns {Array} 树形结构数组
 */
function flatArrayToTree(flatArray:any[], rootParentId = null) {
  // 创建映射表，通过id快速查找对应项
  const itemMap:any = {};
  const treeResult: any[] = [];

  // 第一步：构建id到数据项的映射，并初始化children数组
  flatArray.forEach((item:any) => {
    // 为每个项添加children属性（如果不存在）
    itemMap[item.fakeId] = { ...item, children: [], _X_ROW_CHILD: [] };
    delete itemMap[item.fakeId]._X_ROW_CHILD;
    delete itemMap[item.fakeId]._X_ROW_KEY;
  });

  // 第二步：遍历所有项，根据parentId建立父子关系
  flatArray.forEach(item => {
    const currentItem = itemMap[item.fakeId];
    const parentId = item.parentId;

    if (parentId === rootParentId) {
      // 如果parentId是根节点标识，直接加入结果数组
      treeResult.push(currentItem);
    } else {
      // 否则找到父节点，加入其父节点的children
      const parentItem = itemMap[parentId];
      if (parentItem) {
        parentItem.children.push(currentItem);
      } else {
        // 处理找不到父节点的情况（可根据需求调整，这里默认加入根节点）
        treeResult.push(currentItem);
      }
    }
  });

  return treeResult;
}

const closeFun = () => {
  emits('update:showTaskDialog', false);
};

const prePageFun = () => {
  emits('prePageFun', 'taskPage');
};

const leftPoolTableRef = ref();
const leftPoolTableDataList = ref<any[]>([]);

const leftProjectTableDataList = ref<any>([]);

const rightTableRef = ref();

const leftTableLoading = ref(true);
const rightTableLoading = ref(true);

const loadcaseLibList = ref<any[]>([]);
const currentLoadcaseLib = ref();
const currentLoadcaseLibVersionInfo = ref();
const loadcaseLibVersionList = ref();

const changeLoadcaseLibFun = async(lib:any) => {
  currentLoadcaseLib.value = lib;
  await queryLoadcaseLibVersionsFun();
  expandTree(leftPoolTableRef.value);
};

const changeLoadcaseVersionFun = async() => {
  await queryTaskPoolFun();
  expandTree(leftPoolTableRef.value);
};

const queryPoolListFun = async () => {
  const res: any = await getAllTaskPoolApi();
  if (res.code === 200 && Array.isArray(res.data)) {
    loadcaseLibList.value = res.data.reverse();
  } else {
    loadcaseLibList.value = [];
  }
  if (loadcaseLibList.value.length > 0) {
    currentLoadcaseLib.value = loadcaseLibList.value[0];
    queryLoadcaseLibVersionsFun();
  }
};

const queryLoadcaseLibVersionsFun = async () => {
  const req = {
    poolName: currentLoadcaseLib.value.poolName,
  };
  const res:any = await getTaskPoolVersionsApi(req);
  if (res.code === 200 && res.data && Array.isArray(res.data) && res.data.length > 0) {
    loadcaseLibVersionList.value = res.data;
    if (loadcaseLibVersionList.value.length > 0) {
      currentLoadcaseLibVersionInfo.value = loadcaseLibVersionList.value[0];
    }
  } else {
    loadcaseLibVersionList.value = [];
  }
  await queryTaskPoolFun();
};

const queryTaskPoolFun = async () => {
  if (!currentLoadcaseLibVersionInfo.value) {
    return;
  }
  const req = {
    poolName: currentLoadcaseLib.value.poolName,
    version: currentLoadcaseLibVersionInfo.value.poolVersion,
  };
  const res: any = await getTaskPoolApi(req);
  let tree = [];
  if (res.code === 200 && res.data.poolBrief && res.data && res.data.nodes) {
    tree = transformPoolNodesToTree(res.data.nodes);
    leftPoolTableDataList.value = tree;
    nextTick(() => {
      // 待修改
      // leftPoolTableRef.value?.changeLevel('全部展开');
    });
  } else {
    leftPoolTableDataList.value = [];
  }
  leftTableLoading.value = false;
};

setTimeout(() => {
  // rightTableData.value = [
  //   {
  //     id: 101,
  //     fakeId: '右侧学科A',
  //     uuid: 'r-uuid-101',
  //     nodeName: '右侧学科A',
  //     englishName: 'disciplineA',
  //     nodeType: 'discipline',
  //     nodeCode: 'A1',
  //     description: '右侧学科A描述',
  //     type: 'discipline',
  //     children: [
  //       {
  //         id: 102,
  //         fakeId: '右侧节点A1',
  //         uuid: 'r-uuid-102',
  //         nodeName: '右侧节点A1',
  //         englishName: 'groupA1',
  //         nodeType: 'group',
  //         nodeCode: 'A1-1',
  //         description: '右侧节点A1描述',
  //         children: [
  //           {
  //             id: 103,
  //             fakeId: '右侧任务A1-1',
  //             uuid: 'r-uuid-103',
  //             nodeName: '右侧任务A1-1',
  //             englishName: 'taskA1-1',
  //             nodeType: 'task',
  //             nodeCode: 'A1-1-1',
  //             description: '右侧任务A1-1描述',
  //             startTime: '',
  //             endTime: '',
  //             workRate: 10,
  //             flowTemplateName: '',
  //             standard: '',
  //             userName: '',
  //             children: [
  //               {
  //                 id: 104,
  //                 fakeId: '右侧性能A1-1-1',
  //                 uuid: 'r-uuid-104',
  //                 nodeName: '右侧性能A1-1-1',
  //                 englishName: 'performanceA1-1-1',
  //                 nodeType: 'performance',
  //                 description: '右侧性能A1-1-1描述',
  //                 hightValue: '10',
  //               },
  //             ],
  //           },
  //         ],
  //       },
  //       {
  //         id: 103,
  //         fakeId: '右侧节点A2',
  //         uuid: 'r-uuid-102222',
  //         nodeName: '右侧节点A2',
  //         englishName: 'groupA1',
  //         nodeType: 'group',
  //         nodeCode: 'A1-1',
  //         description: '右侧节点A1描述',
  //       },
  //     ],
  //   },
  //   {
  //     id: 201,
  //     fakeId: '右侧学科B',
  //     uuid: 'r-uuid-201',
  //     nodeName: '右侧学科B',
  //     englishName: 'disciplineB',
  //     nodeType: 'discipline',
  //     nodeCode: 'B1',
  //     description: '右侧学科B描述',
  //     children: [],
  //   },
  // ];
  // leftTableLoading.value = false;
}, 1000);

watch(() => props.showTaskDialog,
  (newVal) => {
    if (newVal) {
      if (props.dialogType === 'create' && props.nodeLevel2List?.length ) {
        nodeLevel2Uuid.value = props.nodeLevel2List[0].uuid;
      }
    }
  }
);

onMounted(async() => {
  queryPoolListFun();
});

</script>
<style lang="scss">
.left-panel {
  .left-form-inline {
    width: 100%;
  }
  .el-form-item__content{
    width: 120px;
  }
}
.right-panel {
  .right-form-inline {
    width: 100%;
  }
  .el-form-item__content{
    width: 120px;
  }
}
</style>
<style lang="scss" scoped src="./taskDialog.scss"></style>
