import End from './end'
import Start from './start'
import Task from './task'
import summary from './summary'
import Transition from './transition'
import returnTransition from './returnTransition'
import { logicFlowJsonToSbmit,resDataToLogicflow } from './tool'

/**
 * snakerflow组件注册
 */
class SnakerFlowElement {
  static pluginName = 'snakerFlowElement';
  constructor (data:any) {
    data.lf.register(End)
    data.lf.register(Start)
    data.lf.register(Task)
    data.lf.register(summary)
    data.lf.register(Transition)
    data.lf.register(returnTransition)
  }
}
/**
 * snakerflow给你LogicFlow数据转换器
 */
class SnakerFlowAdapter {
  static pluginName = 'snakerFlowAdapter';
  constructor ({ lf } : { lf: any }) {
    lf.adapterIn = (userData: any) => {
      if (typeof userData.externalData === 'string') {//格式转换
        userData = resDataToLogicflow(userData)
      }
      userData = userData.json ? userData.json : userData;
      // 将流程扩展属性绑定给lf图模型对象
      lf.graphModel.name = userData.name
      lf.graphModel.code = userData.code
      lf.graphModel.moduleName = userData.moduleName
      lf.graphModel.moduleCode = userData.moduleCode
      lf.graphModel.id = userData.id
      return userData
    }
    lf.adapterOut = (logicFlowData: any) => {
      const graphData = {
        name: lf.graphModel.name,
        code: lf.graphModel.code,
        moduleName: lf.graphModel.moduleName,
        moduleCode: lf.graphModel.moduleCode,
        id: lf.graphModel.id,
        ...logicFlowData
      }
      Object.keys(graphData).forEach((key: string) => {
        // 删除undefined的值
        if (graphData[key] === undefined) {
          delete graphData[key]
        }
      })
      
      const submitData:any = logicFlowJsonToSbmit(graphData);
      return {
        json: graphData,
        submitData:{
          ...submitData,
          externalData:JSON.stringify(graphData)
        }
      }
    }
  }
}
export {
  SnakerFlowElement,
  SnakerFlowAdapter
}
