import { BaseEdgeModel, BaseNodeModel } from '@logicflow/core';
/**
 * 节点样式处理方法
 * @param _this
 * @param {*} style
 * @returns
 */
export const nodeStyleHandle = (_this: BaseNodeModel, style: {
  [x: string]: any;
  r?: number;
  fill?: string;
  stroke?: string;
  strokeWidth?: number;
}): {
  [x: string]: any;
  r?: number;
  fill?: string;
  stroke?: string;
  strokeWidth?: number;
} => {
  if (_this.properties.state === 'active') {
    style.stroke = '#00ff00'
  } else if (_this.properties.state === 'history') {
    style.stroke = '#ff0000'
  }
  return style
}
/**
 * 边样式处理方法
 * @param _this
 * @param {*} style
 * @returns
 */
export const edgeStyleHandle = (_this: BaseEdgeModel, style: {
  [x: string]: any;
  r?: number;
  fill?: string;
  stroke?: string;
  strokeWidth?: number;
}): {
  [x: string]: any;
  r?: number;
  fill?: string;
  stroke?: string;
  strokeWidth?: number;
} => {
  if (_this.properties.state === 'active') {
    style.stroke = '#00ff00'
  } else if (_this.properties.state === 'history') {
    style.stroke = '#ff0000'
  }
  return style
}
// 节点类型
const nodeType:any = {
  'task': 0,
  'start': 1,
  'end': 2,
  'summary': 3,
}
/**
 * 将获取到的数据转换成logic flow需要的数据
 * @param {*} data(...processInfo,nodes,edges)
 * @returns
 */
export const resDataToLogicFlow = (data: any): any => {
  return JSON.parse(data.externalData)
}

/**
 * 将LogicFlow的数据转成提交的格式
 * @param {*} data(...processInfo,nodes,edges)
 * @returns
 */
export const logicFlowJsonToSubmit = (data: any): object => {
  let returnData = {}
  // data的数据由流程定义文件信息+logicFlow数据构成
  // 先构建成流程对象
  const processObj = <any>{
    name: data.name, // 流程定义名称
    code: data.code, // 流程定义code
    moduleName: data.moduleName, // 业务模块
    moduleCode: data.moduleCode, // 业务模块
    id: data.id, // 流程id
    steps: [] // 所有步骤
  }

  // /**
  //  * 获取开始节点
  //  * @returns
  //  */
  const getStartNode = () => {
    return data.nodes.find((node: any) => {
      // 是开始节点，且非子流程中的开始节点
      return node.type === 'hotline:start'
    })
  }
  // 获取结束节点
  const getEndNode = () => {
    return data.nodes.find((node: any) => {
      return node.type === 'hotline:end'
    })
  }

  // /**
  // * 获取当前节点的所有下一个节点集合 非回退
  // * @param {*} id 当前节点名称
  // * @returns
  // */
  // const getNextNodes = (id: string) => {
  //   return data.edges.filter((edge: any) => {
  //     return edge.sourceNodeId === id && !edge.properties.isPrevious
  //   }).map((edge: any) => {
  //     return data.nodes.find((node: any) => {
  //       return node.id === edge.targetNodeId
  //     })
  //   })
  // }
  // /**
  //  * 获节点的下一步
  //  * @param {*} id
  //  * @returns
  //  */
  // const getNextStep = (id: string) => {
  //   return data.edges.filter((edge: any) => {
  //     return edge.sourceNodeId === id
  //   }).map((edge: any) => {
  //     return {
  //       isPrevious: edge.properties.isPrevious ?? false,
  //       code: edge.targetNodeId
  //     }
  //   })
  // }
  // /**
  //  * 构建节点属性
  //  * @param {}} node
  //  * @returns
  //  */
  const buildNode = (node: any) => {
    const nodeName = node.type.replace('hotline:', '')
    return {
      stepType: nodeType[nodeName],
      name: (node.text instanceof String || node.text === undefined) ? node.text : node.text.value,
      ...node.properties,
      handlerClassifies: formatArrayHandlerClassifies(node),
      components: formatArrayComponent(node),
      code: node.id,
      nextSteps: node.nextSteps
    }
  }
  /**
   * 处理数组类型
   * @param {} node
   */
  const formatArrayHandlerClassifies = (node: any) => {
    const nodeName = node.type.replace('hotline:', '')
    let data: string[] = []
    if (nodeName === 'task' || nodeName === 'summary') {
      if (node.properties.handlerClassifies && Object.prototype.toString.call(node.properties.handlerClassifies) === '[object String]') {
        data = JSON.parse(node.properties.handlerClassifies)
      }
    }
    return data;
  }
  /**
   * 处理数组类型
   * @param {} node
   */
  const formatArrayComponent = (node: any) => {
    const nodeName = node.type.replace('hotline:', '')
    let data: string[] = []
    if (nodeName === 'task' || nodeName === 'summary') {
      if (node.properties.components && Object.prototype.toString.call(node.properties.components) === '[object String]') {
        data = JSON.parse(node.properties.components)
      }
    }
    return data;
  }
  // /**
  //  * 递归构建节点属性
  //  * @param {} node
  //  */
  // const recursionBuildNode = (node: any) => {
  //   const nodeName = node.type.replace('hotline:', '')
  //   if (!processObj[nodeName + '_' + node.id]) {
  //     processObj.steps.push(buildNode(node))

  //     const nextNodes = getNextNodes(node.id)

  //     nextNodes.forEach((nextNode: any) => {
  //       recursionBuildNode(nextNode)
  //     })
  //   }
  // }
  const startNode = getStartNode();
  const endNode = getEndNode();
  if (!startNode) {
    // 开始节点不存在
    return { error: '开始节点不存在' }
  }
    if (!endNode) {
    // 结束节点不存在
    return { error: '结束节点不存在' }
  }
  // recursionBuildNode(startNode);
  for (let node of data.nodes) {
    node.nextSteps = [];
    const edges = data.edges.filter((v: any) => v.sourceNodeId === node.id);// 找到当前节点的边
    for (let edge of edges) {
      if (edge.sourceNodeId === node.id) {
        node.nextSteps.push({
          code: edge.targetNodeId
        })
      }
    }
    processObj.steps.push(buildNode(node))
  }
  for (let i of processObj.steps) {
    if (i.stepType == 0 || i.stepType == 3) { //普通节点字段非空校验
      if (!i.handlerType && String(i.handlerType) !== '0') {
        return { error: `请选择${i.name}的处理人` };
      }
      if (!i.countersignMode && String(i.countersignMode) !== '0') {
        return { error: `请选择${i.name}的会签` };
      }
    }
  }
  returnData = {
    ...processObj
  }

  return returnData;
}