<template>
  <PageWrapper
    contentClass="flex"
    contentFullHeight
    fixedHeight
    dense
  >
    <BasicTree class="m-4 mr-0 overflow-hidden bg-white w-1/4 xl:w-1/5"
               search
               :clickRowToExpand="false"
               :treeData="state.treeData"
               :fieldNames="{ key: 'id', title: 'name' }"
               @select="handleSelect"
    >
      <template #toolbarRight>
        <a-button
          type="primary"
          shape="circle"
          size="small"
          @click="handleFormCategoryAdd()"
        >
          <PlusOutlined/>
        </a-button>
      </template>
      <template #title="data">
        <span class="custom-tree-node">
          <span>{{ data.name }}</span>
          <span>
            <a-button type="link"
                      size="small"
                      @click="handleFormCategoryAdd(data)"
            >
              <PlusOutlined/>
            </a-button>
            <a-button type="link"
                      size="small"
                      @click="handleFormCategoryEdit(data)"
            >
              <FormOutlined/>
            </a-button>
            <a-button type="link"
                      size="small"
                      @click="handleFormCategoryDel(data)"
            >
              <DeleteOutlined/>
            </a-button>
          </span>
        </span>
      </template>
    </BasicTree>
    <BasicTable
      class="w-3/4 xl:w-4/5"
      @register="registerTable"
      @selection-change="handleSelectionChange"
    >
      <template #tableTitle>
        <a-button
          type="primary"
          @click="handleAdd()"
        >新增</a-button>
        <a-button
          type="primary"
          :disabled="state.single"
          @click="handleEdit()"
        >修改</a-button>
        <a-button
          type="primary"
          :disabled="state.multiple"
          @click="handleDel()"
        >删除</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '设计',
                icon: 'fa-solid:fill-drip',
                onClick: handleWorkFlowFormDesign.bind(null, record)
              },
              {
                label: '版本管理',
                icon: 'fa6-solid:code-compare',
                onClick: handleWorkFlowVersion.bind(null, record),
              }]"
            :dropDownActions="[
              {
                label: '修改',
                icon: 'fa6-regular:pen-to-square',
                color: 'error',
                onClick: handleEdit.bind(null, record)
              },
              {
                label: '删除',
                icon: 'ant-design:delete-outlined',
                color: 'error',
                onClick: handleDel.bind(null, record),
              }]"
          />
        </template>
      </template>
    </BasicTable>
    <FormModal @register="registerModal" @success="handleRefreshTable"/>
    <FormCategoryModal @register="registerFormCategoryModal" @success="handleRefreshTree"/>
    <WorkflowFormDesign @register="registerWorkflowFormModal" @success="handleRefreshTable"/>
  </PageWrapper>
</template>

<script lang="ts">
  import { defineComponent, reactive, toRaw, onMounted } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { listFormDefinition, delFormDefinition, } from '/@/api/platform/workflow/extension/controller/formDefinition';
  import { PageWrapper } from '/@/components/Page';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { useModal } from '/@/components/Modal';
  import FormModal from './FormModal.vue';
  import FormCategoryModal from './FormCategoryModal.vue';
  import WorkflowFormDesign from './helper/WorkflowFormDesign.vue';
  import { columns, searchFormSchema } from './form.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { listToTree } from '/@/utils/helper/treeHelper';
  import { listFormCategory, delFormCategory } from '/@/api/platform/workflow/extension/controller/formCategory';
  import { PlusOutlined, FormOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import { useRouter } from 'vue-router';

  /** 类型规范统一声明定义区域 */
  interface TableState {
    ids: string[];
    single: boolean;
    multiple: boolean;
    searchInfo: Recordable;
    treeData: TreeItem[];
  }

  export default defineComponent({
    name: 'WorkFlowForm',
    components: {
      BasicTable,
      PageWrapper,
      BasicTree,
      TableAction,
      FormModal,
      PlusOutlined,
      FormOutlined,
      DeleteOutlined,
      WorkflowFormDesign,
      FormCategoryModal
    },
    setup() {

      /** 通用变量统一声明区域 */
      const state = reactive<TableState>({
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 搜索信息
        searchInfo: {},
        treeData: []
      });
      const { push } = useRouter();
      const { createConfirm, createMessage } = useMessage();
      const [registerModal, { openModal }] = useModal();
      const [registerFormCategoryModal, { openModal: openFormCategoryModal }] = useModal();
      const [registerWorkflowFormModal , { openModal: openWorkflowFormModal }] = useModal();
      const [registerTable, { reload, clearSelectedRowKeys, getForm }] = useTable({
        title: '流程表单列表',
        api: listFormDefinition,
        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,
        searchInfo: state.searchInfo,
        actionColumn: {
          width: 220,
          title: '操作',
          dataIndex: 'action',
          fixed: false
        },
        handleSearchInfoFn: () => clearSelectedRowKeys()
      });

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

      /** 处理多选框选中数据 */
      function handleSelectionChange(selection?: Recordable) {
        const rowSelection = toRaw(selection?.keys) || [];
        state.ids = rowSelection;
        state.single = rowSelection.length != 1;
        state.multiple = !rowSelection.length;
      }

      /** 新增按钮操作,行内新增与工具栏局域新增通用 */
      function handleAdd(record?: Recordable) {
        openModal(true, { _tag: 'add', record });
      }

      /** 编辑按钮操作,行内编辑 */
      function handleEdit(record?: Recordable) {
        record = record || { id: toRaw(state.ids) };
        openModal(true, { _tag: 'edit', record });
      }

      /** 删除按钮操作,行内删除 */
      async function handleDel(record?: Recordable) {
        const ids = record?.id || toRaw(state.ids);
        createConfirm({
          iconType: 'warning',
          title: '警告',
          content: `是否确认删除表单编号为${ids}吗?`,
          onOk: async () => {
            await delFormDefinition(ids);
            createMessage.success('删除成功!');
            handleRefreshTable();
          }
        });
      }

      /** 处理添加表单分类 */
      function handleFormCategoryAdd(record?: Recordable) {
        openFormCategoryModal(true,{ _tag: 'add', record });
      }

      /** 处理编辑表单分类 */
      function handleFormCategoryEdit(record?: Recordable) {
        openFormCategoryModal(true, { _tag: 'edit', record });
      }

      /** 处理表单分类删除 */
      async function handleFormCategoryDel(record?: Recordable) {
        const id = record?.id;
        createConfirm({
          iconType: 'warning',
          title: '警告',
          content: `是否确认删除表单分类编号为${id}吗?`,
          onOk: async () => {
            await delFormCategory(id);
            createMessage.success('删除成功!');
            await handleRefreshTree();
          }
        });
      }

      /** 处理表格刷新 */
      function handleRefreshTable() {
        clearSelectedRowKeys();
        reload();
      }

      /** 处理树形列表刷新 */
      async function handleRefreshTree() {
        state.treeData = listToTree(await listFormCategory());
        await getForm().updateSchema({
          field: 'categoryId',
          componentProps: {
            treeData: state.treeData
          }
        });
      }

      /** 处理工作流表单设计 */
      function handleWorkFlowFormDesign(row: Recordable) {
        const record = row.formDefinitionJson || {};
        openWorkflowFormModal(true, { _tag: 'edit', record });
      }

      /** 处理打开工作流版本管理 */
      function handleWorkFlowVersion(row: Recordable) {
        push({ path : `/workflow/formDefinitionJson/${row.id}`, query: { _meta: 'y', title: `流程表单【${row.name}】` }});
      }

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

      return {
        state,
        registerTable,
        registerModal,
        registerWorkflowFormModal,
        handleAdd,
        handleEdit,
        handleDel,
        handleSelectionChange,
        handleRefreshTable,
        handleSelect,
        handleWorkFlowFormDesign,
        handleWorkFlowVersion,
        registerFormCategoryModal,
        handleRefreshTree,
        handleFormCategoryAdd,
        handleFormCategoryEdit,
        handleFormCategoryDel
      };
    }
  });
</script>
<style lang="less" scoped>

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

:deep(.ant-tree .ant-tree-node-content-wrapper .ant-tree-title .ant-btn) {
  display: none;
}

:deep(.ant-tree .ant-tree-node-content-wrapper .ant-tree-title:hover .ant-btn) {
  padding: 0px 5px;
  display: unset;
}
</style>
