<template>

  <div>

    <div class="dnd-app">

      <div class="dnd-wrap" ref="cRef">
        <div class="name-w">
          <div
            :data-num-type="item.type"
            v-for="item in lctLeftArr"
            data-type="rect"
            class="dnd-rect"
            @mousedown="startDrag"
          >
            {{item.name}}
          </div>
        </div>
      </div>
      <div class="dia-parent">
        <flow-chart-dialog @changeNode="changeNode" :current-op-node="currentOpNode" v-model:dialog-visible="isDialogShow"/>
      </div>
      <div class="app-content" ref="refV" >

      </div>

    </div>
    <div class="detail-operation-btn" v-if="operationType!=='detail'">
      <el-button @click="openModel" :icon="Select">保存</el-button>
    </div>
    <div v-if="isTemplateShow">
      <chooce-template v-model:dialog-visible="isTemplateShow" @importE="importE"/>
    </div>
    <template v-if="isNameDialogIsShow">
      <flow-char-name-dialog @confirm="editOrAddGooFlow" :current-op-obj="mbForm" v-model:dialog-visible="isNameDialogIsShow"/>
    </template>
  </div>
</template>

<script>
import {Selection} from "@antv/x6-plugin-selection";
import { Dnd } from "@antv/x6-plugin-dnd";
import { Graph, Dom,Shape} from '@antv/x6';
import { Scroller } from '@antv/x6-plugin-scroller'
import {onMounted, ref, watch} from 'vue'

import FlowChartDialog from "@/components/FlowChartDialog.vue";
import {getProcessMbDData} from "@/service/zsk/process-mb";
import ChooceTemplate from "@/view/other/c-views/data-handle/task-manage/task-set/ChooceTemplate.vue";
import {getGoofFlowTemplate, getGoolFlowTemplate2} from "@/service/task-manage/task-set";
import FlowCharNameDialog from "@/view/other/c-views/data-handle/task-manage/task-set/FlowCharNameDialog.vue";
import {Select} from "@element-plus/icons-vue";
import {uuidv4} from "@/unit/code";

export default {
  name: "FlowChart",
  computed: {
    Select() {
      return Select
    }
  },
  components: {FlowCharNameDialog, ChooceTemplate, FlowChartDialog},
  props:{
    isShow:{

    },
    settingType:{
      default:''
    },

    operationType:{

    },
    currentOpObj:{

    },
    pageType:{
      default:'normal'
    }
  },
  setup(props,{emit}) {
    // watch(() => props.isShow,val => {
    //   if (!val){
    //     console.log('graph.value.getEdges()',graph.value.getNodes())
    //      data.nodes = graph.value.getNodes()
    //      data.edges = graph.value.getEdges()
    //   }else {
    //     graph.value.fromJSON(data)
    //   }
    // })
    const isNameDialogIsShow = ref(false)
    const isTemplateShow = ref(false)

    let graph = ref({})
    const isDialogShow =ref(true)
    const refV = ref(null)
    const cRef = ref(null)
    const lctLeftArr = ref([
      {
        name:'流程开始',
        type:'start',
      },
      {
        name:'目录发布',
        type:'1',
      },
      {
        name:'服务发布',
        type:'11',
      },
      {
        name:'前置机入共享交换',
        type:'2',
      },
      {
        name:'数据质检',
        type:'3',
      },
      {
        name:'数据清洗',
        type:'4',
      },
      {
        name:'数据安全',
        type:'5',
      },
      {
        name:'数据标签',
        type:'6',
      },

      {
        name:'共享库入政务库',
        type:'7',
      },
      {
        name:'共享库入信用库',
        type:'8',
      },
      {
        name:'共享库入档案',
        type:'9',
      },
      {
        name:'共享库入大数据中心',
        type:'10',
      },
      {
        name:'共享库入一网通办',
        type:'17',
      },
      {
        name:'前置机入政务',
        type:'15',
      },
      {
        name:'政务入大数据中心',
        type:'16',
      },
      {
        name:'流程结束',
        type:'end',
      },
    ])
    const mbForm = ref({})
    const currentOpNode = ref(null)
    function importE(data2,isImportMb) {


      if (data2){


        mbForm.value = {
          ...mbForm.value,
          ...props.currentOpObj,
          ...data2
        }
        if (isImportMb){
             mbForm.value.id = uuidv4()
        }
        if (data2.nodes){
          data.nodes = Object.keys(data2.nodes).map(key => {
            let node = new Shape.TextBlock({

              shape:'text-block',
              text:data2.nodes[key]['name'],
              label:data2.nodes[key]['name'],
              ...data2.nodes[key],
              x:data2.nodes[key]['left'],
              width:100,
              height:60,
              y:data2.nodes[key]['top'],
              id:data2.nodes[key]['nood_id'],
              data:{
                type:data2.nodes[key]['yw_type'],
              },
              attrs: {

                foreignObject:{
                  magnet:false,
                },
                body2:{
                  position: 'static',
                  'background-color': 'transparent',
                  'text-align': 'center',
                  'margin': '0px',
                  'padding':' 0px 5px',
                  'box-sizing': 'border-box',
                  'display': 'flex',
                  'align-items': 'center',
                  'justify-content': 'center',
                  'font-size': '14px',
                  width: 100,
                  height: 40,
                  magnet:false,
                },
                body: {
                  zIndex:1,
                  magnet:false,
                  stroke: '#8f8f8f',
                  strokeWidth: 1,
                  fill: '#fff',
                  rx: 6,
                  ry: 6,
                  refWidth: '100%',
                  refHeight: '100%',
                },
                label: {
                  fontSize: 14,
                  fill: '#333333',
                  refX: '50%',
                  refY: '50%',
                  textAnchor: 'middle',
                  textVerticalAnchor: 'middle',
                  //contenteditable: "true",// 编辑开启
                },
              }
            })
            // graph.value.addNode(node)
            return {

              shape:'text-block',
              text:data2.nodes[key]['name'],
              label:data2.nodes[key]['name'],
              ...data2.nodes[key],
              x:+data2.nodes[key]['left'],
              width:100,
              height:60,
              y:+data2.nodes[key]['top'],
              id:data2.nodes[key]['nood_id'],
              data:{
                type:data2.nodes[key]['yw_type'],
              },
              attrs: {

                foreignObject:{
                  magnet:false,
                },
                body2:{
                  position: 'static',
                  'background-color': 'transparent',
                  'text-align': 'center',
                  'margin': '0px',
                  'padding':' 0px 5px',
                  'box-sizing': 'border-box',
                  'display': 'flex',
                  'align-items': 'center',
                  'justify-content': 'center',
                  'font-size': '14px',
                  width: 100,
                  height: 40,
                  magnet:false,
                },
                body: {
                  zIndex:1,
                  magnet:false,
                  stroke: '#8f8f8f',
                  strokeWidth: 1,
                  fill: '#fff',
                  rx: 6,
                  ry: 6,
                  refWidth: '100%',
                  refHeight: '100%',
                },
                label: {
                  fontSize: 14,
                  fill: '#333333',
                  refX: '50%',
                  refY: '50%',
                  textAnchor: 'middle',
                  textVerticalAnchor: 'middle',
                  // contenteditable: "true",// 编辑开启
                },
              }
            }
          })
        }
        if (data2.lines){
          data.edges = Object.keys(data2.lines).filter(i => data2.nodes && data2.nodes[data2.lines[i]['from']] && data2.nodes[data2.lines[i]['to']]).map(key => {
            return {
              ...data2.lines[key],
              source:data2.lines[key]['from'],
              target:data2.lines[key]['to'],
            }
          })
        }
      }
      isTemplateShow.value =false
      graph.value.fromJSON(data)

    }
    const data = {
      // 节点
      nodes: [],
      // 边
      edges: [

      ],
    };

    let dnd
    function changeNode(forms){
      currentOpNode.value.attr('label/text',forms.name)
      currentOpNode.value.attr('text/text',forms.name)
      // currentOpNode.value.attr('label',forms.name)
      currentOpNode.value.setData({
        'type':forms.type
      })

    }

    function getGraph() {

    }
    function  startDrag (e)  {
      const target = e.currentTarget
      const type = target.getAttribute('data-type')

      const node =
        type === 'rect'
          ? new Shape.TextBlock({
            width: 100,
            height: 40,
            text:target.innerText,
            label:target.innerText,

            data:{
              type:target.getAttribute('data-num-type'),
            },
            attrs: {
              label2:{
                text:target.innerText,
                width:'100%',
                height: '100%',

              },
              foreignObject:{
                magnet:false,
              },
              body2:{
                position: 'static',
                'background-color': 'transparent',
                'text-align': 'center',
                'margin': '0px',
                'padding':' 0px 5px',
                'box-sizing': 'border-box',
                'display': 'flex',
                'align-items': 'center',
                'justify-content': 'center',
                'font-size': '14px',
                width: 100,
                height: 40,
                magnet:false,
              },
              body: {
                zIndex:1,
                magnet:false,
                stroke: '#8f8f8f',
                strokeWidth: 1,
                fill: '#fff',
                rx: 6,
                ry: 6,
                refWidth: '100%',
                refHeight: '100%',
              },
              label: {
                fontSize: 14,
                fill: '#333333',
                refX: '50%',
                refY: '50%',
                textAnchor: 'middle',
                textVerticalAnchor: 'middle',
                //contenteditable: "true",// 编辑开启
              },
            }
          })
          : new Shape.Rect({
            width: 60,
            height: 60,
            data:{
              type:target.getAttribute('data-num-type'),
            },
            text:target.innerText,
            attrs: {
              body: {
                zIndex:1,
                magnet:false,
                stroke: '#8f8f8f',
                strokeWidth: 1,
                fill: '#fff',
                rx: 30,
                ry: 30,
                refWidth: '100%',
                refHeight: '100%',
              },
              label: {
                fontSize: 14,
                fill: '#333333',
                refX: '50%',
                refY: '50%',
                textAnchor: 'middle',
                textVerticalAnchor: 'middle',
                //contenteditable: "true",// 编辑开启
              },
            }
            // shape: 'custom-click-node',
            // markup:[
            //   {
            //     tagName: 'rect',
            //     selector: 'body',
            //   },
            //   {
            //     tagName: 'text',
            //     selector: 'label',
            //   },
            // ],
            // attrs: {
            //   btn: {
            //     refX: '100%',
            //     refX2: -28,
            //     y: 4,
            //     width: 24,
            //     height: 18,
            //     rx: 10,
            //     ry: 10,
            //     fill: 'rgba(255,255,0,0.01)',
            //     stroke: 'red',
            //     cursor: 'pointer',
            //     event: 'node:delete',
            //   },
            //   btnText: {
            //     fontSize: 14,
            //     fill: 'red',
            //     text: 'x',
            //     refX: '100%',
            //     refX2: -19,
            //     y: 17,
            //     cursor: 'pointer',
            //     pointerEvent: 'none',
            //   },
            //   body: {
            //     stroke: '#8f8f8f',
            //     strokeWidth: 1,
            //     fill: '#fff',
            //     rx: 6,
            //     ry: 6,
            //     refWidth: '100%',
            //     refHeight: '100%',
            //   },
            //   label: {
            //     text:target.innerText,
            //     fontSize: 14,
            //     fill: '#333333',
            //     refX: '50%',
            //     refY: '50%',
            //     textAnchor: 'middle',
            //     textVerticalAnchor: 'middle',
            //   },
            // },
          })

      dnd.start(node, e)
    }
    function draw() {
      if (props.pageType === 'process'){
        getGoolFlowTemplate2(props.currentOpObj.ID).then(res => {
          importE(res.msg[0].Rows[0],false)
        })
      }else {
        getGoofFlowTemplate(props?.currentOpObj?.CATALOG_CODE).then(res => {
          let data2 = res.msg[0].Rows[0]

          if (data2){
            if (data2.nodes){
              data.nodes = Object.keys(data2.nodes).map(key => {
                let node = new Shape.TextBlock({

                  shape:'text-block',
                  text:data2.nodes[key]['name'],
                  label:data2.nodes[key]['name'],
                  ...data2.nodes[key],
                  x:data2.nodes[key]['left'],
                  width:100,
                  height:60,
                  y:data2.nodes[key]['top'],
                  id:data2.nodes[key]['nood_id'],
                  data:{
                    type:data2.nodes[key]['yw_type'],
                  },
                  attrs: {

                    foreignObject:{
                      magnet:false,
                    },
                    body2:{
                      position: 'static',
                      'background-color': 'transparent',
                      'text-align': 'center',
                      'margin': '0px',
                      'padding':' 0px 5px',
                      'box-sizing': 'border-box',
                      'display': 'flex',
                      'align-items': 'center',
                      'justify-content': 'center',
                      'font-size': '14px',
                      width: 100,
                      height: 40,
                      magnet:false,
                    },
                    body: {
                      zIndex:1,
                      magnet:false,
                      stroke: '#8f8f8f',
                      strokeWidth: 1,
                      fill: '#fff',
                      rx: 6,
                      ry: 6,
                      refWidth: '100%',
                      refHeight: '100%',
                    },
                    label: {
                      fontSize: 14,
                      fill: '#333333',
                      refX: '50%',
                      refY: '50%',
                      textAnchor: 'middle',
                      textVerticalAnchor: 'middle',
                      //contenteditable: "true",// 编辑开启
                    },
                  }
                })
                // graph.value.addNode(node)
                return {

                  shape:'text-block',
                  text:data2.nodes[key]['name'],
                  label:data2.nodes[key]['name'],
                  ...data2.nodes[key],
                  x:+data2.nodes[key]['left'],
                  width:100,
                  height:60,
                  y:+data2.nodes[key]['top'],
                  id:data2.nodes[key]['nood_id'],
                  data:{
                    type:data2.nodes[key]['yw_type'],
                  },
                  attrs: {

                    foreignObject:{
                      magnet:false,
                    },
                    body2:{
                      position: 'static',
                      'background-color': 'transparent',
                      'text-align': 'center',
                      'margin': '0px',
                      'padding':' 0px 5px',
                      'box-sizing': 'border-box',
                      'display': 'flex',
                      'align-items': 'center',
                      'justify-content': 'center',
                      'font-size': '14px',
                      width: 100,
                      height: 40,
                      magnet:false,
                    },
                    body: {
                      zIndex:1,
                      magnet:false,
                      stroke: '#8f8f8f',
                      strokeWidth: 1,
                      fill: '#fff',
                      rx: 6,
                      ry: 6,
                      refWidth: '100%',
                      refHeight: '100%',
                    },
                    label: {
                      fontSize: 14,
                      fill: '#333333',
                      refX: '50%',
                      refY: '50%',
                      textAnchor: 'middle',
                      textVerticalAnchor: 'middle',
                      // contenteditable: "true",// 编辑开启
                    },
                  }
                }
              })
            }
            if (data2.lines){
              console.log('Object.keys(data2.lines).filter(i => data2.nodes && data2.nodes[i])',Object.keys(data2.lines).filter(i => data2.nodes && data2.nodes[i]))
              data.edges = Object.keys(data2.lines).filter(i => data2.nodes && data2.nodes[data2.lines[i]['from']] && data2.nodes[data2.lines[i]['to']]).map(key => {
                return {
                  ...data2.lines[key],
                  source:data2.lines[key]['from'],
                  target:data2.lines[key]['to'],
                }
              })
            }
            mbForm.value = {
              ...mbForm.value,
              ...props.currentOpObj,
              ...data2,
              CATALOG_NAME:data2.title
            }

            emit('changeFormD',mbForm.value)

          }
          graph.value.fromJSON(data)

        })
      }
    }
    onMounted(() =>{
      if (props.currentOpObj){

        mbForm.value = {
          ...props.currentOpObj,
          ...mbForm.value
        }

      }
      if (!+props.currentOpObj.STATE && props.operationType!=='detail'){
        //   未配置
        isTemplateShow.value = true
      }
      graph.value = new Graph({
        container:refV.value,
        width: '100%',
        height:600,
        panning: true,
        mousewheel: true,
        grid:{
          visible:true
        },
        highlighting: {
          magnetAdsorbed:{
            name: "stroke",
            args: {
              attrs: {
                fill: "transparent",
                stroke: '#f00',
                // strokeWidth: 2,
              },
            },
          },
          // 连接桩可以被连接时在连接桩外围围渲染一个包围框
          magnetAvailable: {
            name: "stroke",
            args: {
              attrs: {
                fill: "transparent",
                stroke: "#f00",
                strokeWidth: 1,
              },
            },
          },
        },
        connecting: {
          snap: true,
          allowBlank: false,
          allowNode: true,
          allowEdge: false,
          allowLoop: false,
          allowMulti:false,
          allowPort:false,
          validateMagnet(){
            return true
          },
          vertexDeletable(){
            return true
          }
          // createEdge(){
          // return  this.createEdge({
          //    shape:'edge',
          //    attrs:{
          //      line: {
          //        stroke: "#8f8f8f",
          //        strokeWidth: 1,
          //      },
          //    }
          //  })
          // },
          // 连接装的样式

        },


      })

      // graph.value.use(
      //   new Scroller({
      //     enabled: true,
      //     pannable: false,
      //     pageVisible: false,
      //     pageBreak: true,
      //     autoResize: true,
      //     minVisibleWidth: 50,
      //     minVisibleHeight: 50,
      //   }),
      // )
      graph.value.use(
        new Selection({
          enabled: true,
          multiple: false,
          rubberband: true,
          movable: true,
          showNodeSelectionBox: false,
          pointerEvents: "none",

        })
      );

      dnd = new Dnd({
        target: graph.value,
        scaled: false,
        dndContainer: cRef.value,
      })

      graph.value.on('node:delete', ({ view, e }) => {
        e.stopPropagation()
        view.cell.remove()
      })
      graph.value.on('edge:selected', (each) => {
        console.log('便选择',each)
        // e.stopPropagation()
        each.edge.addTools({
          name: 'button-remove',
          args: {distance: 20},
        })
      })
      graph.value.on('node:dblclick',({node}) => {

        if (['2','7','8','9','10','15','16'].includes(node.data.type)){
          // 前置机
          emit('update:settingType',node.data.type)

        }else if (node.data.type === '4'){
          // 数据清洗
          emit('update:settingType',node.data.type)

        }else if (node.data.type === '3'){
          // 数据清洗
          emit('update:settingType',node.data.type)

        }else if (node.data.type === '6'){
          // 数据清洗
          emit('update:settingType',node.data.type)

        }else if (node.data.type === '5'){
          // 数据清洗
          emit('update:settingType',node.data.type)

        }else if (node.data.type === 'start'){
          // 数据清洗
          emit('update:settingType',node.data.type)

        }
        // let isChange = node.data.type === 'start' || node.data.type === '1'
        // isChange &&
      })
      graph.value.on('node:mouseenter',({node}) => {

        node.addTools({
          name: 'button-remove',
          args: {distance: 20},
        })
        // node.attr('body/magnet',true)
        // node.attr('foreignObject/magnet',true)
      })
      graph.value.on('node:selected', ({node}) => {
        node.attr('body/magnet',true)
        node.attr('foreignObject/magnet',true)
        currentOpNode.value = node || {}


      })
      graph.value.on('node:unselected', ({node}) => {
        node.attr('body/magnet',false)
        node.attr('foreignObject/magnet',false)
        node.removeTools()
        currentOpNode.value = null
      })
      graph.value.on('node:mouseleave',({node}) => {
        node.removeTools()
      })
      graph.value.on('edge:unselected', ({edge}) => {
        edge.removeTools()
      })


      draw()

      // const source = graph.value.addNode({
      //   shape: 'custom-click-node',
      //   x: 40,
      //   y: 80,
      //   width: 120,
      //   height: 40,
      //   attrs: {
      //     label: {
      //       text: 'Source',
      //     },
      //   },
      // })

      // graph.value.on('edge:click',each=>{
      //   let arr = each.edge.markup
      //   arr.splice(1,0,{
      //         tagName:'text',
      //     selector:'btnText'
      //   })
      //   each.edge.markup = arr
      //   each.edge.attr('btnText',{
      //     fontSize: 14,
      //     fill: 'red',
      //     text: 'x',
      //     refX: '100%',
      //     refX2: -19,
      //     y: 17,
      //     cursor: 'pointer',
      //     pointerEvent: 'none',
      //   })
      //   // console.log(each,'s')
      //   // each.e.stopPropagation()
      //   // graph.value.removeEdge(each.edge)
      //
      // })


    })
    function openModel() {
      isNameDialogIsShow.value = true
    }
    function editOrAddGooFlow(form) {
      let allNodes = graph.value.getNodes()
      let allLine = graph.value.getEdges()
      isNameDialogIsShow.value = false

      emit('editOrAddGooFlow',allNodes,allLine,form)
    }
    return {
      refV,
      cRef,
      startDrag,
      lctLeftArr,
      graph,

      isDialogShow,
      currentOpNode,
      changeNode,
      editOrAddGooFlow,
      importE,
      isTemplateShow,
      mbForm,
      isNameDialogIsShow,
      openModel,
      data
    }
  }
}
</script>

<style scoped lang="scss">
.dnd-app {
  display: flex;
  padding: 0;
  position: relative;
  font-family: sans-serif;

  .app-content {
    position: relative;
    z-index: 1;
    flex: 1;
    height: 240px;
    margin-right: 8px;
    margin-left: 8px;
    box-shadow: 0 0 10px 1px #e9e9e9;
  }

  .dnd-wrap {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 200px;
    padding: 16px;
    border: 1px solid #f0f0f0;
    user-select: none;

    .dnd-rect {
      margin-bottom: 5px;

      padding: 5px;
      text-align: center;
      border: 1px solid #8f8f8f;
      border-radius: 6px;
      cursor: move;
    }

    .dnd-circle {
      width: 60px;
      height: 60px;
      margin: 16px;
      line-height: 60px;
      text-align: center;
      border: 1px solid #8f8f8f;
      border-radius: 100%;
      cursor: move;
    }
  }
}
.dia-parent{

   position: absolute;
  /* flex: 1; */
  /* right: 40px; */
  /* top: 40px; */
  left: 242px;
  right: 8px;
  height: 100%;
}
.btns{
  text-align: center;
  margin: 20px 0;
  padding-bottom: 20px;
}
</style>
