<template>
  <div class="gl-page-content no-padding">
    <!-- <el-button @click="exportJson">导出json</el-button>
    <el-button @click="importJson">导入json</el-button> -->
    <div class="header-box">
      <div class="left-box">
        <img class="back" @click="goBack" src="@/assets/imgs/dragFlow/back.svg" alt="">
        <span class="name">{{ flowName }}</span>
        <span class="line">|</span>
        <span class="version">版本：</span>
        <el-select
          @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 class="center-box">
        <img @click="undoFun(graph)" src="@/assets/imgs/dragFlow/undo.svg" alt="">
        <img @click="zoomOutFun(graph)" src="@/assets/imgs/dragFlow/magnify.svg" alt="">
        <img @click="zoomInFun(graph)" src="@/assets/imgs/dragFlow/lessen.svg" alt="">
        <img @click="yAlign" src="@/assets/imgs/dragFlow/vertical-center.svg" alt="">
        <img src="@/assets/imgs/dragFlow/lateral-distribution.svg" alt="">
      </div>
      <div class="right-box">
        <el-button v-if="operationType !== FLOW_OPERATION_TYPE.UPGRADE" @click="saveDraftFun()">保存草稿</el-button>
        <el-button type="primary" @click="openApproveDiaFun">提交评审</el-button>
      </div>
    </div>
    <div id="flow-box">
      <div :id="FLOW_CREATE_ID">
      </div>
    </div>
    <TeleportContainer />
    <ConfigPage v-if="drawerVisible" v-model:drawerVisible="drawerVisible" :nodeAttribute="nodeAttribute" />
    <ApproveDialog
      v-model:showDialog="showApproveDia"
      :uuid="currentVersion?.uuid"
      :versionType="currentVersion?.templateVersion"
      :graph="graph"
      :nodeRelation="nodeRelation"
      :flowDetail="flowDetail"
      :operationType="operationType"
      @saveDraft="saveDraftFun"
      :templateVersion="templateVersion"
    ></ApproveDialog>
  </div>
</template>
<script setup lang="ts">

import { onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import { getTeleport } from '@antv/x6-vue-shape';
import { useNodeAttribute, useNodeEvents } from './components/nodeEvents';
import ConfigPage from './components/configPage.vue';
import { queryFlowTemplateDetailApi, queryFlowTemplateVersionApi, updateFlowTemplateDraftApi } from '@/api/capability/flow';
import { ElMessage } from 'element-plus';
import { FLOW_CREATE_ID, initGraph } from './components/initGraph';
import ApproveDialog from './components/approveDialog.vue';
import { FLOW_APPROVE_MAP, FLOW_OPERATION_TYPE } from '@/utils/enum/flow';
import { getRelationNodeAndVerifyFlowFun } from './components/flow';
import { cancelKeyboardEvents } from './components/keyboard';

const props = defineProps({
  flowUuid: {
    type: String,
    default: '',
  },
  // operationType: {
  //   type: FLOW_OPERATION_TYPE,
  // },
  templateVersion: {
    type: String,
    default: '',
  },
  operationType: {
    type: String,
    default: FLOW_OPERATION_TYPE.CREATE,
  },
});

const emits = defineEmits(['goBack']);

const flowName = ref('');

const currentVersion = ref<any>();

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

const { drawerVisible, nodeAttribute } = useNodeAttribute();
const { undoFun, zoomInFun, zoomOutFun, yAlign } = useNodeEvents();

// 注册连线
// registerCustomConnector();

const TeleportContainer = getTeleport();

const graph = ref<any>();

const getFlowVersionOptions = async() => {
  console.log('123', 123);
  const res:any = await queryFlowTemplateVersionApi({ type: 0, code: props.flowUuid });
  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();
    }
  } else {
    ElMessage.error(res.msg);
  }
};

const changeVersionFun = () => {
  drawerVisible.value = false;
  getFlowDetail();
};

const flowDetail = reactive<any>({
  uuid: '',
  version: '',
  comment: '',
  templateName: '',
  templateType: '',
});

const getFlowDetail = async() => {
  const res:any = await queryFlowTemplateDetailApi({ uuid: currentVersion.value.uuid, status: 1 });
  if (res.code === 200) {

    // flowDetail.uuid = res.data.uuid;
    // flowDetail.templateVersion = res.data.templateVersion;
    // flowDetail.templateName = res.data.templateName;
    // flowDetail.comment = res.data.comment;
    // flowDetail.templateType = res.data.templateType;

    for (const key in res.data) {
      flowDetail[key] = res.data[key];
    }

    if (res.data.viewContent.length > 50) {
      const dataJson = JSON.parse(res.data.viewContent);
      graph.value.fromJSON(dataJson);
    }
    flowName.value = res.data.templateName;
  } else {
    ElMessage.error(res.msg);
  }
};

const goBack = () => {
  emits('goBack');
};

const saveDraftFun = async(callback?: () => void) => {
  const dataJson = graph.value.toJSON();
  console.log('dataJson', dataJson);
  if (!callback) {
    nodeRelation.value = getRelationNodeAndVerifyFlowFun(graph.value.model.collection.cells, flowDetail.templateName, flowDetail.uuid);
  }
  const res:any = await updateFlowTemplateDraftApi({ ...flowDetail, uuid: props.flowUuid, viewContent: JSON.stringify(dataJson), templateContent: JSON.stringify(nodeRelation.value) });
  if (!callback) {
    if (res.code === 200) {
      ElMessage.success('保存成功');
    } else {
      ElMessage.error(res.msg);
    }
  }
  if (callback) {
    console.log('callback', 111);
    callback();
  }
};

const showApproveDia = ref(false);

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

const openApproveDiaFun = () => {
  console.log('graph.value', graph.value);
  nodeRelation.value = getRelationNodeAndVerifyFlowFun(graph.value.model.collection.cells, flowDetail.templateName, flowDetail.uuid);
  console.log('nodeRelation.value', nodeRelation.value);
  if (nodeRelation.value) {
    showApproveDia.value = true;
  }
};

onMounted(async() => {
  graph.value = await initGraph();
  await getFlowVersionOptions();
  // document.addEventListener('keydown', (e) => {
  //   console.log('e', e);
  // });
});

onBeforeUnmount(() => {
  cancelKeyboardEvents();
});

</script>
<style lang="scss" src="./index.scss">
</style>
