<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <FormSchemeTree
      ref="childRef"
      class="w-1/4 xl:w-1/5"
      @select="formSortSelect"
      @add="drawerAdd"
      @edit="drawerEdit"
    />
    <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 === 'category'">
          {{ findModuleName(treeData, record.category) }}
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '编辑',
                onClick: () => {
                  handleEdit(record);
                },
              },
              {
                label: '删除',
                color: 'error',
                onClick: () => {
                  handleDelete(record);
                },
              },
              {
                label: '预览',
                onClick: () => {
                  handlePreview(record);
                },
              },
              {
                label: '历史记录',
                onClick: () => {
                  handleHistory(record);
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <!-- 树的橱窗 -->
    <FormSchemeDrawer @register="registerDrawer" @success="handleSuccess" />
    <!-- 预览弹窗 -->
    <VFormPreview ref="eFormPreview" :formConfig="formConfig" />
    <!-- 历史记录列表弹窗 -->
    <HistoryModal @register="historyModal" :closeFunc="handleCloseFunc" />
    <FormModal @submitsuccess="submitsuccess" @register="registerModal" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { reactive, nextTick, ref, onMounted } from 'vue';

  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { TreeItem } from '@/components/Tree';
  import { PageWrapper } from '@/components/Page';
  import { useDrawer } from '@/components/Drawer';
  import { useModal } from '@/components/Modal';
  import { useMessage } from '@/hooks/web/useMessage';
  // 子组件
  import HistoryModal from './modal/HistoryModal.vue';
  import FormSchemeDrawer from './FormSchemeDrawer.vue';
  import FormSchemeTree from './FormSchemeTree.vue';
  import FormModal from '@/views/demo/onlineform/formdesign/FormModal.vue';
  // 预览
  import { IFormConfig } from '@/views/demo/form-design/typings/v-form-component';
  import { IToolbarMethods } from '@/views/demo/form-design/typings/form-type';
  import { cloneDeep } from 'lodash-es';
  import VFormPreview from '@/views/demo/form-design/components/VFormPreview/index.vue';
  // api
  import { columns, searchFormSchema } from './formScheme.data';
  import {
    functionLoadFormSort,
    functionLoadFormPage,
    functionGetForm,
    functionDeleteForm,
  } from '@/api/demo/formScheme';

  const { createConfirm, createMessage } = useMessage();

  const searchInfo = reactive<Recordable>({});

  // 预览
  const eFormPreview = ref<null | IToolbarMethods>(null);
  // 预览endregion
  const formConfig = ref<IFormConfig>({
    schemas: [],
    layout: 'horizontal',
    labelLayout: 'flex',
    labelWidth: 100,
    labelCol: {},
    wrapperCol: {},
    currentItem: {
      component: '',
      componentProps: {},
    },
    activeKey: 1,
  });
  // 抽屉
  const [registerDrawer, { openDrawer }] = useDrawer();
  // 列表
  const [registerTable, { reload, expandAll, clearSelectedRowKeys }] = useTable({
    title: '表单列表',
    api: functionLoadFormPage,
    columns,
    rowKey: 'id',
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    striped: false,
    // 序号列
    showIndexColumn: true,
    // 使用搜索表单
    useSearchForm: true,
    // 显示表格设置工具
    showTableSetting: true,
    bordered: true,
    actionColumn: {
      width: 200,
      title: '操作',
      dataIndex: 'action',
    },
    handleSearchInfoFn(info) {
      return info;
    },
  });

  // 表单列表新增和编辑弹窗
  const [registerModal, { openModal }] = useModal();
  // 历史记录列表弹窗
  const [historyModal, { openModal: handleHistoryModal, closeModal }] = useModal();

  // 树ref
  const childRef = ref<any>();

  // 树分类-分类查询-连接表格
  function formSortSelect(category = '') {
    searchInfo.category = category;
    clearSelectedRowKeys();
    reload();
  }
  // 树分类-抽屉-新增
  async function drawerAdd() {
    openDrawer(true, {
      isUpdate: false,
    });
  }
  // 树分类-抽屉-编辑
  async function drawerEdit(node: Recordable) {
    const record = node;
    openDrawer(true, {
      record,
      isUpdate: true,
    });
  }
  // 树的橱窗-提交
  function handleSuccess() {
    childRef.value.fetch();
    clearSelectedRowKeys();
    reload();
  }

  // 表单列表-新增
  function handleAddForm() {
    openModal(true, {});
  }
  // 表单列表-编辑
  function handleEdit(record) {
    openModal(true, record);
  }
  // 表单列表-保存后
  function submitsuccess() {
    reload();
  }
  // 表单列表-删除
  async function handleDelete(record) {
    var query = {
      id: [record.id],
    };
    createConfirm({
      iconType: 'info',
      title: '删除',
      content: '确定要删除当前表单吗？',
      onOk: async () => {
        let result = await functionDeleteForm(query);
        if (result) {
          createMessage.success('表单删除成功!');
        } else {
          createMessage.error('表单删除失败!');
        }
        reload();
      },
    });
  }
  // 表单列表-预览
  async function handlePreview(record) {
    // 使用ID获取表单的info和scheme
    const preview = await functionGetForm({ id: record.id });
    let scheme = JSON.parse(preview.scheme?.scheme);
    if (!scheme) {
      createMessage.error('预览失败');
      return;
    }
    formConfig.value.schemas = scheme.formInfo.schemas;
    eFormPreview.value.showModal(cloneDeep(formConfig.value));
  }
  // 表单列表-历史记录
  async function handleHistory(record) {
    let id = record.id;
    let schemeId = record.schemeId;
    handleHistoryModal(true, { id, schemeId });
  }

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

  // 分类
  function findModuleName(modules, pmoduleId) {
    for (const module of modules) {
      if (module.itemValue === pmoduleId) {
        return module.itemName;
      }
      if (Array.isArray(module.children) && module.children.length > 0) {
        const foundName = findModuleName(module.children, pmoduleId);
        if (foundName) {
          return foundName;
        }
      }
    }
    return '';
  }

  // 历史弹窗点击关闭
  function handleCloseFunc() {
    closeModal();
    clearSelectedRowKeys();
    reload();
    return true;
  }

  // 上级
  const treeData = ref<TreeItem[]>([]);
  async function fetch() {
    treeData.value = await functionLoadFormSort();
  }

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