<template>
  <div style="width: 100%; height: 100%">
    <a-spin :spinning="modelLoading" :delay="100">
      <div class="workflow-design">
        <a-layout>
          <a-layout-header class="workflow-design-header">
            <div>
              <a-space>
                <div class="back" @click="gotoUpLevel"><LeftOutlined class="back-icon" /> 返回</div>
              </a-space>
            </div>
            <span class="modelName">{{ modelName }}</span>
            <div>
              <a-space :size="16">
                <a-button size="mini" @click="upgrade" class="green-btn border-radius">
                  <span>升级</span>
                </a-button>
                <a-button size="mini" @click="save('back')" class="blue-btn border-radius">
                  <span>保存并退出</span>
                </a-button>
                <a-button type="primary" size="mini" class="border-radius" @click="save()">保存</a-button>
              </a-space>
            </div>
          </a-layout-header>
          <a-layout-content>
            <flow-design v-model="modelDetail" v-if="modelDetail" :backUrl="backUrl"></flow-design>
          </a-layout-content>
        </a-layout>
      </div>
    </a-spin>
  </div>
</template>

<script setup name="WorkflowDesign">
import { onMounted, ref, provide, watch } from 'vue';
import { useWorkflowStore } from '@/store/modules/workflow';
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { FlowDesignApi } from './api/FlowDesignApi';
import FlowDesign from '../../../flow-design/index.vue';

// route
const route = useRoute();
const router = useRouter();

// store
const workflowStore = useWorkflowStore();

// 流程模型id
const modelId = ref('');
// 模型名称
const modelName = ref('');
// 模型加载状态
const modelLoading = ref(false);
// 模型数据
const modelDetail = ref(null);
// 流程设计id
const definitionId = ref('');

// 用于项目流程
const currentType = ref('');

const backUrl = ref('');

provide('modelId', modelId);
provide('definitionId', definitionId);

/**
 * 保存模型
 */
const save = flag => {
  modelLoading.value = true;
  if (definitionId.value) {
    const params = {
      definitionId: definitionId.value,
      sixGraphDesign: {
        flowGlobalConfig: workflowStore.flowGlobalConfig,
        nodeGraph: workflowStore.graph.toJSON()
      }
    };
    FlowDesignApi.saveSixGraphDesign(params)
      .then(res => {
        modelLoading.value = false;
        message.success(res.message);
        if (flag == 'back') {
          gotoUpLevel();
        }
      })
      .finally(() => (modelLoading.value = false));
  } else {
    modelLoading.value = false;
  }
};

/**
 * 流程设计升级版本
 */
const upgrade = () => {
  modelLoading.value = true;
  if (definitionId.value) {
    const params = {
      definitionId: definitionId.value,
      sixGraphDesign: {
        flowGlobalConfig: workflowStore.flowGlobalConfig,
        nodeGraph: workflowStore.graph.toJSON()
      }
    };
    // 修改
    FlowDesignApi.upgradeAndSave(params).then(res => {
      modelLoading.value = false;
      message.success(res.message);
      definitionId.value = res.data;
      // 刷新页面
      router.push({
        path: '/mid/workflow/design',
        query: {
          modelId: modelId.value,
          definitionId: definitionId.value
        }
      });
      getFlowDesignDetail();
    });
  } else {
    modelLoading.value = false;
  }
};

/**
 * 获取流程详情
 */
const getFlowDesignDetail = () => {
  if (!definitionId.value) return;
  modelLoading.value = true;
  const params = {
    definitionId: definitionId.value
  };
  FlowDesignApi.flowDesignDetail(params)
    .then(result => {
      let modelData = result.data;
      modelName.value = modelData?.modelName;
      workflowStore.setFlowGlobalConfig(modelData.xsixGraphJson);
      let xsixGraphJson = modelData?.xsixGraphJson?.nodeGraph;
      if (xsixGraphJson) {
        modelDetail.value = xsixGraphJson;
      } else {
        modelDetail.value = { cells: [] };
      }
    })
    .catch(() => {
      // 接口有错则跳转到上一级
      gotoUpLevel();
    })
    .finally(() => {
      modelLoading.value = false;
    });
};

/**
 * 跳转到上级
 */
const gotoUpLevel = () => {
  router.push(backUrl.value);
};

onMounted(() => {
  init();
});

const init = () => {
  // 阻止浏览器快捷键
  document.onkeydown = e => {
    // ctrl + s   command + s
    if ((e.metaKey || e.ctrlKey) && e.key === 's') {
      // 阻止默认事件
      e.preventDefault();
    }
  };

  if (!route.query.modelId) {
    gotoUpLevel();
  }
  if (!route.query.definitionId) {
    gotoUpLevel();
  }

  if (route.query?.type) {
    currentType.value = route.query.type;
  }

  // 模型id赋值
  modelId.value = route.query.modelId;
  // 流程设计id赋值
  definitionId.value = route.query.definitionId;

  getBackUrl();
  // 赋值modelid
  useWorkflowStore().setDefinitionId(definitionId.value);

  // 获取流程详情
  getFlowDesignDetail();
};

const getBackUrl = () => {
  if (!currentType.value) {
    backUrl.value = '/mid/workflow/model';
  } else if (currentType.value == 'workFlow') {
    backUrl.value = '/mid/project/work?type=4';
  } else if (currentType.value == 'reviewFlow') {
    backUrl.value = '/mid/project/review?type=6';
  } else if (currentType.value == 'integration') {
    backUrl.value = '/mid/devops/integration';
  } else if (currentType.value == 'bussinessFlow') {
    backUrl.value = '/mid/app/detail?type=flow';
  }
};

watch(
  () => route.path,
  val => {
    if (val == '/mid/workflow/design') {
      init();
    }
  }
);
</script>

<style scoped lang="less">
.workflow-design {
  display: flex;
  width: 100%;
  height: 100%;
}

.workflow-design-header {
  display: flex;
  justify-content: space-between;
  background-color: #fff;
  border-bottom: 1px #d9d9d9 solid;
}

:deep(.ant-layout-header) {
  padding: 0 16px;
  height: 72px;
  line-height: 72px;
}
.modelName {
  padding-left: 50px;
  font-size: 18px;
  font-weight: bold;
  margin-right: 10px;
}
.back {
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  color: #60666b;
}
.back-icon {
  font-size: 14px;
  color: #b9bcbe;
}
.blue-btn {
  color: var(--primary-color);
  font-weight: bold;
  border: 1px solid var(--primary-color);
}
.green-btn {
  color: #43cf7c;
  font-weight: bold;
  border: 1px solid #43cf7c;
}
</style>
