<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" />
        <!-- <Upload
          :multiple="multiple"
          helpText="只能导入json文件"
          :show-upload-list="false"
          :accept="['.json']"
          :maxSize="1"
          :maxNumber="1"
          :api="uploadApi"
        >
          <a-button type="primary">导入</a-button>
        </Upload> -->
        <a-button type="primary" @click="handleDownByData">导出</a-button>
      </template>
      <!-- <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'category'">
          <Select 
              v-model:value="record.category"
              :options="categoryOptioins"
            />
        </template>
      </template> -->
    </BasicTable>
    <!-- 树的橱窗 -->
    <FormSchemeDrawer @register="registerDrawer" @success="handleSuccess" />
    <!-- 预览弹窗 -->
    <PreviewModal @register="previewModal" />
    <!-- 表单列表新增和编辑弹窗 -->
    <!-- <TableModal @register="tableModal" /> -->
    <!-- 历史记录列表弹窗 -->
    <HistoryModal @register="historyModal" />
    <FormModal @submitsuccess="submitsuccess" @register="registerModal" v-if="formModalVisible" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { reactive, nextTick, ref } from 'vue';

  import { BasicTable, useTable } from '@/components/Table';
  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 { Upload } from 'ant-design-vue';
  import PreviewModal from './modal/PreviewModal.vue';
  // import TableModal from './modal/PageStepTableModal.vue';
  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 { uploadApi } from '/@/api/sys/upload';

  import { columns, searchFormSchema } from './formScheme.data';
  import { functionLoadFormPage, functionGetForm, functionDeleteForm } from '@/api/demo/formScheme';

  const { createConfirm, createMessage } = useMessage();

  const searchInfo = reactive<Recordable>({});
  // 抽屉
  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 [previewModal, { openModal: handlePreviewModal }] = useModal();
  // 表单列表新增和编辑弹窗
  // 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('请选择一个表单进行编辑');
    }
    // var query = {
    //   id: rows[0].id,
    // };
    // const record = await functionGetForm(query);
    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,
    });
  }

  // // 表单-新增
  // function formTableModalCreate() {
  //   const record = null;
  //   handleTableModal(true, { record, isUpdate: false });
  // }
  // // 表单-编辑
  // async function formTableModalEdit() {
  //   let rows = getSelectRows();
  //   if (rows.length == 0) {
  //     return createMessage.warn('请选择一个表单进行编辑');
  //   }
  //   var query = {
  //     id: rows[0].id,
  //   };
  //   const record = await functionGetForm(query);
  //   handleTableModal(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
    var query = {
      id: rows[0].id,
    };
    // 使用ID获取表单的info和scheme
    const data = await functionGetForm(query);
    const scheme: string = data.scheme.scheme;
    handlePreviewModal(true, {
      scheme,
    });
  }
  // 表单历史记录-编辑
  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':
        // formTableModalCreate();
        handleAddForm();
        break;
      case 'btnEdit':
        // formTableModalEdit();
        handleEdit();
        break;
      case 'btnDelete':
        handleDelete();
        break;
      case 'btnPreview':
        fromTablePreviewModal();
        break;
      case 'btnShowHistory':
        formTableHistoryModal();
        break;
      default:
        break;
    }
  }
</script>
