import End from './end'
import Start from './start'
import Task from './task'
import Transition from './transition'
import {logicFlowJsonToSubmit, 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(Transition)
  }
}
/**
 * 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.flowType = userData.flowType
      lf.graphModel.description = userData.description
      lf.graphModel.isMainHandlerShow = userData.isMainHandlerShow
      lf.graphModel.id = userData.id
      return userData
    }
    lf.adapterOut = (logicFlowData: any) => {
      const graphData = {
        name: lf.graphModel.name,
        code: lf.graphModel.code,
        flowType: lf.graphModel.flowType,
        description:lf.graphModel.description,
        isMainHandlerShow:lf.graphModel.isMainHandlerShow,
        id: lf.graphModel.id,
        ...logicFlowData
      }
      Object.keys(graphData).forEach((key: string) => {
        // 删除undefined的值
        if (graphData[key] === undefined) {
          delete graphData[key]
        }
      })
      const submitData:any = logicFlowJsonToSubmit(graphData);
      return {
        json: graphData,
        submitData:{
          ...submitData,
          externalData:JSON.stringify(graphData)
        }
      }
    }
  }
}
export {
  SnakerFlowElement,
  SnakerFlowAdapter
}
