<template>
  <div style="width: 100%; height: 100%">
    <a-spin :spinning="loading" :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">{{ diagramName }}</span>
            <div>
              <a-space :size="16">
                <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="graphDetail" v-if="graphDetail" showBusinessGraph backUrl="/mid/app/summary?type=2"></flow-design>
          </a-layout-content>
        </a-layout>
      </div>
    </a-spin>
  </div>
</template>

<script setup name="BusinessGraphDesign">
import html2canvas from 'html2canvas';
import { message } from 'ant-design-vue';
import { onMounted, ref, watch, defineAsyncComponent } from 'vue';
import { useWorkflowStore } from '@/store/modules/workflow';
import { useRoute, useRouter } from 'vue-router';
import { BusinessGraphApi } from '../api/BusinessGraphApi';
import { FileApi } from '@/views/system/backend/file/api/FileApi';

const FlowDesign = defineAsyncComponent(() => import('../../../../flow-design/index.vue'));

defineOptions({
  name: 'BusinessGraphDesign'
});

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

// store
const workflowStore = useWorkflowStore();

// 业务图id
const diagramId = ref('');
// 业务图名称
const diagramName = ref('');
// 加载状态
const loading = ref(false);
// 业务图数据
const graphDetail = ref(null);

const businessGrpahDetail = ref(null);

const currentType = ref('1');

//div内容生成图片
const generateImage = callback => {
  const element = document.getElementById('workflow-graph');
  if (!element) {
    callback('');
    return;
  }
  html2canvas(element, {
    useCORS: true // 添加这个选项以解决跨域问题
  }).then(canvas => {
    // 将canvas转换为图片数据URL
    const image = canvas.toDataURL('image/png');
    convertImageToBlob(image, blob => {
      const formData = new FormData();
      formData.append('file', blob, 'business_graph.png');
      FileApi.commonUpload('N', formData).then(res => {
        callback(res.data.fileId);
      });
    });
  });
};

// 使用fetch API将图片数据URL转换为Blob对象
const convertImageToBlob = (image, callback) => {
  fetch(image)
    .then(res => res.blob())
    .then(blob => callback(blob));
};

/**
 * 保存模型
 */
const save = flag => {
  generateImage(fileId => {
    loading.value = true;
    const params = {
      ...businessGrpahDetail.value,
      diagramFileId: fileId,
      diagramContent: workflowStore.graph.toJSON()
    };
    BusinessGraphApi.edit(params)
      .then(res => {
        loading.value = false;
        message.success(res.message);
        if (flag == 'back') {
          gotoUpLevel();
        }
      })
      .finally(() => (loading.value = false));
  });
};

/**
 * 获取业务图详情
 */
const getGraphDesignDetail = () => {
  loading.value = true;
  const params = {
    diagramId: diagramId.value
  };
  BusinessGraphApi.detail(params)
    .then(result => {
      businessGrpahDetail.value = result;
      diagramName.value = businessGrpahDetail.value?.diagramName;
      let xsixGraphJson = businessGrpahDetail.value?.diagramContent;
      if (xsixGraphJson) {
        graphDetail.value = xsixGraphJson;
      } else {
        graphDetail.value = { cells: [] };
      }
    })
    .catch(() => {
      // 接口有错则跳转到上一级
      gotoUpLevel();
    })
    .finally(() => {
      loading.value = false;
    });
};

/**
 * 跳转到上级
 */
const gotoUpLevel = () => {
  let path = '';
  if (currentType.value == '1') {
    path = '/mid/app/detail';
  } else if (currentType.value == '2') {
    path = '/mid/app/summary';
  }
  router.push({
    path: path,
    query: { type: currentType.value == '2' ? '2' : 'busGraph' }
  });
};

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

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

  if (!route.query.diagramId) {
    gotoUpLevel();
  }

  if (!route.query.type) {
    gotoUpLevel();
  }

  // 模型id赋值
  diagramId.value = route.query.diagramId;

  currentType.value = route.query.type;

  // 获取业务图详情
  getGraphDesignDetail();
};

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>
