<template>
  <BasicModal
    @register="registerModal"
    @ok="modalSubmit"
    title="选择表单"
    width="60%"
    height="650"
    useWrapper="false"
  >
    <div>
      <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
        <div class="w-1/4 m-2 mr-0 overflow-hidden bg-white xl:w-1/5">
          <BasicTree
            ref="asyncExpandTreeRef"
            title="表单分类"
            :treeData="treeData"
            :defaultExpandAll="true"
            :fieldNames="{ key: 'itemValue', title: 'title' }"
            @select="handleSelect"
          />
        </div>
        <div class="m-2 mr-0 overflow-hidden bg-white l-rblock">
          <BasicTable @register="registerTable" :searchInfo="searchInfo">
            <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: () => {
                        previewModal(record, eFormPreview);
                      },
                    },
                  ]"
                />
              </template>
            </template>
          </BasicTable>
        </div>
      </PageWrapper>
    </div>
    <VFormPreview ref="eFormPreview" :formConfig="formConfig" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { onMounted, ref, defineEmits, reactive, nextTick, unref } from 'vue';
  import { cloneDeep } from 'lodash-es';

  import { PageWrapper } from '@/components/Page';
  import { BasicModal, useModal } from '@/components/Modal';
  import { BasicTree, TreeItem, TreeActionType } from '@/components/Tree';
  import { BasicTable, useTable, TableAction } from '@/components/Table';

  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 {
    functionLoadFormSort,
    functionLoadFormPage,
    functionGetPreviewForm,
  } from '@/api/demo/formScheme';
  import { modalColumns, searchFormSchema_Modal } from './formModule.data';
  import { cardNestStructure } from '@/views/demo/onlineform/util.ts';

  const emit = defineEmits(['get-scheme-row']);

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

  // 子组件实例
  const eFormPreview = ref<null | IToolbarMethods>(null);

  // 列表
  const [registerTable, { getSelectRows, reload, clearSelectedRowKeys }] = useTable({
    api: functionLoadFormPage,
    columns: modalColumns,
    rowKey: 'id',
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema_Modal,
    },
    // 使用搜索表单
    useSearchForm: true,
    canResize: false,
    striped: false,
    // 显示表格设置工具
    showTableSetting: false,
    // 是否显示表格边框
    bordered: true,
    // 序号列
    showIndexColumn: true,
    tableSetting: { fullScreen: true },
    isCanResizeParent: true,
    rowSelection: {
      //多选框
      type: 'radio',
    },
    handleSearchInfoFn(info) {
      return info;
    },
    beforeFetch: (data) => {
      // 接口请求前 参数处理
      var temp = {
        limit: data.limit,
        page: data.page,
        isEnabled: 1,
      };
      return temp;
    },
  });

  // 树分类获取
  const treeData = ref<TreeItem[]>([]);
  const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);
  async function fetch() {
    treeData.value = (await functionLoadFormSort()) as unknown as TreeItem[];
    treeData.value = treeData.value.map((item) => ({
      ...item,
      title: item.itemName,
    }));
    // 展开全部
    nextTick(() => {
      unref(asyncExpandTreeRef)?.expandAll(true);
    });
  }
  // 树分类-分类查询-连接表格
  function handleSelect(category = '') {
    searchInfo.category = category[0];
    clearSelectedRowKeys();
    reload();
  }

  // 表单
  const [registerModal, { closeModal }] = useModal();
  // 表单提交
  function modalSubmit() {
    let rows = getSelectRows();
    emit('get-scheme-row', rows[0]);
    closeModal();
    clearSelectedRowKeys();
    reload();
  }

  // 预览-endregion
  const formConfig = ref<IFormConfig>({
    // 表单配置
    schemas: [],
    layout: 'horizontal',
    labelLayout: 'flex',
    labelWidth: 100,
    labelCol: {},
    wrapperCol: {},
    currentItem: {
      component: '',
      componentProps: {},
    },
    activeKey: 1,
  });
  // 预览
  async function previewModal(record, Modal: IToolbarMethods) {
    let query: any = { keyValue: record.schemeId };
    const preview: any = await functionGetPreviewForm(query);
    let scheme = JSON.parse(preview.scheme);
    console.log('scheme1111', scheme);
    // if (scheme.formInfo.tabList && scheme.formInfo.tabList.length > 1) {
    //   const arr: any = [];
    //   scheme.formInfo.tabList.forEach((item, index) => {
    //     const rowArr: any = [];
    //     item.schemas.forEach((col) => {
    //       if (col.ptype !== 'gridlayout') {
    //         rowArr.push(col);
    //       }
    //     });
    //     arr.push({
    //       label: item.text,
    //       value: index + 1,
    //       children: rowArr,
    //     });
    //   });
    //   scheme.formInfo.schemas = [
    //     {
    //       component: 'Tabs',
    //       label: '选项卡',
    //       colProps: {
    //         span: 24,
    //       },
    //       field: 'Tabs',
    //       componentProps: {
    //         options: arr,
    //       },
    //       itemProps: {
    //         labelCol: {},
    //         wrapperCol: {},
    //       },
    //     },
    //   ];
    // }
    // if (scheme.formInfo.tabList && scheme.formInfo.tabList.length == 1) {
    //   const arr: any = [];
    //   scheme.formInfo.tabList[0].schemas.forEach((item) => {
    //     if (item.ptype !== 'gridlayout') {
    //       arr.push(item);
    //     }
    //   });
    //   scheme.formInfo.schemas = arr;
    // }
    // delete scheme.formInfo.tabList;
    // formConfig.value.schemas = scheme.formInfo.schemas;
    scheme.formInfo.tabList = cardNestStructure(scheme.formInfo.tabList);
    if (scheme.formInfo.tabList.length > 1) {
      let data = [
        {
          component: 'Tabs',
          componentProps: {
            options: [],
          },
        },
      ];
      data[0].componentProps.options = scheme.formInfo.tabList.map((item, index) => {
        return {
          label: item.text,
          value: index,
          children: item.schemas,
        };
      });
      formConfig.value.schemas = data;
    } else {
      formConfig.value.schemas = scheme.formInfo.tabList[0].schemas;
    }
    Modal?.showModal(cloneDeep(formConfig.value));
  }

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

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