<template>
  <div class="page-wrapper batch-import">
    <div class="page-container">
      <a-form-model
        ref="FormModel"
        class="logical-chart-form"
        layout="inline"
        :model="form"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
      >
        <a-row :gutter="24" type="flex" justify="start">
          <a-col :span="8">
            <a-form-model-item
              :rules="[
                {
                  required: true,
                  message: $t('PLACEENTER'),
                  trigger: 'blur',
                },
              ]"
              prop="chainName"
              :label="$t('LINK_NAME')"
            >
              <a-input
                v-model="form.chainName"
                :placeholder="$t('PLACEENTER')"
                allow-clear
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              :rules="[
                {
                  required: true,
                  message: $t('PLACEENTER'),
                  trigger: 'blur',
                },
              ]"
              :label="$t('LINK_IDENTIFICATION')"
              prop="chainKey"
            >
              <a-input
                v-model="form.chainKey"
                :placeholder="$t('PLACEENTER')"
                allow-clear
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              :label="$t('TAGCATEGORY_LABEL')"
              :rules="[
                {
                  required: true,
                  message: $t('PLACEENTER'),
                  trigger: 'change',
                },
              ]"
              prop="category"
            >
              <a-select v-model="form.category" style="width: 100%" allow-clear>
                <a-select-option
                  v-for="item in categoryList"
                  :key="item.value"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <FlowGraphComp
        ref="FlowGraphComp"
        :groups="groups"
        :graph-data="graphData"
      />
    </div>

    <div class="page-bottom-op">
      <a-button
        icon="save"
        type="primary"
        :loading="saveLoading"
        @click="handleSave"
      >
        {{ $t("SAVE") }}
      </a-button>
      <a-button @click="goBack">
        <Icon type="icon-dir-f-rollback" :size="18" /> {{ $t("CANCEL") }}
      </a-button>
    </div>
  </div>
</template>

<script>
import { Icon } from "@mega-design/ui-vue";
import FlowGraphComp from "@/components/LogicalChart/index.jsx";
import ApiConstant from "@/api/ApiConstant";
import { getObjByString } from "@/utils/util";

export default {
  components: { FlowGraphComp, Icon },
  data() {
    return {
      form: {
        id: null,
        chainName: undefined, // 业务名
        chainKey: undefined, // 业务key
        category: undefined, // 分类
        disableFlag: undefined, // 状态
        modular: undefined, // 模块
        remark: undefined,
      },
      saveLoading: false,
      categoryList: [],
      groups: [],
      graphData: {},
    };
  },
  mounted() {
    this.getComponent();
  },
  methods: {
    async getComponent() {
      await this.getDictByCode("DIC:SYS:FLOW_CATEGORY").then((res) => {
        this.categoryList = res.data.data;
      });
      const { id } = this.$route.query;
      id &&
        this.$axios
          .get(`${ApiConstant.PREFIX_CORE}/api/sys/flow-chain/detail/${id}`)
          .then((res) => {
            this.graphData = this.resData(res.data.data);
            Object.keys(this.form).forEach((key) => {
              this.form[key] = res.data.data[key];
            });
          });
      await this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/flow-chain/list-all-component`)
        .then((res) => {
          this.groups = res.data.data;
        });
    },
    handleSave() {
      this.saveLoading = true;
      this.$refs.FormModel.validate((valid) => {
        if (valid) {
          const { nodeList, nodeRelList } = this.reqData();

          this.$axios
            .put(`${ApiConstant.PREFIX_CORE}/api/sys/flow-chain`, {
              ...this.form,
              nodeList,
              nodeRelList,
            })
            .then(() => {
              this.saveLoading = false;
              this.$message.success(this.$t("EDIT_SUCCESS"));
              this.$store.dispatch("tagsView/jumpBeforeView", {
                to: { path: "/upms/operationFlow/serviceLink" },
                vm: this,
              });
            })
            .catch(() => {
              this.saveLoading = false;
            });
        } else {
          this.saveLoading = false;
        }
      });
    },
    resData(data) {
      const graphData = {
        cells: [],
      };
      const { nodeList = [], nodeRelList = [] } = data;

      nodeList.forEach((item) => {
        const { nodeType, id } = item;
        const color = nodeType === "COMPONENT" ? "#005583" : "#00DC99";
        const { ports = {}, attrs = {} } = getObjByString(item.pointInfo) || {};
        graphData.cells.push({
          id,
          data: {
            id: item.objectId,
            nodeType,
            nodeKey: attrs.title?.text,
            nodeName: attrs.text?.text,
          },
          shape: "custom-node",
          position: {
            x: item.positionX,
            y: item.positionY,
          },
          ports,
          attrs: {
            ...attrs,
            head: {
              fill: color,
              stroke: color,
            },
            divide: {
              fill: color,
              stroke: color,
            },
          },
        });
      });
      nodeRelList.forEach((item) => {
        graphData.cells.push({
          id: item.id,
          shape: "edge",
          router: {
            name: "manhattan",
          },
          source: {
            cell: item.nodeId,
            port: item.nodePoint,
          },
          target: {
            cell: item.nextNodeId,
            port: item.nextNodePoint,
          },
        });
      });
      return graphData;
    },
    reqData() {
      const nodeList = [];
      const nodeRelList = [];
      const { cells = [] } = this.$refs.FlowGraphComp.flowGraphJson() || {};
      cells.forEach((item) => {
        const id = item.id.replace(/[-]/g, "");
        if (item.shape === "custom-node") {
          nodeList.push({
            id,
            nodeType: item.data.nodeType,
            objectId: item.data.id,
            positionX: item.position.x,
            positionY: item.position.y,
            pointInfo: JSON.stringify({
              attrs: {
                title: {
                  text: item.data.nodeKey,
                },
                text: {
                  text: item.data.nodeName,
                },
              },
              ports: {
                items: item.ports.items.map((e) => ({
                  ...e,
                  id: e.id.replace(/[-]/g, ""),
                })),
              },
            }),
          });
        } else if (item.shape === "edge") {
          nodeRelList.push({
            id,
            nodeId: item.source.cell.replace(/[-]/g, ""),
            nextNodeId: item.target.cell.replace(/[-]/g, ""),
            nodePoint: item.source.port.replace(/[-]/g, ""),
            nextNodePoint: item.target.port.replace(/[-]/g, ""),
          });
        }
      });

      return { nodeList, nodeRelList };
    },
    goBack() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: { path: "/upms/operationFlow/serviceLink" },
        vm: this,
      });
    },
  },
};
</script>

<style lang="less" scoped>
.page-container {
  padding-top: 20px;
  .logical-chart-form {
    padding: 0 20px;
    border-bottom: 1px solid rgb(218, 221, 225);
    /deep/.ant-form-item {
      margin-bottom: 22px;
      margin-right: 0;
      width: 100%;
    }
  }
}
</style>
