<template>
  <PageWrapper
    contentClass="flex"
    contentFullHeight
    fixedHeight
    dense
  >
    <div class="m-4 mr-0 overflow-hidden bg-white w-1/4 xl:w-1/5">
      <BasicTree title="流程分类"
                 toolbar
                 search
                 defaultExpandAll
                 :clickRowToExpand="false"
                 :treeData="state.treeData"
                 :fieldNames="{ key: 'id', title: 'name' }"
                 @select="handleSelect"
      />
    </div>
    <BasicTable class="w-3/4 xl:w-4/5" @register="registerTable">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '启动流程',
                icon: 'fa-brands:discord',
                onClick: handleProcessDefinitionStart.bind(null, record)
              }]"
          />
        </template>
      </template>
    </BasicTable>
  </PageWrapper>
</template>

<script lang="ts" name="Process">
  /**
   * 提供模板规范代码参考,请尽量保证编写代码风格跟模板规范代码一致
   * 采用vben-动态表格表单封装组件编写,不采用 setup 写法
   * Copyright © 2023-2023 <a href="https://godolphinx.org">海豚生态开源社区</a> All rights reserved.
   * author wangxiang4
   */
  import { defineComponent, onMounted, reactive } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { listProcessDef } from '/@/api/platform/workflow/controller/process';
  import { columns, searchFormSchema } from './process.data';
  import { PageWrapper } from '/@/components/Page';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { listToTree } from '/@/utils/helper/treeHelper';
  import { listProcessCategory } from '/@/api/platform/workflow/extension/controller/processCategory';
  import { getTaskDefinition } from '/@/api/platform/workflow/controller/task';
  import { useUserStore } from '/@/store/modules/user';
  import { formatToDateTime } from '/@/utils/dateUtil';
  import { useRouter } from 'vue-router';

  /** 类型规范统一声明定义区域 */
  interface TableState {
    treeData: TreeItem[];
  }

  export default defineComponent({
    name: 'WorkflowProcess',
    components: {
      PageWrapper,
      BasicTable,
      TableAction,
      BasicTree
    },
    setup() {
      /** 通用变量统一声明区域 */
      const state = reactive<TableState>({
        treeData: []
      });
      const userStore = useUserStore();
      const { push } = useRouter();
      const [registerTable, { reload, getForm }] = useTable({
        title: '流程定义列表',
        api: listProcessDef,
        rowKey: 'id',
        columns,
        formConfig: {
          compact: true,
          labelWidth: 100,
          schemas: searchFormSchema,
          autoSubmitOnEnter: true,
          showAdvancedButton: true,
          autoAdvancedLine: 3
        },
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        clickToRowSelect: false,
        showIndexColumn: false,
        actionColumn: {
          width: 240,
          title: '操作',
          dataIndex: 'action',
          fixed: false
        }
      });

      onMounted(async () => {
        state.treeData = listToTree(await listProcessCategory());
      });

      async function handleProcessDefinitionStart(record?: Recordable) {
        const tabTitle = `启动流程【${record?.name}】`;
        const formTitle = `${userStore.getUserInfo.nickName} 在 ${formatToDateTime()} 发起了 [${record?.name}]`;
        const data = await getTaskDefinition( { processDefId: record?.id });
        await push({
          path: '/workflow/task/taskForm',
          query: {
            _meta: 'y',
            processDefId: record?.id,
            processDefKey: record?.key,
            status: 'start',
            title: tabTitle,
            formTitle: formTitle,
            formType: data.formType,
            formKey: data.formKey
          }
        });
      }

      function handleSelect(selectedKeys: string[]) {
        getForm().setFieldsValue({
          categoryId: selectedKeys[0]
        });
        getForm().submit();
      }

      function handleRefreshTable() {
        reload();
      }

      return {
        state,
        registerTable,
        handleRefreshTable,
        handleProcessDefinitionStart,
        handleSelect,
      };
    }
  });
</script>
