<template>
  <MegaSplitPanes class="process-model-page">
    <MegaSplitPane size="18">
      <a-tree
        v-if="treeData.length"
        :block-node="true"
        :default-expand-all="true"
        :tree-data="treeData"
        :replace-fields="{
          children: 'children',
          key: 'id',
          value: 'id',
          title: 'label',
        }"
        @select="handleNodeClick"
      />
      <div v-else>
        {{ $t("NO_DATA") }}
      </div>
    </MegaSplitPane>
    <MegaSplitPane size="82">
      <MomTable
        ref="MomTable"
        row-key="id"
        :columns="columns"
        :data-source="tableData"
        :query-param="queryParam"
        :query-param-item="queryParamItem"
        :action-buttons="actionButtons"
        :page.sync="page"
        :total="total"
        :mega-extend="{
          rowAction: {
            width: 140,
          },
        }"
        @beforeSearch="beforeSearch"
        @search="searchPageData"
        @edit="(record) => handleEdit(record)"
        @delete="handleDelete"
      >
        <div slot="toolbar" class="button-top-table">
          <a-button
            v-if="hasAuth('USER_MANAGEMENT:ADD')"
            type="primary"
            @click="handleAdd"
          >
            <a-icon type="plus" />
            {{ $t("ADD") }}
          </a-button>
        </div>
        <template slot="status" slot-scope="text">
          <span :class="getStatusColor(text)">
            {{ getAttrValue(queryParamItem.status.options, text) }}
          </span>
        </template>
      </MomTable>
    </MegaSplitPane>
  </MegaSplitPanes>
</template>
<script>
import { SplitPanes as MegaSplitPanes, Icon } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";

export default {
  components: {
    MegaSplitPanes,
    MegaSplitPane: MegaSplitPanes.Pane,
    // eslint-disable-next-line vue/no-unused-components
    Icon,
  },
  data() {
    return {
      treeData: [],
      tableData: [],
      // 表格列配置项
      columns: [
        {
          dataIndex: "id",
          title: () => this.$t("PROCESS_ID"),
        },
        {
          dataIndex: "name",
          title: () => this.$t("PROCESS_NAME"),
        },
        {
          dataIndex: "category",
          title: () => this.$t("PROCESS_CATEGORY"),
        },
        {
          dataIndex: "version",
          title: () => this.$t("PROCESS_VERSION"),
          sorter: false,
        },
        {
          dataIndex: "status",
          title: () => this.$t("STATUS"),
          width: 80,
          sorter: false,
          scopedSlots: { customRender: "status" },
        },
      ],
      total: 0,
      page: 1,
      // 当前点击节点的类型和编码
      currentClickNode: {},
      // 查询的表单的配置项
      queryParam: {
        name: undefined, // 流程名称
        status: undefined, // 状态 1-设计 2-启用 3-禁用
      },
      actionButtons: [
        "edit",
        (h, { record }) => {
          return (
            <a-button
              type="link"
              title={this.$t("EDIT_NEW_VERSION")}
              onClick={() => this.handleEdit(record, true)}>
              <Icon type="icon-cur-a-versionmanagement" size={16} />
            </a-button>
          );
        },
        (h, { record, index }) => {
          const { status, deployId } = record;
          if ([1, "1"].includes(status)) {
            return (
              <a-button
                title={this.$t("RELEASE")}
                type="link"
                onClick={() => this.handlePublish(record)}>
                <Icon
                  type="icon-cur-release"
                  size={15}
                  style="color: #3dc2e5; cursor: pointer"
                />
              </a-button>
            );
          }
          if ([2, "2"].includes(status)) {
            return (
              <a-button
                title={this.$t("DISABLED")}
                type="link"
                onClick={() =>
                  this.handleToggleEnable(
                    { deployId, status: "2" },
                    "DISABLED",
                    "DISABLED_DATA_INFO",
                    "DISABLE_SUCCESS"
                  )
                }>
                <a-icon type="stop" class="text-error" />
              </a-button>
            );
          }
          if ([3, "3"].includes(status)) {
            return (
              <a-button
                title={this.$t("ENABLED")}
                type="link"
                onClick={() =>
                  this.handleToggleEnable(
                    { deployId, status: "3" },
                    "ENABLED",
                    "ENABLED_DATA_INFO",
                    "ENABLE_SUCCESS"
                  )
                }>
                <a-icon type="check-circle" />
              </a-button>
            );
          }
          return null;
        },
        "delete",
      ],
    };
  },
  computed: {
    // 表格搜索配置项
    queryParamItem() {
      return this.$observable("queryFormItem", {
        name: {
          itemType: "input",
          label: () => this.$t("PROCESS_NAME"),
        },
        status: {
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
          label: () => this.$t("STATUS"),
        },
      });
    },
  },
  mounted() {
    this.getTreeData();
  },
  methods: {
    getStatusColor(text) {
      if ([2, "2"].includes(text)) {
        return "text-success";
      }
      if ([3, "3"].includes(text)) {
        return "text-error";
      }
      return "";
    },
    /**
     *获取左侧流程分类树图
     */
    getTreeData() {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/flowable/category/tree`)
        .then((res) => {
          this.treeData = res.data.data;
        });
    },
    // 获取数据字典
    beforeSearch() {
      Promise.all([
        this.getDictByCode("DIC:WORKFLOW:MODEL_STATUS"), // 状态 1-设计 2-启用 3-禁用
      ]).then(([res]) => {
        this.queryParamItem.status.options = res.data.data;
      });
    },
    /**
     * 获取右侧table的数据
     */
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/flowable/model/search`, {
          params: {
            ...params,
            category: this.currentClickNode.categoryId || null,
          },
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    // 点击节点查询数据
    handleNodeClick(node) {
      this.currentClickNode = {};
      // eslint-disable-next-line prefer-destructuring
      this.currentClickNode.categoryId = node[0];
      this.$refs.MomTable?.query();
    },
    handleAdd() {
      this.$router.push({
        path: "/flowable/model/add",
      });
    },
    // 点击表格行内的编辑
    handleEdit(row, isNewVersion) {
      this.$router.push({
        path: "/flowable/model/edit",
        query: {
          id: row.id,
          newVersion: isNewVersion ? "1" : "0",
        },
      });
    },
    handleDelete({ id }) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/flowable/model/${id}`)
            .then((res) => {
              this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 发布
    handlePublish({ id }) {
      this.$confirm({
        title: this.$t("RELEASE"),
        content: this.$t("RELEASE_INFO"),
        okType: "warning",
        okText: this.$t("RELEASE"),
        cancelText: this.$t("CANCEL"),
        onOk: () => {
          this.$axios
            .post(`${ApiConstant.PREFIX_CORE}/api/flowable/model/deploy/${id}`)
            .then(() => {
              this.$message.success(this.$t("RELEASE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 启用 禁用
    handleToggleEnable({ deployId, status }, titleText, contentText, tips) {
      this.$confirm({
        title: this.$t(titleText),
        content: this.$t(contentText),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        onOk: () => {
          this.$axios
            .post(
              `${ApiConstant.PREFIX_CORE}/api/flowable/definition/update-status/${deployId}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
  },
};
</script>
<style lang="less" scoped>
.process-model-page {
  position: absolute;
}

/deep/.form-header {
  height: 56px;
}
/deep/.btn-item {
  padding-left: 30px;
}

/deep/.ant-table td {
  white-space: nowrap;
}
</style>
