import { GAP_X, GAP_Y, START_Y, MIDDMLE_X } from "../config"

//创建节点
function createNode(raw, level = 0, index = 0, max = 0, _middle = -1) {
  let x = 0;
  const _index = index + 1;
  const y = START_Y + Number(level) * GAP_Y
  const middle = _middle >= 0 ? _middle + 1 : Math.ceil(max / 2);

  if (_index === middle || max === 0) x = MIDDMLE_X;
  if (_index > middle && max !== 0) x = MIDDMLE_X + (_index * GAP_X)
  if (_index < middle && max !== 0) x = MIDDMLE_X - (_index * GAP_X)


  return ({
    id: raw.order_process,
    text: raw.status_name,
    type: 'NormalTask',
    x,
    y,
  })
}

//创建开始节点
function createStartNode(source) {
  const raw = source.find(({ action_type }) => action_type == '1');
  const start = createNode(raw);

  return {
    start,
    startRaw: raw
  }
}

//创建连线
function createEdge(sourceNodeId, targetNodeId) {
  return {
    sourceNodeId,
    targetNodeId,
    isHitable: false,
    type: "dashe-edge"
  }
}

//去掉相同的审批记录
function uniqueRecordData(source) {
  const data = [];
  source.forEach((item) => {
    const { order_process: order_process_current } = item;
    const itemIndex = data.findIndex(({order_process}) => order_process === order_process_current);
    if(itemIndex >= 0) data.splice(itemIndex)
    data.push(item)
  })
  return data;
};

//根据开始节点递归寻找生成其他节点和连线
function createNodes(source, startNode) {
  const nodesRaw = [];
  const edgesRaw = [];

  function convert(raw, parent = "0", level = 0) {
    level++;
    const { next_actions } = raw;
    const next = source.filter(({ status_name }) => next_actions.includes(status_name));
    for (let i = 0; i < next.length; i++) {
      const index = i;
      const current = next[i]
      const maxLength = next.length;
      //根据主流程找到中间的节点
      const _middle = next.findIndex(({ is_master }) => is_master === '1');
      const edge = createEdge(parent, current.order_process);
      const node = createNode(current, level, index, maxLength, _middle);
      const prevSameNodeIndex = nodesRaw.findIndex(({ text }) => text === node.text);
      if (prevSameNodeIndex >= 0) nodesRaw.splice(prevSameNodeIndex, 1);
      
      nodesRaw.push(node);
      edgesRaw.push(edge);
      
      if (current.next_actions.length > 0) convert(current, current.order_process, level);
    }
  }

  convert(startNode, startNode.order_process);

  return ({ nodesRaw, edgesRaw })
}

//根据审批记录改变连线和节点类型
function createNodesWithRecord(nodesRaw, edgesRaw, record) {
  for (let i = 0; i < record.length; i++) {
    const current = record[i];
    const next = record[i + 1];
    const isLast = i === record.length - 1;
    const sourceNodeIndex = nodesRaw.findIndex(({ id }) => String(id) === String(current.order_process));

    if (sourceNodeIndex >= 0) {
      nodesRaw[sourceNodeIndex].type = isLast ? 'ProcessTask' : 'StartTask';
      nodesRaw[sourceNodeIndex].properties = {
        name: current.action_name,
        time: current.addtime
      }
    }

    const sourceEdgeIndex = edgesRaw.findIndex(({ sourceNodeId, targetNodeId }) => {
      return String(sourceNodeId) === String(current?.order_process) && String(targetNodeId) === String(next?.order_process);
    })

    if (edgesRaw.length === 1 && record.length === 3) {
      edgesRaw[0].type = 'polyline'
    }

    if (sourceEdgeIndex >= 0) edgesRaw[sourceEdgeIndex].type = 'polyline';
  }

  return {
    edges: edgesRaw,
    nodes: nodesRaw
  };
}



function generateTargetStartNode(soruceStartNode){
  const startNode = {
    action_type :  "1",
    addtime : "",
    creater:  "",
    id:  "-1",
    is_master : "1",
    next_action_ids: "",
    next_actions :  [soruceStartNode.status_name],
    operation_type : "2",
    order_process :  "-1",
    remark : "",
    status : "-1",
    status_name :  "创建",
  }

  return startNode
}


export function createProcessData(_source, record) {
  console.log(record)
  record = uniqueRecordData(record)
  const processChart = { nodes: [], edges: [] }
  const sourceStartIndex = _source.findIndex(({ action_type }) => action_type == '1')
  const source = [generateTargetStartNode(_source[sourceStartIndex]),..._source]
  const { start, startRaw } = createStartNode(source);
  const { nodesRaw: _nodesRaw, edgesRaw } = createNodes(source, startRaw);
  const nodesRaw = [start, ..._nodesRaw];
  const { nodes, edges } = createNodesWithRecord(nodesRaw, edgesRaw, record)
  processChart.nodes.push(...nodes);
  processChart.edges.push(...edges);
  return processChart
}
