<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_MAP.get(item.approveType) + '）'"
          :value="item"
        />
      </el-select>
    </div>
  </div>
  <div class="flow-view-box" v-loading="contentLoading">
    <div id="flow-view-content"></div>
  </div>
  <TeleportContainer />
  <FlowConfig v-model:drawerVisible="drawerVisible" :nodeAttribute="nodeAttribute"></FlowConfig>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { getTeleport } from '@antv/x6-vue-shape';
import { queryFlowTemplateDetailApi, queryFlowTemplateVersionApi } from '@/api/capability/flow';
import { ElMessage } from 'element-plus';
import { FLOW_APPROVE_MAP } from '@/utils/enum/flow';
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';

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

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.msg);
  }
};

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

const contentLoading = ref(false);

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;
  } else {
    ElMessage.error(res.msg);
  }
};

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) => {
    console.log('click node', node);
    if (node.data.isApp) {
      nodeAttribute.value = node.data;
      drawerVisible.value = true;
    }
  });
};

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

      // const dataJson = JSON.parse(props.data.approveContents).viewContents;
      // // contentLoading.value = true;
      // console.log('dataJson', dataJson);
      // setTimeout(() => {
      //   if (dataJson.length > 50) {
      //     graph.value.fromJSON(dataJson);
      //     graph.value.centerContent();
      //   }
      //   contentLoading.value = false;
      // }, 3000);
    }
  });
  // document.addEventListener('keydown', (e) => {
  //   console.log('e', 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)  ;
    }
  }
}
</style>
