<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <MenuTree ref="childRef" class="w-1/4 xl:w-1/5" @select="handleSelect" />
    <BasicTable
      class="w-3/4 xl:w-4/5"
      @register="registerTable"
      @fetch-success="onFetchSuccess"
      :searchInfo="searchInfo"
    >
      <template #toolbar>
        <PermissionBtn @btn-event="onBtnClicked" />
        <!-- <a-button type="primary" @click="handleAddForm">新增</a-button> -->
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'pmoduleId'">
          {{ findModuleName(pmoduleIds, record.pmoduleId) }}
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '编辑',
                onClick: () => {
                  handleEdit(record);
                },
              },
              {
                label: '删除',
                color: 'error',
                onClick: () => {
                  handleDelete(record);
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <FormModal
      @submitsuccess="submitsuccess"
      @register="registerModal"
      v-if="formModalVisible"
      @submit-reload="submitReload"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { reactive, nextTick, ref, onMounted } from 'vue';
  import { PermissionBtn } from '@/components/PermissionBtn/index';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { PageWrapper } from '@/components/Page';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useModal } from '@/components/Modal';
  import { TreeItem } from '@/components/Tree';
  import { cloneDeep } from 'lodash-es';
  // 子组件
  import MenuTree from './FormTree.vue';
  import FormModal from './FormModal.vue';
  // ts
  import { formModuleColumns, searchFormSchema } from './formModule.data';
  // api
  import { getMenuList } from '@/api/demo/system';
  import { fun_GetPageList, fun_DeleteForm } from '@/api/demo/formModule';
  import { usePermissionStore } from '@/store/modules/permission';
  const permissionStore = usePermissionStore();
  defineOptions({ name: 'FormModule' });
  const searchInfo = reactive<Recordable>({});
  const { createConfirm, createMessage } = useMessage();

  const [registerModal, { openModal }] = useModal();
  const [registerTable, { reload, expandAll, clearSelectedRowKeys }] = useTable({
    title: '发布列表',
    api: fun_GetPageList,
    columns: formModuleColumns,
    rowKey: 'id',
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    striped: false,
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    // 序号列
    showIndexColumn: true,
    actionColumn: {
      width: 120,
      title: '操作',
      dataIndex: 'action',
    },
    handleSearchInfoFn(info) {
      return info;
    },
  });

  const childRef = ref<any>();
  // 是否打开弹窗
  const formModalVisible = ref(true);
  // 上级
  const pmoduleIds = ref<TreeItem[]>([]);

  // searchInfo的树分支条件查询
  function handleSelect(ModuleId = '') {
    searchInfo.pmoduleid = ModuleId;
    clearSelectedRowKeys();
    reload();
  }

  // 表单列表-新增
  function handleAddForm() {
    formModalVisible.value = true;
    openModal(true, {
      isEdit: false,
    });
  }
  // 表单列表-编辑
  function handleEdit(record: Recordable) {
    formModalVisible.value = true;
    openModal(true, {
      isEdit: true,
      record: cloneDeep(record),
      formVerison: record.formVerison,
    });
  }
  // 表单列表-删除
  async function handleDelete(record: Recordable) {
    const query = { id: record.id };
    createConfirm({
      iconType: 'info',
      title: '删除',
      content: '确定要删除当前表单吗？',
      onOk: async () => {
        const data = await fun_DeleteForm(query);
        if (data) {
          createMessage.success('删除成功');
        } else {
          createMessage.warn('删除失败');
        }
        reload();
        await permissionStore.buildRoutesAction()
        permissionStore.setChangeMenu()
      },
    });
  }

  // 表单弹窗保存传回数据
  function submitsuccess() {
    reload();
    formModalVisible.value = false;
  }

  // 演示默认展开所有表项
  function onFetchSuccess() {
    nextTick(expandAll);
  }

  // 上级功能
  function findModuleName(modules, pmoduleId) {
    for (const module of modules) {
      if (module.id === pmoduleId) {
        return module.name;
      }
      if (Array.isArray(module.children) && module.children.length > 0) {
        const foundName = findModuleName(module.children, pmoduleId);
        if (foundName) {
          return foundName;
        }
      }
    }
    return '';
  }

  // 上级
  async function fetch() {
    pmoduleIds.value = await getMenuList();
  }

  // 新增、编辑-保存后，刷新
  async function submitReload() {
    clearSelectedRowKeys();
    reload();
    await permissionStore.buildRoutesAction()
    permissionStore.setChangeMenu()
  }

  function onBtnClicked(domId) {
    switch (domId) {
      case 'btnAdd':
        handleAddForm();
        break;
      default:
        break;
    }
  }

  onMounted(() => {
    fetch();
  });
</script>
