import { UserTaskModel, UserTaskView } from './kanhouchunode/usertasknode.js'
import { SystemTaskModel, SystemTaskView } from './kanhouchunode/systemtasknode.js'
import { StartNodeModel, StartNodeView } from './kanhouchunode/startnode.js'
import { EndNodeModel, EndNodeView } from './kanhouchunode/endnode.js'
import { tiaojianNodeView, taiojianNodeModel } from './kanhouchunode/taiojiannode.js'
import { StartBingfaView, StartBingfaModel } from './kanhouchunode/startbingfanode.js'
import { EndBingfaView, EndBingfaModel } from './kanhouchunode/overbingfanode.js'
import { Panel } from './panel/panel.js'
import { ControlPanel } from './panel/control.js'
import { KhcMenu } from './menu/menu.js'
import {config} from "../kanhouchu/config.js";
import {util} from "../kanhouchu/util/util.js";
import {khcAlert} from "../kanhouchu/component/alert/khcAlert.js";
import {fullMap} from "../kanhouchu/fullMap.js";
import {httpUtil} from "../kanhouchu/util/httpUtil.js";
import {khcToastr} from "../kanhouchu/component/alert/khcToastr.js";
import {khcMask} from "../kanhouchu/component/alert/khcMask.js";
axios.defaults.baseURL = config.getConfigJson().baseURL;
config.getConfigJson().downFileUrl=config.getConfigJson().baseURL+config.getConfigJson().contextPath+'/api/file/downFile'//这个没走axios，所以补上/api
//全局响应拦截器
axios.interceptors.response.use( (response)=> {
  if (response.data.status == '4010') {//4010,登录状态失效，跳转登录页面重新登录 //todo login
    util.toLogin();
    return response;
  }else if (response.data.status != 'ok') {//非ok状态则根据响应的中文错误信息弹出
    let alertData={title:response.data.message,text:'错误码：' + response.data.status}
    khcAlert.showSystemError(alertData);
    return response;
  }else{
    return response;
  }
},  (error)=> {
  return Promise.reject(error);//错误信息不处理，交给全局异常处理
});
//监听js运行时错误事件
window.addEventListener('error', (error) => {
  //当资源（如img或script）加载失败，加载资源的元素会触发一个Event接口的error事件，并执行该元素上的onerror()处理函数。
  //这些error事件不会向上冒泡到window，但可以在捕获阶段被捕获因此如果要全局监听资源加载错误，需要在捕获阶段捕获事件
  khcAlert.showSystemError(error.message);
});
window.addEventListener('unhandledrejection', (error) => {
  fullMap.getObj('mask').hide();
  if (error.reason.code == "ERR_BAD_RESPONSE") {//后端接口不通异常
    let alertData={title:'服务器正在升级更新',text:'请稍后再访问'}
    khcAlert.showSystemError(alertData);//出现此异常，说明和后端通信异常，检查后端是否正常运行，和IP和端口是否正确
  } else {
    //其他异常，这个能复现的有当前页面还没渲染完就点击下一个菜单导致捕抓到此异常
    let alertData={title:'操作频繁',text:'请稍后再访问'}
    khcAlert.showSystemError(alertData);
  }
});
let mask = new khcMask();
fullMap.push('mask',mask);
/*const data = {
  // 节点
  nodes: [
    {
      id: 50,
      type: 'userTask',
      x: 200,
      y: 150,
      text: '起草',
    },
    {
      id: 21,
      type: 'userTask',
      text: '审批',
      x: 400,
      y: 150,
    },
  ],
  // 边
  edges: [
    {
      type: 'polyline',
      sourceNodeId: 50,
      targetNodeId: 21,
    },
  ],
};*/
//const data={"nodes":[{"x":320.0,"y":212.0,"id":"sid-A24D7AD5-EBE5-45BF-A4A4-FFC8C94835CA","text":"起草","type":"userTask"},{"x":320.0,"y":365.0,"id":"sid-25D0B40D-780C-40DE-B7A2-E0D38292B75B","text":"审批","type":"userTask"},{"x":285.0,"y":75.0,"id":"sid-360032F7-D475-4CF2-A5CC-9B9F286BCA18","text":"开始","type":"startNode"},{"x":284.0,"y":463.0,"id":"sid-8E23F54C-F88B-40AC-9749-D7A9714B509F","text":"结束","type":"endNode"}],"edges":[{"sourceNodeId":"sid-A24D7AD5-EBE5-45BF-A4A4-FFC8C94835CA","type":"polyline","targetNodeId":"sid-25D0B40D-780C-40DE-B7A2-E0D38292B75B"},{"sourceNodeId":"sid-360032F7-D475-4CF2-A5CC-9B9F286BCA18","type":"polyline","targetNodeId":"sid-A24D7AD5-EBE5-45BF-A4A4-FFC8C94835CA"},{"sourceNodeId":"sid-25D0B40D-780C-40DE-B7A2-E0D38292B75B","type":"polyline","targetNodeId":"sid-8E23F54C-F88B-40AC-9749-D7A9714B509F"}]}
let modelId=util.getUrlParam('modelId');
if(util.isNull(modelId)){
  khcToastr.showErrorMessage('请在URL参数里指定：modelId')
}else{
  //let params={version: '1.0.0', dsCode: 'ds_bpm_model',methodName:'getKhcEditorJson',"modelId":modelId};
  let params={version: '1.0.0', dsCode: 'ds_bpm_model',methodName:'getKhcEditorJson2',"modelId":modelId};
  let obj={url:config.getConfigJson().myActionUrl,params:params}
  httpUtil.post(obj, (response)=>{
    //const data=response.data.data.data
    const data=response.data.data
    //const data={"nodes":[{"x":320.0,"y":212.0,"id":"sid-A24D7AD5-EBE5-45BF-A4A4-FFC8C94835CA","text":"起草","type":"userTask"},{"x":320.0,"y":365.0,"id":"sid-25D0B40D-780C-40DE-B7A2-E0D38292B75B","text":"审批","type":"userTask"},{"x":285.0,"y":75.0,"id":"sid-360032F7-D475-4CF2-A5CC-9B9F286BCA18","text":"开始","type":"startNode"},{"x":289.9999947018098,"y":474.999990781149,"id":"sid-A4726DB8-F026-4033-8301-D088EA2F1AD9","text":"账号开通start","type":"startbingfa"},{"x":219.9999974568687,"y":599.1110887904247,"id":"sid-CFC82F68-0054-4E31-A075-06E738D35C78","text":"内容发布组件","type":"userTask"},{"x":429.99999300638893,"y":599.1110777890275,"id":"sid-DFC9D638-3C69-4F86-BF2D-4D63857216FC","text":"领导信箱组件","type":"userTask"},{"x":289.9999947018098,"y":684.9999863306692,"id":"sid-93EF9587-C808-4521-A043-1E762CCDF7B3","text":"账号开通end","type":"endbingfa"},{"x":319.9999900394025,"y":829.999968210859,"id":"sid-3F21CC4C-3EAB-4853-9ADD-DD5F517D42E7","text":"起草人确认","type":"userTask"},{"x":283.9999945746532,"y":927.9999809265153,"id":"sid-70236341-2293-4872-B5CB-D1848B909C11","text":"结束","type":"endNode"}],"edges":[{"sourceNodeId":"sid-A24D7AD5-EBE5-45BF-A4A4-FFC8C94835CA","type":"polyline","targetNodeId":"sid-25D0B40D-780C-40DE-B7A2-E0D38292B75B"},{"sourceNodeId":"sid-360032F7-D475-4CF2-A5CC-9B9F286BCA18","type":"polyline","targetNodeId":"sid-A24D7AD5-EBE5-45BF-A4A4-FFC8C94835CA"},{"sourceNodeId":"sid-25D0B40D-780C-40DE-B7A2-E0D38292B75B","type":"polyline","targetNodeId":"sid-A4726DB8-F026-4033-8301-D088EA2F1AD9"},{"sourceNodeId":"sid-A4726DB8-F026-4033-8301-D088EA2F1AD9","type":"polyline","targetNodeId":"sid-CFC82F68-0054-4E31-A075-06E738D35C78"},{"sourceNodeId":"sid-A4726DB8-F026-4033-8301-D088EA2F1AD9","type":"polyline","targetNodeId":"sid-DFC9D638-3C69-4F86-BF2D-4D63857216FC"},{"sourceNodeId":"sid-CFC82F68-0054-4E31-A075-06E738D35C78","type":"polyline","targetNodeId":"sid-93EF9587-C808-4521-A043-1E762CCDF7B3"},{"sourceNodeId":"sid-DFC9D638-3C69-4F86-BF2D-4D63857216FC","type":"polyline","targetNodeId":"sid-93EF9587-C808-4521-A043-1E762CCDF7B3"},{"sourceNodeId":"sid-93EF9587-C808-4521-A043-1E762CCDF7B3","type":"polyline","targetNodeId":"sid-3F21CC4C-3EAB-4853-9ADD-DD5F517D42E7"},{"sourceNodeId":"sid-3F21CC4C-3EAB-4853-9ADD-DD5F517D42E7","type":"polyline","targetNodeId":"sid-70236341-2293-4872-B5CB-D1848B909C11"}]}
    //fullMap.push('bpmFormCode',data.form_code);
    fullMap.push('bpmFlowData',data.data);
    let logicFlowData=bpmStrDataToLogicFlowData(data.data);
    fullMap.push('bpmFormCode',data.form_code);
    lf.render(logicFlowData);
  })
}
//该方法暂时先放这
function bpmStrDataToLogicFlowData(strData){
  let data=JSON.parse(strData);
  console.log('data before：')
  console.log(data)
  let childShapes=data.model.childShapes;
  if(util.isNull(childShapes)){
    childShapes=[]
  }
  let nodeArray=[];
  let edgesArray=[];
  let outgoingMap= new Map();
  let bpmTypeMap=new Map();
  bpmTypeMap.set("UserTask","userTask");
  bpmTypeMap.set("StartNoneEvent","startNode");
  bpmTypeMap.set("EndNoneEvent","endNode");
  bpmTypeMap.set("EndTerminateEvent","endNode");
  bpmTypeMap.set("start_baorong","startbingfa");
  bpmTypeMap.set("end_baorong","endbingfa");
  fullMap.push('bpmTypeMap',bpmTypeMap);
  for (let i = 0; i < childShapes.length; i++) {
    let childShapeJson=childShapes[i];
    let type=childShapeJson['stencil']['id'];
    let propertiesJson=childShapeJson['properties'];
    let x=childShapeJson['bounds']['lowerRight']['x'];
    let y=childShapeJson['bounds']['lowerRight']['y'];
    let documentation;
    if(util.isNull(propertiesJson['documentation'])){
      documentation={}
    }else{
      documentation=JSON.parse(propertiesJson['documentation']);
    }
    if(!util.isNull(documentation['x'])){
      x=documentation['x'];
    }
    if(!util.isNull(documentation['y'])){
      y=documentation['y'];
    }
    if(!util.isNull(bpmTypeMap.get(type))){
      let outgoingArray=childShapeJson['outgoing']
      for (let j = 0; j < outgoingArray.length; j++) {
        outgoingMap.set(outgoingArray[j]['resourceId'],childShapeJson['resourceId'])
      }
      let nodeJson={
        id:childShapeJson['resourceId'],
        type:bpmTypeMap.get(type),
        text:propertiesJson['name'],
        x:x,
        y:y
      }
      nodeArray.push(nodeJson);
      fullMap.push(childShapeJson['resourceId'],childShapeJson)
    }
    if(type=='SequenceFlow'){
      let nodeJson={
        id:childShapeJson['resourceId'],
        sourceNodeId:outgoingMap.get(childShapeJson['resourceId']),
        type:'polyline',
        targetNodeId:childShapeJson['target']['resourceId']
      }
      edgesArray.push(nodeJson);
      fullMap.push(childShapeJson['resourceId'],childShapeJson)
    }
    if(type=='InclusiveGateway'){
      let outgoingArray=childShapeJson['outgoing']
      for (let j = 0; j < outgoingArray.length; j++) {
        outgoingMap.set(outgoingArray[j]['resourceId'],childShapeJson['resourceId'])
      }
      let nodeJson={
        id:childShapeJson['resourceId'],
        type:bpmTypeMap.get(documentation['type']),//并发是从documentation获取，取出的值用于区分是开始还是结束。
        text:propertiesJson['name'],
        x:x,
        y:y
      }
      nodeArray.push(nodeJson);
      fullMap.push(childShapeJson['resourceId'],childShapeJson)
    }
  }
  let retData={}
  retData['nodes']=nodeArray;
  retData['edges']=edgesArray;
  console.log('data after：')
  console.log(retData)
  return retData;
}
LogicFlow.use(SelectionSelect);//开启多选，配合拖拽面板的选区按钮
LogicFlow.use(Snapshot);//下载图片
LogicFlow.use(Menu);//右键菜单
let lfwidth=document.getElementById("container").clientWidth
const lf = new LogicFlow({
  container: document.querySelector('#container'),
  stopScrollGraph: true,
  stopZoomGraph: true,
  width: lfwidth,
  height: 800,
  style: {
    nodeText: { // 节点文本样式
      fontSize: 16,
      color: '#000000'
    },
    edgeText: { // 边文本样式
      fontSize: 16,
      color: '#000000'
    },
  },
  grid: {
    type: 'dot',
    size: 20,
  },
  keyboard: {
    enabled: true,
    shortcuts: [
      {
        keys: ["delete"],
        callback: () => {
          deleteSelectElements();
        }
      },
      /*
      {
        keys: ["up"],
        callback: () => {
          moveNode('up', 5);
        }
      },
      {
        keys: ["down"],
        callback: () => {
          moveNode('down', 5);
        }
      },
      {
        keys: ["left"],
        callback: () => {
          moveNode('left', 5);
        }
      },
      {
        keys: ["right"],
        callback: () => {
          moveNode('right', 5);
        }
      }
     
     */ 
    ]


  },
});

lf.register({
  type: 'userTask',
  view: UserTaskView,
  model: UserTaskModel,
});
lf.register({
  type: 'systemTask',
  view: SystemTaskView,
  model: SystemTaskModel
})
lf.register({
  type: 'startNode',
  view: StartNodeView,
  model: StartNodeModel
})
lf.register({
  type: 'endNode',
  view: EndNodeView,
  model: EndNodeModel
})
lf.register({
  type: 'panduan',
  view: tiaojianNodeView,
  model: taiojianNodeModel
})
lf.register({
  type: 'startbingfa',
  view: StartBingfaView,
  model: StartBingfaModel,
})
lf.register({
  type: 'endbingfa',
  view: EndBingfaView,
  model: EndBingfaModel,
})


lf.openSelectionSelect();//开启多选

let panel = new Panel(lf, 'compentArray');
panel.rander();

let controlPanel = new ControlPanel(lf, 'controlArray');
controlPanel.rander();
controlPanel.setUndoIsActive(false);
controlPanel.setRedoIsActive(false);


let kanhouchuMenu=new KhcMenu(lf,lfwidth);






/*
lf.on('node:click', (eventObject) => {
  let nodeId = eventObject.data.id;
});
*/



lf.on('history:change', (eventObject => {
  controlPanel.setUndoIsActive(eventObject.data.undoAble);
  controlPanel.setRedoIsActive(eventObject.data.redoAble);
}))


/*
function moveNode(fangxiang, yidongliang) {
  var elements = lf.getSelectElements(true);
  var nodeArray = elements.nodes;
  let edgeArray=Array.from(lf.graphModel.edges);

  for (var i = 0; i < nodeArray.length; i++) {
    const model = lf.graphModel.getElement(nodeArray[i].id)
    
    
    //logicflow的线不能通过api调整起始位置，所以键盘快捷键移动节点可以，但是线不能】
    //动，还报错，只能等待以后支持了再说。
    /*
    if (fangxiang == 'up') {
      for(var x=0;x<edgeArray.length;x++){
        let edgeTarget=edgeArray[i];
        if(edgeTarget.targetNodeId==nodeArray[i].id){
          let edgeData=lf.getEdgeData(edgeTarget.id);
          console.log(edgeData);
          //lf.setEdgeData()
        }
      }
      model.move(0,-yidongliang)
    }
    if (fangxiang == 'down') {
      model.move(0,yidongliang)
    }
    if (fangxiang == 'left') {
      model.move(-yidongliang,0)
    }
    if (fangxiang == 'right') {
      model.move(yidongliang,0)
    }
    
  }

}*/

function deleteSelectElements() {
  var elements = lf.getSelectElements(true);
  var nodeArray = elements.nodes;
  for (var i = 0; i < nodeArray.length; i++) {
    
    lf.deleteNode(nodeArray[i].id);
  }
  var edgeArray = elements.edges;
  for (var i = 0; i < edgeArray.length; i++) {
    let edgeItem = edgeArray[i];
    lf.deleteEdge(edgeItem.id)
  }
}

document.getElementById('compentArray').onselectstart = function () { return false; };//解决拖动会选中文字的问题
document.getElementById('compentArray').ondragstart = function () { return false; };