<template>
  <div class="smallTitle">审批信息</div>
  <div class="ww100">
    <el-steps :active="0" space="500" finish-status="success" direction="vertical" status=''>
      <el-step :title="item.eventType == '0' ? '发起申请' : item.eventType == '1' ? '审批结束' : item.nodeName"
        v-for="(item, index) in workflow" :key="index">
        <template #description>
          <div class="ww100 mt10 mb20 nodeBox" v-if="item.eventType == '0' || item.eventType == '1'">
            <div class="nodeorgNameTg">{{ item.xtLrrbm }}</div>
            <div class="flex just-between nameTag">
              <div>{{ item.xtLrrxm}}</div>
              <div class="fontColor">{{ item.eventType == '0' ? '发起' : '结束' }}</div>
            </div>
            <div>{{ item.xtLrsj }}</div>
          </div>
          <div v-else class="ww100 mt10 mb20 nodeBox">
            <div :class="item.taskStatus == '2' ? 'nodeorgNameTg' : 'nodeorgNameDd'">{{ item.nodeName }}</div>
            <!-- <div v-for="(items, indexs) in item.log" :key="indexs"> -->
              <div class="flex just-between nameTag">
                <div>{{ item.logNode.userName }}</div>
                <div :class="item.taskStatus == '2' ? 'fontColor' : 'fontColorDd'">
                  {{ item.taskStatus == '2' ? '已审批' : '审批中' }}
                </div>
              </div>
              <div>{{ item.logNode.xtZhxgsj }}</div>
            <!-- </div> -->
          </div>
        </template>
      </el-step>

    </el-steps>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { queryProcessNode, queryProcessNodeLog, queryProcess } from '@/api/spl'
const workflow = ref()
const getWorkflow = async (id) => {
  const promes = {
    processId: id
  }
  const process = await queryProcess(promes)
  const proNode = await queryProcessNode(promes)
  const proNodeLog = await queryProcessNodeLog(promes)
  let newProNode = proNode.rows.filter(item => item.eventType == '0')
  const decisionPNodeId = proNode.rows.map(item => {
    const log = proNodeLog.rows.find(items => items.nodeId == item.nodeId)
    return {
      ...item,
      logNode: log ? log : ""
    }
  })
  workflow.value = sortNodesByFlow(decisionPNodeId)
console.log(workflow.value);

}


function sortNodesByFlow(nodes) {
  // 找到首节点（eventType为0的节点）
  const startNode = nodes.find(node => node.eventType === "0");
  if (!startNode) {
    console.error("未找到首节点");
    return nodes;
  }

  // 创建排序后的节点数组
  const sortedNodes = [startNode];

  // 使用Map提高查找效率
  const nodeMap = new Map();
  nodes.forEach(node => {
    if (node.pNodeId) {
      nodeMap.set(node.pNodeId, node);
    }
  });

  // 当前节点指针
  let currentNode = startNode;

  // 循环查找下一个节点
  while (true) {
    // 查找下一个节点（prevPNodeId等于当前节点的pNodeId）
    const nextNode = nodes.find(node => node.prevPNodeId === currentNode.pNodeId);

    if (!nextNode) {
      break; // 没有下一个节点，结束循环
    }

    sortedNodes.push(nextNode);
    currentNode = nextNode;
  }

  return sortedNodes;
}
function sortNodesWithNoPreviousFirst(nodes) {
  if (!Array.isArray(nodes)) {
    console.error('参数必须是一个数组');
    return [];
  }
  if (nodes.length === 0) {
    return [];
  }

  // 1. 创建节点ID到节点的映射表，用于快速查找
  const nodeMap = nodes.reduce((map, node) => {
    if (node && node.nodeId) {
      map[node.nodeId] = node;
    }
    console.log(node, "xxxxxx");

    return map;
  }, {});
  console.log(nodeMap);
  // 2. 分离节点：没有前驱的节点和有前驱的节点
  const result = nodes.reduce((acc, node) => {
    // 检查是否为有效节点
    if (!node || !node.nodeId) {
      console.warn('发现无效节点，将被忽略:', node);
      return acc;
    }
    // 判断是否没有前驱节点
    const hasNoPrevious = !node.prevPNodeId && !nodeMap[node.prevPNodeId];

    if (hasNoPrevious) {
      acc.noPrevious.push(node);
    } else {
      acc.hasPrevious.push(node);
    }

    return acc;
  }, { noPrevious: [], hasPrevious: [] });

  // 3. 合并结果：没有前驱的节点在前，有前驱的节点在后
  console.log(result.noPrevious);
  console.log(result.hasPrevious);
  return [...result.noPrevious, ...result.hasPrevious];
}






defineExpose({
  getWorkflow
})

</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";

.smallTitle {
  width: 100%;
  font-size: 15px;
  line-height: 50px;
  font-weight: 550;
  color: #606266;
}

.mapSearch {
  left: 10px;
  top: 10px;
  z-index: 100;
}

.dialog {
  ::v-deep .el-form-item--default {
    margin: 0 1% 0 0 !important;
    padding-bottom: 0 !important;
  }
}

::v-deep .avatar-uploader {
  display: flex;
}

::v-deep .el-upload--picture-card i {
  width: 156px;
}

.depBox {
  border: 1px solid #e9e9e9;
  width: 305px;
  padding: 0 0 0 4px;
  border-radius: 4px;

  ::v-deep .el-input__inner {
    border: none;
  }

  ::v-deep .el-cascader .el-input.is-focus .el-input__inner {
    border-color: transparent !important;
  }

  ::v-deep .el-input__inner:focus {
    box-shadow: none;
  }

  ::v-deep .el-input.is-disabled .el-input__inner {
    border-color: transparent !important;
  }

}

/* 使用深度选择器覆盖子组件样式 */
::v-deep .el-step.is-vertical .el-step__title {
  color: #000000 !important;
  border-color: #000000 !important;
}

::v-deep .el-step__description {
  padding: 0 !important;
}

::v-deep .el-step__description.is-wait {

  color: #000000 !important;
  border-color: #000000 !important;
}

.el-step__title.is-wait {
  color: #000000 !important;
  border-color: #000000 !important;
}

::v-deep .el-step__head.is-wait {
  color: #000000 !important;
  border-color: #000000 !important;
}

::v-deep .el-step__line {
  background-color: #000000 !important;
}

.nodeBox {
  width: 80%;
  text-align: center;
  line-height: 30px;
  border-radius: 10px;
  overflow: hidden;
  background-color: aliceblue;

  .nodeorgNameTg {
    background-color: #1abe20;
  }

  .nameTag {
    line-height: 30px;
    padding: 0 10px;
  }

  .nodeorgNameDd {
    background-color: #18a2dd;
  }

  .fontColor {
    color: #1abe20;
  }

  .fontColorDd {
    color: #18a2dd;
  }
}
</style>
