<template>
  <div class="gl-page-content no-padding flow-content">
    <!-- <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_STATUS.O[item.approveType] + '）'"
            :value="item"
          />
        </el-select>
      </div>
      <div class="center-box">
        <el-tooltip effect="dark" content="上一步">
          <img @click="undoFun(graph)" src="@/assets/imgs/dragFlow/undo.svg" alt="" />
        </el-tooltip>
        <el-tooltip effect="dark" content="放大画布">
          <img @click="zoomOutFun(graph)" src="@/assets/imgs/dragFlow/magnify.svg" alt="" />
        </el-tooltip>
        <el-tooltip effect="dark" content="缩小画布">
          <img @click="zoomInFun(graph)" src="@/assets/imgs/dragFlow/lessen.svg" alt="" />
        </el-tooltip>
        <el-tooltip effect="dark" content="框选节点垂直居中">
          <img @click="yAlign(graph)" src="@/assets/imgs/dragFlow/vertical-center.svg" alt="" />
        </el-tooltip>
        <el-tooltip effect="dark" content="框选节点横向分布">
          <img
            @click="xAlign(graph)"
            src="@/assets/imgs/dragFlow/lateral-distribution.svg"
            alt=""
          />
        </el-tooltip>
        <el-tooltip effect="dark" content="框选节点删除">
          <img
            id="delete-btn"
            @click="deleteFun(graph)"
            src="@/assets/imgs/dragFlow/delete-black.svg"
            alt=""
          />
        </el-tooltip>
      </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"
      :graph="graph"
    />
    <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_OPERATION_TYPE } from '@/utils/enum/flow';
import { getRelationNodeAndVerifyFlowFun } from './components/flow';
import { cancelKeyboardEvents } from './components/keyboard';
import { useDict } from '@/utils/useDict';

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 { FLOW_APPROVE_STATUS } = useDict('FLOW_APPROVE_STATUS');

const flowName = ref('');

const currentVersion = ref<any>();

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

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

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

const TeleportContainer = getTeleport();

const graph = ref<any>();

const getFlowVersionOptions = async () => {
  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.message);
  }
};

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

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

const saveDraftFun = async (callback?: () => void) => {
  const dataJson = graph.value.toJSON();
  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.message);
    }
  }
  if (callback) {
    callback();
  }
};

const showApproveDia = ref(false);

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

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

onMounted(async () => {
  graph.value = await initGraph();
  await getFlowVersionOptions();
});

onBeforeUnmount(() => {
  cancelKeyboardEvents();
});
</script>
<style lang="scss" src="./index.scss" scoped></style>
<style lang="scss">
.x6-widget-stencil.collapsable.collapsed > .x6-widget-stencil-title::before,
.x6-widget-stencil-group.collapsable.collapsed > .x6-widget-stencil-group-title::before {
  background-image: url(@/assets/imgs/dragFlow/close.svg) !important;
  background-size: 10px;
  background-position: center;
}
.x6-widget-stencil.collapsable > .x6-widget-stencil-title::before,
.x6-widget-stencil-group.collapsable > .x6-widget-stencil-group-title::before {
  background-image: url(@/assets/imgs/dragFlow/open.svg) !important;
  background-size: 10px;
  background-position: center;
}
.x6-widget-stencil-title {
  display: none;
}
.x6-widget-stencil-title,
.x6-widget-stencil-group > .x6-widget-stencil-group-title {
  height: 25px;
}

#flow-create-content {
  display: flex;
  border: 1px solid #dfe3e8;
  // height: calc(100vh - 176px);
  // height: 100%;
  // height: calc(100% - 40px) !important;
  height: 100%;
  width: 100%;
}
#stencil {
  width: 220px;
  height: 100%;
  position: relative;
  border-right: 1px solid #dfe3e8;
}
#graph-container {
  width: calc(100% - 180px);
  height: 100%;
}
.x6-widget-stencil {
  background-color: #fff;
}
.x6-widget-stencil-title {
  background-color: #fff;
}
.x6-widget-stencil-group-title {
  background-color: #fff !important;
}
.x6-widget-transform {
  margin: -1px 0 0 -1px;
  padding: 0px;
  border: 1px solid #239edd;
}
.x6-widget-transform > div {
  border: 1px solid #239edd;
}
.x6-widget-transform > div:hover {
  background-color: #3dafe4;
}
.x6-widget-transform-active-handle {
  background-color: #3dafe4;
}
.x6-widget-transform-resize {
  border-radius: 0;
}
.x6-widget-selection-inner {
  border: 1px solid #239edd;
}
.x6-widget-selection-box {
  opacity: 0;
}
.x6-widget-stencil-content {
  .x6-port-body {
    visibility: hidden !important;
  }
}
</style>
