<template>
  <div>
    <BasicTable
      @register="registerTable"
      @selection-change="handleSelectionChange"
    >
      <template #tableTitle>
        <a-button
          type="primary"
          @click="handleModelAdd"
        >新增</a-button>
        <a-button
          danger
          type="primary"
          :disabled="state.multiple"
          @click="handleDel()"
        >删除</a-button>
        <a-button
          type="primary"
          :disabled="state.single"
          @click="setProcessCategory"
        >设置分类</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '设计',
                icon: 'fa6-regular:pen-to-square',
                onClick: handleDesign.bind(null, record)
              },
              {
                label: '发布',
                icon: 'fa-solid:bullhorn',
                onClick: handleDeploy.bind(null, record)
              }]"
            :dropDownActions="[
              {
                label: '激活',
                icon: 'fa-solid:toggle-on',
                ifShow: record.processDefinition?.suspend,
                onClick: handleProcessActive.bind(null, record)
              },
              {
                label: '挂起',
                icon: 'fa-solid:toggle-off',
                ifShow: !record.processDefinition?.suspend,
                onClick: handleProcessSuspend.bind(null, record)
              },
              {
                label: '导出',
                icon: 'fa-solid:file-import',
                onClick: handleExportXml.bind(null, record)
              },
              {
                label: '复制',
                icon: 'ant-design:copy-outlined',
                onClick: handleCopy.bind(null, record)
              },
              {
                label: '删除',
                icon: 'ant-design:delete-outlined',
                onClick: handleDel.bind(null, record)
              }]"
          />
        </template>
      </template>
    </BasicTable>
    <WorkflowModelDesign @register="registerWorkflowModelDesign" @success="handleRefreshTable"/>
  </div>
</template>

<script lang="ts">
  /**
   * 提供模板规范代码参考,请尽量保证编写代码风格跟模板规范代码一致
   * 采用vben-动态表格表单封装组件编写,不采用 setup 写法
   * Copyright © 2023-2023 <a href="https://godolphinx.org">海豚生态开源社区</a> All rights reserved.
   * author wangxiang4
   */
  import { defineComponent, reactive, toRaw } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { listModel, delModel, copyModel, bpmnXmlDownload, deployModel } from '/@/api/platform/workflow/controller/model';
  import { setProcessInstanceStatus } from '/@/api/platform/workflow/controller/process';
  import { useModal } from '/@/components/Modal';
  import { columns, searchFormSchema } from './model.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import WorkflowModelDesign from './helper/WorkflowModelDesign.vue';

  interface TableState {
    ids: string[];
    single: boolean;
    multiple: boolean;
  }
  export default defineComponent({
    name: 'WorkflowModel',
    components: {
      BasicTable,
      TableAction,
      WorkflowModelDesign,
    },
    setup() {
      const state = reactive<TableState>({
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
      });
      const { createConfirm, createMessage } = useMessage();
      const [registerWorkflowModelDesign , { openModal: openWorkflowModelDesign }] = useModal();
      const [registerTable, { reload, clearSelectedRowKeys }] = useTable({
        api: listModel,
        rowKey: 'id',
        columns,
        formConfig: {
          compact: true,
          labelWidth: 100,
          schemas: searchFormSchema,
          autoSubmitOnEnter: true,
          showAdvancedButton: true,
          autoAdvancedLine: 3
        },
        rowSelection: { type: 'checkbox' },
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        clickToRowSelect: false,
        showIndexColumn: false,
        actionColumn: {
          width: 240,
          title: '操作',
          dataIndex: 'action',
          fixed: false
        },
        handleSearchInfoFn: () => clearSelectedRowKeys()
      });

      function handleSelectionChange(selection?: Recordable) {
        const rowSelection = toRaw(selection?.keys) || [];
        state.ids = rowSelection;
        state.single = rowSelection.length != 1;
        state.multiple = !rowSelection.length;
      }

      function  setProcessCategory() {

      }

      function  handleModelAdd() {
        openWorkflowModelDesign(true,{ _tag: 'add' });
      }

      function  handleDesign(record?: Recordable) {
        record = record || { id: toRaw(state.ids) };
        openWorkflowModelDesign(true, { _tag: 'edit', record });
      }

      function handleDeploy(record?: Recordable) {
        createConfirm({
          iconType: 'warning',
          title: '警告',
          content: '确认要发布流程吗？',
          onOk: async () => {
            await deployModel(record?.id, record?.category || '未分类');
            createMessage.success('发布成功!');
            handleRefreshTable();
          }
        });
      }

      function handleProcessActive(record?: Recordable) {
        createConfirm({
          iconType: 'warning',
          title: '警告',
          content: '确认要激活该流程吗?',
          onOk: async () => {
            await setProcessInstanceStatus(record?.modelKey, 'active');
            createMessage.success('激活成功!');
            handleRefreshTable();
          }
        });
      }

      function handleProcessSuspend(record?: Recordable) {
        createConfirm({
          iconType: 'warning',
          title: '警告',
          content: '确认要挂起该流程吗?',
          onOk: async () => {
            await setProcessInstanceStatus(record?.modelKey, 'suspend');
            createMessage.success('挂起成功!');
            handleRefreshTable();
          }
        });
      }

      function handleExportXml(record?: Recordable) {
        bpmnXmlDownload(record?.id);
      }

      function handleCopy(record?: Recordable) {
        createConfirm({
          iconType: 'warning',
          title: '警告',
          content: '确定复制该流程吗？',
          onOk: async () => {
            await copyModel(record?.id);
            createMessage.success('复制成功!');
            handleRefreshTable();
          }
        });
      }

      async function handleDel(record?: Recordable) {
        const ids = record?.id || toRaw(state.ids);
        createConfirm({
          iconType: 'warning',
          title: '警告',
          content: '确定删除该流程吗?删除流程会级联删除已经存在的实例与历史数据，且不可恢复，请谨慎操作!',
          onOk: async () => {
            await delModel(ids);
            createMessage.success('删除成功!');
            handleRefreshTable();
          }
        });
      }

      function handleRefreshTable() {
        clearSelectedRowKeys();
        reload();
      }

      return {
        state,
        registerTable,
        handleDel,
        handleSelectionChange,
        handleRefreshTable,
        registerWorkflowModelDesign,
        setProcessCategory,
        handleModelAdd,
        handleDesign,
        handleExportXml,
        handleCopy,
        handleProcessActive,
        handleProcessSuspend,
        handleDeploy
      };
    }
  });
</script>
