import { BpmnNodeKey } from '/@/enums/workflowEnum';
import {
  RootElement,
  RootElements,
  ValidateProcessConfigs,
} from '/@/model/workflow/workflowConfig';
import { useI18n } from '/@/hooks/web/useI18n';
const { t } = useI18n();
// 校验xml节点连接线
export function validateRootElements(rootElements: RootElements): ValidateProcessConfigs {
  const validateProcess: ValidateProcessConfigs = flowElementsNodes(rootElements);
  return validateProcess;
}
function flowElementsNodes(flowElements: RootElements): ValidateProcessConfigs {
  const validateProcess: ValidateProcessConfigs = [];
  flowElements.forEach((element) => {
    if (element.$type == BpmnNodeKey.START) validateProcess.push(...startNode(element));
    else if (element.$type == BpmnNodeKey.SUB_PROCESS) {
      validateProcess.push(...subProcessNode(element));
    } else if (element.$type == BpmnNodeKey.SEQUENCEFLOW) {
      //流转线 不用校验 【sourceRef  targetRef 肯定是有的】
    } else if (element.$type == BpmnNodeKey.END) validateProcess.push(...endNode(element));
    else {
      validateProcess.push(...basicNode(element));
    }
  });
  return validateProcess;
}
function startNode(element: RootElement): ValidateProcessConfigs {
  return basicOutgoingNode(element);
}
function endNode(element: RootElement): ValidateProcessConfigs {
  return basicIncomingNode(element);
}

function subProcessNode(element: RootElement): ValidateProcessConfigs {
  const validateProcess: ValidateProcessConfigs = [
    ...basicIncomingNode(element),
    ...basicOutgoingNode(element),
  ];
  if (element.flowElements) validateProcess.push(...flowElementsNodes(element.flowElements));
  return validateProcess;
}
function basicNode(element: RootElement): ValidateProcessConfigs {
  return [...basicIncomingNode(element), ...basicOutgoingNode(element)];
}
function basicIncomingNode(element: RootElement): ValidateProcessConfigs {
  const validateProcess: ValidateProcessConfigs = [];
  if (
    !element.incoming ||
    (element.incoming && !Array.isArray(element.incoming)) ||
    (element.incoming && Array.isArray(element.incoming) && element.incoming.length == 0)
  ) {
    const name = element.name ? element.name : element.id;
    validateProcess.push({
      nodeName: t('流程图'),
      nodeType: BpmnNodeKey.PROCESS,
      msg: t('流程中') + name + t('节点未画入线，将无法触发，请确认后再保存'),
      validate: false,
    });
  }
  return validateProcess;
}
function basicOutgoingNode(element: RootElement): ValidateProcessConfigs {
  const validateProcess: ValidateProcessConfigs = [];
  if (
    !element.outgoing ||
    (element.outgoing && !Array.isArray(element.outgoing)) ||
    (element.outgoing && Array.isArray(element.outgoing) && element.outgoing.length == 0)
  ) {
    const name = element.name ? element.name : element.id;
    validateProcess.push({
      nodeName: t('流程图'),
      nodeType: BpmnNodeKey.PROCESS,
      msg: t('流程中') + name + t('节点未画出线，将无法触发，请确认后再保存'),
      validate: false,
    });
  }
  return validateProcess;
}
