<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <FormSchemeTree
      ref="childRef"
      class="w-1/4 xl:w-1/5"
      @select="formSortSelect"
      @edit="formSortdrawerEdit"
    />
    <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="handleDownByData">导出</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'category'">
          {{ findModuleName(treeData, record.category) }}
        </template>
      </template>
    </BasicTable>
    <!-- 树的橱窗 -->
    <FormSchemeDrawer @register="registerDrawer" @success="handleSuccess" />
    <!-- 预览弹窗 -->
    <VFormPreview ref="eFormPreview" :formConfig="formConfig" />
    <!-- 表单列表新增和编辑弹窗 -->
    <!-- <TableModal @register="tableModal" /> -->
    <!-- 历史记录列表弹窗 -->
    <HistoryModal @register="historyModal" />
    <FormModal @submitsuccess="submitsuccess" @register="registerModal" v-if="formModalVisible" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { reactive, nextTick, ref, onMounted } from 'vue';
  import { cloneDeep } from 'lodash-es';

  import { BasicTable, useTable } from '@/components/Table';
  import { TreeItem } from '@/components/Tree';
  import { PageWrapper } from '@/components/Page';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useDrawer } from '@/components/Drawer';
  import PermissionBtn from '@/components/PermissionBtn/index.vue';
  import { useModal } from '@/components/Modal';
  import { downloadByData } from '@/utils/file/download';

  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 VFormPreview from '@/views/demo/form-design/components/VFormPreview/index.vue';

  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, getSelectRows, clearSelectedRowKeys }] = useTable({
    title: '表单列表',
    api: functionLoadFormPage,
    columns,
    rowKey: 'id',
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    isTreeTable: true,
    striped: false,
    // 序号列
    showIndexColumn: true,
    // 使用搜索表单
    useSearchForm: true,
    // 显示表格设置工具
    showTableSetting: true,
    bordered: true,
    rowSelection: {
      //多选框
      type: 'radio',
    },
    handleSearchInfoFn(info) {
      return info;
    },
  });

  // 表单列表新增和编辑弹窗
  // const [tableModal, { openModal: handleTableModal }] = useModal();
  const [registerModal, { openModal }] = useModal();
  const formModalVisible = ref(true);

  function handleAddForm() {
    formModalVisible.value = true;
    openModal(true, {});
  }
  function handleEdit() {
    formModalVisible.value = true;
    let rows = getSelectRows();
    if (rows.length == 0) {
      return createMessage.warn('请选择一个表单进行编辑');
    }
    openModal(true, rows[0]);
  }
  function submitsuccess() {
    reload();
    formModalVisible.value = false;
  }

  // 历史记录列表弹窗
  const [historyModal, { openModal: handleHistoryModal }] = useModal();

  const childRef = ref<any>();

  // 树分类-分类查询-连接表格
  function formSortSelect(category = '') {
    searchInfo.category = category;
    clearSelectedRowKeys();
    reload();
  }
  // // 树分类-抽屉-新增
  // function formSortdrawerCreate() {
  //   // record.type = '1';
  //   const record = null;
  //   openDrawer(true, {
  //     record,
  //     isUpdate: false,
  //   });
  // }
  // 树分类-抽屉-编辑
  async function formSortdrawerEdit(node: Recordable) {
    const record = node;
    openDrawer(true, {
      record,
      isUpdate: true,
    });
  }

  // 表单-删除
  async function handleDelete() {
    let rows = getSelectRows();
    if (rows.length == 0) {
      return createMessage.warn('请选择一个表单进行删除');
    }
    var query = {
      id: [rows[0].id],
    };

    createConfirm({
      iconType: 'info',
      title: '删除',
      content: '确定要删除当前表单吗？',
      onOk: async () => {
        await functionDeleteForm(query);
        reload();
      },
    });
  }
  // 表单-预览
  async function fromTablePreviewModal() {
    let rows = getSelectRows();
    if (rows.length == 0) {
      return createMessage.warn('请选择一个表单进行预览');
    }
    // 使用ID获取表单的info和scheme
    const preview = await functionGetForm({ id: rows[0].id });
    let scheme = JSON.parse(preview.scheme.scheme);
    formConfig.value.schemas = scheme.formInfo.schemas;
    eFormPreview.value.showModal(cloneDeep(formConfig.value));
  }
  // 表单历史记录-编辑
  async function formTableHistoryModal() {
    let rows = getSelectRows();
    if (rows.length == 0) {
      return createMessage.warn('请选择一个表单查看历史记录');
    }
    let id = rows[0].id;
    let schemeId = rows[0].schemeId;
    handleHistoryModal(true, { id, schemeId });
  }

  function handleSuccess() {
    childRef.value.fetch();
    clearSelectedRowKeys();
    reload();
  }

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

  // 导入
  // const uploadApi = null;

  // 导出
  async function handleDownByData() {
    let rows = getSelectRows();
    if (rows.length == 0) {
      return createMessage.warn('请选择一个表单进行预览');
    }
    // 所选表单的id
    var query = {
      id: rows[0].id,
    };
    const data = await functionGetForm(query);
    let downloadName = data.info.name;
    downloadByData(JSON.stringify(data), downloadName + '.json');
  }

  // 表单设计按钮
  function onBtnClicked(domId) {
    switch (domId) {
      case 'btnAdd':
        handleAddForm();
        break;
      case 'btnEdit':
        handleEdit();
        break;
      case 'btnDelete':
        handleDelete();
        break;
      case 'btnPreview':
        fromTablePreviewModal();
        break;
      case 'btnShowHistory':
        formTableHistoryModal();
        break;
      default:
        break;
    }
  }

  const treeData = ref<TreeItem[]>([]);

  // 分类
  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 '';
  }

  // 上级
  async function fetch() {
    treeData.value = await functionLoadFormSort();
  }

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