<template>
  <div>
    <MomTable
      ref="MomTable"
      row-key="id"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryParam"
      :query-param-item="queryFormItem"
      :action-buttons="actionButtons"
      :total="total"
      :page.sync="page"
      :mega-extend="{
        rowAction: {
          width: 74,
        },
      }"
      @beforeSearch="beforeSearch"
      @search="searchPageData"
    >
      <template slot="status" slot-scope="text">
        <span :class="[[1, '1'].includes(text) && 'text-error']">
          {{ getAttrValue(queryFormItem.status.options, text) }}
        </span>
      </template>
    </MomTable>
    <!-- 流程追踪 -->
    <BpmnTrack
      v-if="trackParams.id"
      :key="trackParams.id"
      :track-visible.sync="trackVisible"
      :params="trackParams"
    />
    <MegaModal
      :visible="closeFormVisible"
      :title="$t('CLOSE')"
      width="480px"
      @cancel="handleCloseFormCancel"
      @ok="handleCloseFormOk"
    >
      <a-form-model
        ref="addForm"
        :model="closeForm"
        :rules="closeFormRules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-form-model-item :label="$t('CLOSE_REASON')">
          <a-input v-model="closeForm.closeReason" allow-clear />
        </a-form-model-item>
      </a-form-model>
    </MegaModal>
  </div>
</template>

<script>
import { Modal as MegaModal } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import BpmnTrack from "@/components/bpmn/track";

export default {
  components: {
    MegaModal,
    BpmnTrack,
  },
  data() {
    return {
      // 表格的配置项
      tableColumns: [
        {
          dataIndex: "procInstName",
          sorter: false,
          ellipsis: true,
          width: 300,
          title: () => this.$t("PROCESS_NAME"), // 流程名称
        },
        {
          dataIndex: "procDefKey",
          sorter: false,
          ellipsis: true,
          width: 260,
          title: () => this.$t("PROCESS_KEY"), // 流程key
        },
        // {
        //   dataIndex: "businessKey",
        //   sorter: false,
        //   ellipsis: true,
        //   minWidth: 160,
        //   title: () => this.$t("BUSINESS_KEY"), // 业务key
        // },
        {
          dataIndex: "startUserName",
          sorter: false,
          width: 140,
          title: () => this.$t("SPONSOR"), // 发起人
        },
        {
          dataIndex: "startTime",
          sorter: false,
          title: () => this.$t("CREATION_TIME"), // 创建时间
        },
        {
          dataIndex: "endTime",
          sorter: false,
          title: () => this.$t("COMPLETE_TIME"), // 完成时间
        },
        {
          dataIndex: "status",
          sorter: false,
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "status" },
        },
      ],
      tableData: [],
      page: 1, // 页码
      total: 0, // 每页个数
      // 查询的表单的配置项
      queryParam: {
        procInstName: undefined,
        time: null,
        status: undefined,
      },
      actionButtons: [
        (h, { record }) => {
          return (
            <a-button
              title={this.$t("PROCESS_TRACKING")}
              type="link"
              onClick={() => this.handleOpenTrack(record)}>
              <a-icon type="interaction" />
            </a-button>
          );
        },
        (h, { record }) => {
          return (
            <a-button
              title={this.$t("OPEN")}
              type="link"
              onClick={() => this.handleOpen(record, true)}>
              <a-icon type="folder-open" />
            </a-button>
          );
        },
        (h, { record }) => {
          return (
            false &&
            ["1", 1].includes(record.status) && (
              <a-button
                class="text-error"
                onClick={() => this.handleClose(record)}>
                <a-icon type="poweroff" title={this.$t("CLOSE")} />
              </a-button>
            )
          );
        },
        (h, { record }) => {
          return (
            false &&
            ["2", 2].includes(record.status) && (
              <a-button type="link" onClick={() => this.handleDelete(record)}>
                <a-icon type="delete" title={this.$t("DELETE")} />
              </a-button>
            )
          );
        },
      ],
      // 流程追踪
      trackVisible: false,
      trackParams: {
        id: undefined,
        type: "INS",
      },
      // 流程关闭的表单
      closeFormVisible: false,
      closeForm: {
        id: null,
        closeReason: undefined,
      },
      closeFormRules: {
        closeReason: [],
      },
    };
  },
  computed: {
    // 表格搜索配置
    queryFormItem() {
      return this.$observable("queryFormItem", {
        procInstName: {
          itemType: "input",
          label: () => this.$t("PROCESS_NAME"), // 流程名称
        },
        time: {
          itemType: "range",
          valueFormat: "YYYY-MM-DD",
          label: () => this.$t("STARTING_TIME"), // 发起时间
        },
        status: {
          itemType: "select",
          label: () => this.$t("STATUS"),
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
      });
    },
  },
  methods: {
    beforeSearch() {
      return Promise.all([this.getDictByCode("DIC:WORKFLOW:INS_STATUS")]).then(
        ([res]) => {
          this.queryFormItem.status.options = res?.data?.data || [];
        }
      );
    },
    // 后台分页查询
    searchPageData(params) {
      const req = { ...params };
      delete req.time;
      req.startTime = params.time?.length ? `${params.time[0]} 00:00:00` : null;
      req.endTime = params.time?.length ? `${params.time[1]} 23:59:59` : null;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/flowable/instance/search`, {
          params: req,
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    // 点击表格行内的编辑
    handleEdit(row) {
      Object.keys(this.form).forEach((key) => {
        this.form[key] = row[key];
      });
      this.drawerVisible = true;
    },
    // 行内 删除事件
    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/instance/${id}`)
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 行内 流程跟踪
    handleOpenTrack(item) {
      this.$set(this.trackParams, "id", item.procInsId);

      this.trackVisible = true;
    },
    // 行内 打开事件
    handleOpen(item) {
      this.$router.push({
        path: "/flowable/instance/open",
        query: {
          id: item.procInsId,
          type: "INS",
          returnUrl: this.$route.fullPath,
        },
      });
    },
    // 行内 关闭事件
    handleClose(row) {
      this.closeForm.id = row.procInsId;
      this.closeFormVisible = true;
    },
    // 关闭流程 取消
    handleCloseFormCancel() {
      this.closeFormVisible = false;
    },
    // 关闭流程 确认
    handleCloseFormOk() {
      this.$axios
        .post(
          `${ApiConstant.PREFIX_CORE}/api/flowable/instance/stop`,
          this.closeForm
        )
        .then(() => {
          this.$message.success(this.$t("CLOSE_SUCCESS"));
          this.closeFormVisible = false;
          this.$refs.MomTable?.query();
        });
    },
  },
};
</script>
<style lang="less">
.icon-defult {
  font-weight: 600;
}
</style>
