<template>
  <MegaSplitPanes class="setting-user-page">
    <MegaSplitPane size="60">
      <MomTable
        ref="MomTable"
        row-key="id"
        :columns="columns"
        :row-selection="rowSelection"
        :data-source="tableData"
        :query-param="queryParam"
        :query-param-item="queryParamItem"
        :action-buttons="actionButtons"
        :show-enable-flag="true"
        :page.sync="page"
        :total="total"
        :custom-row="handRowClick"
        @beforeSearch="beforeSearch"
        @search="searchPageData"
        @edit="handleEdit"
        @delete="handleDelete"
        @enable="
          (record) =>
            handleStatus(
              { status: 'Y', id: record.id },
              'ENABLED',
              'ENABLED_DATA_INFO',
              'ENABLE_SUCCESS'
            )
        "
        @disable="
          (record) =>
            handleStatus(
              { status: 'N', id: record.id },
              'DISABLED',
              'DISABLED_DATA_INFO',
              'DISABLE_SUCCESS'
            )
        "
      >
        <div slot="toolbar" class="button-top-table">
          <a-button
            v-if="hasAuth('BUSINESS_CHAIN:ADD')"
            type="primary"
            @click="handleAdd"
          >
            <a-icon type="plus" />
            {{ $t("ADD") }}
          </a-button>
          <a-button
            v-if="hasAuth('BUSINESS_CHAIN:BATCH_DELETE')"
            type="danger"
            icon="delete"
            @click="handDelete"
          >
            {{ $t("BATCH_DELETE") }}
          </a-button>
        </div>
        <span slot="category" slot-scope="text, record">
          <span>
            {{ formatData(flowList, record.category) }}
          </span>
        </span>
        <span slot="source" slot-scope="text, record">
          <span>
            {{ formatData(sourceList, record.source) }}
          </span>
        </span>
        <span slot="enableFlag" slot-scope="text, record">
          <span v-if="record.enableFlag == 'Y'" style="color: #0fd19c">
            {{ formatData(enableFlaglist, record.enableFlag) }}
          </span>
          <span v-else style="color: #d45f5f">
            {{ formatData(enableFlaglist, record.enableFlag) }}
          </span>
        </span>
      </MomTable>
    </MegaSplitPane>
    <MegaSplitPane size="40">
      <a-collapse
        v-model="activeName"
        :bordered="false"
        expand-icon-position="right"
        class="collapse-header-divide"
      >
        <a-collapse-panel key="a" :header="$t('FLOW')">
          <FlowGraphComp
            ref="FlowGraphComp"
            :is-show="false"
            :graph-data="graphData"
          />
        </a-collapse-panel>
      </a-collapse>
    </MegaSplitPane>
  </MegaSplitPanes>
</template>
<script>
import { SplitPanes as MegaSplitPanes } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import FlowGraphComp from "@/components/LogicalChart/index.jsx";
import { getObjByString } from "@/utils/util";

export default {
  components: {
    MegaSplitPanes,
    FlowGraphComp,
    MegaSplitPane: MegaSplitPanes.Pane,
  },
  data() {
    return {
      activeName: "a",
      tableData: [],
      enableFlaglist: [],
      flowList: [],
      sourceList: [],
      // 表格列配置项
      total: 0,
      page: 1,
      graphData: {},
      // 当前点击节点的类型和编码
      // 查询的表单的配置项
      queryParam: {
        chainName: "", // 用户名
        chainKey: "", // 关联员工工号
        category: "", // 姓名
      },
      actionButtons: [
        this.hasAuth("BUSINESS_CHAIN:EDIT") && "edit",
        this.hasAuth("BUSINESS_CHAIN:DELETE") && "delete",
      ],
      selectedRowKeys: [],
      handRowClick: (record) => ({
        // 事件
        on: {
          click: (e) => {
            // 点击改行时要做的事情
            const oldList = document.querySelectorAll(
              ".checked-td-of-add-table"
            );
            if (oldList) {
              // eslint-disable-next-line no-plusplus
              for (let j = 0; j < oldList.length; j++) {
                oldList[j].classList.remove("checked-td-of-add-table");
              }
            }

            const { children } = e.target.parentNode;
            // eslint-disable-next-line no-plusplus
            for (let i = 0; i < children.length; i++) {
              children[i].classList.add("checked-td-of-add-table");
            }
            this.$axios
              .get(
                `${ApiConstant.PREFIX_CORE}/api/sys/flow-chain/detail/${record.id}`
              )
              .then((res) => {
                this.graphData = this.resData(res.data.data);
              });
          },
        },
      }),
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    // 表格搜索配置项
    queryParamItem() {
      return {
        chainName: {
          itemType: "input",
          labelCol: { span: 8 },
          wrapperCol: { span: 16 },
          label: () => this.$t("LINK_NAME"),
        },
        chainKey: {
          itemType: "input",
          labelCol: { span: 8 },
          wrapperCol: { span: 16 },
          label: () => this.$t("LINK_IDENTIFICATION"),
        },
        category: {
          itemType: "select",
          label: () => this.$t("TAGCATEGORY_LABEL"),
          optionsProps: {
            label: "label",
            value: "value",
          },
          options: [],
        },
      };
    },
    columns() {
      return [
        {
          dataIndex: "chainName",
          title: () => this.$t("LINK_NAME"),
          minWidth: 120,
        },
        {
          dataIndex: "chainKey",
          title: () => this.$t("LINK_IDENTIFICATION"),
          width: 120,
        },
        {
          dataIndex: "category",
          title: () => this.$t("TAGCATEGORY_LABEL"),
          scopedSlots: { customRender: "category" },
          width: 120,
        },
        {
          dataIndex: "modular",
          title: () => this.$t("BLONGING_MODEL"),
          width: 90,
          sorter: false,
          scopedSlots: { customRender: "modular" },
        },
        {
          dataIndex: "enableFlag",
          title: () => this.$t("STATUS"),
          width: 120,
          sorter: false,
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "source",
          title: () => this.$t("COMPONENT_SOURCE"),
          width: 90,
          sorter: false,
          scopedSlots: { customRender: "source" },
        },
        {
          dataIndex: "updateBy",
          title: () => this.$t("UPDATE_BY"),
          width: 120,
          sorter: false,
        },
        {
          dataIndex: "updateTime",
          title: () => this.$t("UPDATE_TIME"),
          width: 168,
        },
      ];
    },
  },
  methods: {
    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;
    },
    // 格式化数据
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    // 获取数据字典
    beforeSearch() {
      Promise.all([
        this.getDictByCode("DIC:COMMON:ENABLE_FLAG"),
        this.getDictByCode("DIC:SYS:FLOW_CATEGORY"),
        this.getDictByCode("DIC:SYS:FLOW_SOURCE"),
      ]).then(([statusRes, flowRes, sourceRes]) => {
        this.enableFlaglist = statusRes.data.data;
        this.flowList = flowRes.data.data;
        this.queryParamItem.category.options = flowRes.data.data;
        this.sourceList = sourceRes.data.data;
      });
    },
    // 获取table的数据
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/flow-chain/search`, { params })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    handleAdd() {
      this.$router.push({
        path: "/upms/operationFlow/serviceLink/add",
      });
    },
    // 点击表格行内的编辑
    handleEdit(row) {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: {
          path: "/upms/operationFlow/serviceLink/edit",
          query: {
            id: row.id,
          },
        },
        vm: this,
        del: false,
      });
    },
    // 启用、禁用
    handleStatus(record, titleText, contentText, tips) {
      this.$confirm({
        title: this.$t(titleText),
        content: this.$t(contentText),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          const { id, status } = record;
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/sys/flow-chain/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    handDelete() {
      if (this.selectedRowKeys.length > 0) {
        this.$confirm({
          title: this.$t("DELETE"),
          content: this.$t("DELETE_INFO"),
          okType: "warning",
          okText: this.$t("CONFIRM"),
          cancelText: this.$t("CANCEL"),
          centered: false,
          icon: "close-circle",
          onOk: () => {
            this.$axios
              .delete(
                `${ApiConstant.PREFIX_CORE}/api/sys/flow-chain/batch-delete`,
                {
                  params: {
                    ids: this.selectedRowKeys.join(","),
                  },
                }
              )
              .then((res) => {
                this.$message.success(this.$t("DELETE_SUCCESS"));
                this.$refs.MomTable?.query();
              });
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    handleDelete({ id }) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/sys/flow-chain/${id}`)
            .then((res) => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
  },
};
</script>
<style lang="less" scoped>
.setting-user-page {
  position: absolute;
}
/deep/ .checked-td-of-add-table {
  background: #e6feff;
}
</style>
