<template>
  <!-- <el-button @click="exportJson">导出json</el-button>
    <el-button @click="importJson">导入json</el-button> -->
  <div class="header-box" id="header-box">
    <div class="left-box">
      <span class="name">{{ flowName }}</span>
      <!-- <span class="line">|</span>
      <span class="version">版本：</span> -->
      <el-select
        v-if="type === 'review'"
        @change="changeVersionFun"
        class="select-box"
        value-key="uuid"
        v-model="currentVersion"
      >
        <el-option
          v-for="item in flowVersionOptions"
          :key="item.uuid"
          :label="item.templateVersion + '（' + FLOW_APPROVE_STATUS.O[item.approveType] + '）'"
          :value="item"
        />
      </el-select>
      <span v-if="flowDetailInfo?.templateType">
        分析方向：{{ DISCIPLINE_TYPE.O[flowDetailInfo.templateType] }}
      </span>
      <span v-if="flowDetailInfo?.comment"> 备注：{{ flowDetailInfo.comment }} </span>
    </div>
  </div>
  <div class="flow-view-box" v-loading="contentLoading">
    <div id="flow-view-content"></div>
  </div>
  <TeleportContainer />
  <FlowConfig
    :graph="graph"
    v-model:drawerVisible="drawerVisible"
    :nodeAttribute="nodeAttribute"
  ></FlowConfig>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { getTeleport } from '@antv/x6-vue-shape';
import { queryFlowTemplateDetailApi, queryFlowTemplateVersionApi } from '@/api/capability/flow';
import { ElMessage } from 'element-plus';
import { Graph } from '@antv/x6';
import { createNode, getNodeList } from '@/views/simulation/creation/components/stencil';
import { registerCustomNode } from '@/views/simulation/creation/components/registerNode';
import FlowConfig from './flowConfig.vue';
import { useDict } from '@/utils/useDict';

const props = defineProps({
  flowUuid: {
    type: String,
    default: '',
  },
  data: {
    type: Object,
    default: () => ({}),
  },
  type: {
    type: String,
    default: 'review',
  },
  flowCode: {
    type: String,
    default: '',
  },
});

const { FLOW_APPROVE_STATUS, DISCIPLINE_TYPE } = useDict('FLOW_APPROVE_STATUS', 'DISCIPLINE_TYPE');

const flowName = ref('');

const currentVersion = ref<any>();

const flowVersionOptions = ref<any[]>([]);

const TeleportContainer = getTeleport();

const graph = ref<any>();

const nodeAttribute = ref();

const drawerVisible = ref(false);

const getFlowVersionOptions = async () => {
  const params: any = {};
  if (props.flowUuid) {
    params.code = props.flowUuid;
    params.type = 0;
  } else {
    params.code = props.flowCode;
    params.type = 1;
  }
  const res: any = await queryFlowTemplateVersionApi(params);
  if (res.code === 200) {
    flowVersionOptions.value = res.data.map((item: any) => {
      return {
        templateVersion: item.templateVersion,
        approveType: item.approveType,
        uuid: item.uuid,
      };
    });
    if (flowVersionOptions.value.length > 0) {
      currentVersion.value = flowVersionOptions.value[flowVersionOptions.value.length - 1];
      getFlowDetail(currentVersion.value.uuid);
    }
  } else {
    ElMessage.error(res.message);
  }
};

const changeVersionFun = () => {
  getFlowDetail(currentVersion.value.uuid);
};

const contentLoading = ref(false);

const flowDetailInfo = ref();

const getFlowDetail = async (uuid: string) => {
  contentLoading.value = true;
  const res: any = await queryFlowTemplateDetailApi({ uuid: uuid, status: 1 });
  if (res.code === 200) {
    if (res.data.viewContent.length > 50) {
      const dataJson = JSON.parse(res.data.viewContent);
      setTimeout(() => {
        graph.value.fromJSON(dataJson);
        graph.value.centerContent();
        contentLoading.value = false;
      }, 1000);
    } else {
      contentLoading.value = false;
    }
    flowName.value = res.data.templateName;
    flowDetailInfo.value = res.data;
  } else {
    ElMessage.error(res.message);
  }
};

const initGraph = async () => {
  graph.value = new Graph({
    panning: {
      enabled: true,
    },
    interacting: {
      // 禁用画布拖拽
      nodeMovable: false,
    },
    container: document.getElementById('flow-view-content') as HTMLElement,
    autoResize: true,
    //	画布的最小最大缩放级别
    scaling: { min: 0.5, max: 3 },
    grid: true,
    // width: 800,
    // height: 800,
    background: {
      color: '#F2F7FA',
    },
    connecting: {
      connector: { name: 'smooth' },
      connectionPoint: 'anchor',
      allowBlank: false,
      snap: { radius: 20 },
      allowEdge: false,
      allowLoop: false,
      highlight: true,
    },
  });
  registerCustomNode();
  const nodeList = await getNodeList();
  createNode(nodeList, graph.value);

  graph.value.on('node:click', ({ node }: any) => {
    if (node.data.isApp) {
      nodeAttribute.value = node.data;
      drawerVisible.value = true;
      node.addTools({
        name: 'boundary',
        args: {
          padding: 0,
          attrs: {
            // fill: '#7c68fc',
            stroke: '#0366FF ',
            'stroke-width': 2,
            'stroke-dasharray': '',
            rx: 4,
            ry: 4,
          },
        },
      });
    }
  });
};

watch(
  () => drawerVisible.value,
  (val: boolean) => {
    if (!val) {
      graph.value.getNodes().forEach((item: any) => {
        item.removeTools();
      });
    }
  }
);

onMounted(async () => {
  setTimeout(async () => {
    await initGraph();
    if (props.type === 'review') {
      await getFlowVersionOptions();
    }
    if (props.type === 'approve') {
      getFlowDetail(JSON.parse(props.data.approveContents).flowId);

      // const dataJson = JSON.parse(props.data.approveContents).viewContents;
      // // contentLoading.value = true;
      // setTimeout(() => {
      //   if (dataJson.length > 50) {
      //     graph.value.fromJSON(dataJson);
      //     graph.value.centerContent();
      //   }
      //   contentLoading.value = false;
      // }, 3000);
    }
  });
  // document.addEventListener('keydown', (e) => {
  // });
});
</script>
<style lang="scss">
.flow-view-box {
  height: calc(100% - 40px);
}
#header-box {
  padding: 0;
  height: auto;
  margin-bottom: var(--margin-medium);
  .left-box {
    display: flex;
    align-items: center;
    width: 500px;
    span {
      display: inline-block;
      flex-shrink: 0;
      margin-right: var(--margin-medium);
    }
  }
  .select-box {
    width: 200px;
    flex-shrink: 0;
    margin-right: var(--margin-medium);
  }
}
</style>
