<template>
  <ResizePageWrapper dense contentFullHeight fixed-height contentClass="flex">
    <template #resizeLeft>
      <BasicTree
        :title="t('表单分类')"
        :clickRowToExpand="true"
        :treeData="treeData"
        :selectedKeys="[selectId]"
        :fieldNames="{ key: 'id', title: 'name' }"
        @select="handleSelect"
      />
    </template>
    <template #resizeRight>
      <BasicTable @register="registerTable">
        <template #toolbar>
          <a-button
            type="primary"
            danger
            @click="handleDelete"
            v-auth="'form-design:batchDelete'"
            >{{ t('批量删除') }}</a-button
          >
          <a-button @click="handleCategory" type="primary" v-auth="'form-design:classifyMGT'">{{
            t('分类管理')
          }}</a-button>
          <a-button @click="handleImport" type="primary" v-auth="'form-design:import'">{{
            t('导入')
          }}</a-button>
          <a-button @click="handleExport" type="primary" v-auth="'form-design:export'">{{
            t('导出')
          }}</a-button>
          <a-button type="primary" @click="handleCreate" v-auth="'form-design:add'">
            <template #icon><PlusOutlined /></template>
            {{ t('新增') }}
          </a-button>
        </template>
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                auth: 'form-design:previewForm',
                label: '预览表单',
                onClick: previewForm.bind(null, record),
                ifShow: record.status !== 0,
              },
              {
                auth: 'form-design:history',
                label: '历史记录',
                onClick: queryHistory.bind(null, record),
                ifShow: record.status !== 0,
              },
              {
                auth: 'form-design:generatedCode',
                label: '生成代码',
                onClick: handleCodeGenerator.bind(null, record),
                ifShow: record.status !== 0,
              },
              {
                auth: 'form-design:copy',
                label: '复制',
                onClick: handleCopy.bind(null, record),
                ifShow: record.status !== 0,
              },
              { label: '编辑', auth: 'form-design:edit', onClick: handleEdit.bind(null, record) },
              {
                label: '删除',
                auth: 'form-design:delete',
                color: 'error',
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </BasicTable>
    </template>
    <DesignModal @register="registerDesignModal" @success="handleSuccess" />
    <HistoryModal @register="registerHistoryModal" />
    <CategoryModal title="表单" :dicId="dicId" @register="registerCategoryModal" @success="fetch" />
    <PreviewModal @register="registerPreviewModal" />
    <DataFirstModal
      v-if="state.isShowDataFirst"
      @register="registerDataFirst"
      @success="handleSuccess"
      @close="handleClose('isShowDataFirst')"
    />
    <CodeFirstModal
      v-if="state.isShowCodeFirst"
      @register="registerCodeFirst"
      @success="handleSuccess"
      @close="handleClose('isShowCodeFirst')"
    />
    <SimpleTemplateModal
      v-if="state.isShowSimpleTemplate"
      @register="registerSimpleTemplate"
      @success="handleSuccess"
      @close="handleClose('isShowSimpleTemplate')"
    />
    <NoTableModal
      v-if="state.isShowNoTable"
      @register="registerNoTable"
      @success="handleSuccess"
      @close="handleClose('isShowNoTable')"
    />
    <CodeGeneratorModal
      v-if="state.isShowCodeGenerator"
      @register="registerCodeGenerator"
      @close="handleClose('isShowCodeGenerator')"
    />
    <ImportModal
      @register="registerImportModal"
      importUrl="/form/template/import"
      accept=".json,.txt"
      @success="reload"
    />
  </ResizePageWrapper>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import {
    getFormTemplatePage,
    deleteFormTemplate,
    // updateFormTemplateStatus,
    getFormTemplate,
    addDataFirstFormTemplate,
    addCodeFirstFormTemplate,
    exportFormDesign,
  } from '/@/api/form/design';
  import { ResizePageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import DesignModal from './components/DesignModal.vue';
  import HistoryModal from './components/HistoryModal.vue';
  import { CategoryModal } from '/@/components/CategoryModal';
  import PreviewModal from './components/PreviewModal.vue';
  import DataFirstModal from './components/components/DataFirstModal.vue';
  import CodeFirstModal from './components/components/CodeFirstModal.vue';
  import SimpleTemplateModal from './components/components/SimpleTemplateModal.vue';
  import NoTableModal from './components/components/NoTableModal.vue';
  import CodeGeneratorModal from './components/CodeGeneratorModal.vue';
  import { h, onMounted, ref, createVNode, reactive } from 'vue';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { getDicDetailList } from '/@/api/system/dic';
  import { FormTypeEnum } from '/@/enums/formtypeEnum';
  import { Switch, Modal, Tag } from 'ant-design-vue';
  import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { downloadByData } from '/@/utils/file/download';
  import { ImportModal } from '/@/components/Import';
  import { random } from 'lodash-es';

  const { t } = useI18n();
  const treeData = ref<TreeItem[]>([]);
  const selectId = ref('');
  const selectedKeys = ref<string[]>([]);
  const dicId = '1419276800524424444';
  const formJson = ref();

  const state = reactive({
    isShowDataFirst: true,
    isShowCodeFirst: true,
    isShowSimpleTemplate: true,
    isShowCodeGenerator: true,
    isShowNoTable: true,
  });
  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: '',
      component: 'Input',
      componentProps: {
        placeholder: t('请输入关键字'),
      },
    },
  ];

  const columns: BasicColumn[] = [
    {
      dataIndex: 'name',
      title: t('名称'),
      align: 'center',
      resizable: true,
    },

    {
      dataIndex: 'categoryName',
      title: t('分类'),
      align: 'center',
      resizable: true,
      width: 120,
    },
    {
      dataIndex: 'enabledMark',
      title: t('状态'),
      resizable: true,
      width: 100,
      align: 'center',
      customRender: ({ record }) => {
        if (!Reflect.has(record, 'pendingStatus')) {
          record.pendingStatus = false;
        }
        return h(Switch, {
          checked: record.enabledMark === 1,
          checkedChildren: t('已启用'),
          unCheckedChildren: t('已禁用'),
          loading: record.pendingStatus,
          disabled: record.status === 0,
          // onChange(checked: boolean) {
          //   record.pendingStatus = true;
          //   const newStatus = checked ? 1 : 0;
          //   const { createMessage } = useMessage();
          //   updateFormTemplateStatus(record.id, newStatus)
          //     .then(() => {
          //       record.enabledMark = newStatus;
          //       createMessage.success(t('已成功修改状态'));
          //     })
          //     .catch(() => {
          //       createMessage.error(t('修改状态失败'));
          //     })
          //     .finally(() => {
          //       record.pendingStatus = false;
          //     });
          // },
          disabled: true,
        });
      },
    },
    {
      dataIndex: 'status',
      title: t('状态'),
      width: 120,
      resizable: true,
      customRender: ({ record }) => {
        const color = record.status == 0 ? 'yellow' : 'blue';
        const text = record.status == 0 ? '草稿' : '正常';
        return h(Tag, { color: color }, () => text);
      },
    },
    {
      dataIndex: 'createUserName',
      title: t('创建人'),
      align: 'center',
      resizable: true,
      width: 120,
    },
    {
      dataIndex: 'createDate',
      title: t('创建时间'),
      align: 'center',
      resizable: true,
    },
    {
      dataIndex: 'remark',
      align: 'center',
      title: t('备注'),
      resizable: true,
    },
  ];
  const { notification } = useMessage();
  const { hasPermission } = usePermission();

  const [registerDesignModal, { openModal: openDesignModal }] = useModal();
  const [registerHistoryModal, { openModal: openHistoryModal }] = useModal();
  const [registerCategoryModal, { openModal: openCategoryModal }] = useModal();
  const [registerPreviewModal, { openModal: openPreviewModal }] = useModal();
  const [registerDataFirst, { openModal: openDataFirstModal }] = useModal();
  const [registerCodeFirst, { openModal: openCodeFirstModal }] = useModal();
  const [registerSimpleTemplate, { openModal: openSimpleTemplateModal }] = useModal();
  const [registerCodeGenerator, { openModal: openCodeGeneratorModal }] = useModal();
  const [registerImportModal, { openModal: openImportModal }] = useModal();
  const [registerNoTable, { openModal: openNoTableModal }] = useModal();

  const formConfig = {
    rowProps: {
      gutter: 16,
    },
    schemas: searchFormSchema,
    fieldMapToTime: [],
    showResetButton: false,
  };
  const [registerTable, { reload, setSelectedRowKeys, getSelectRows }] = useTable({
    api: getFormTemplatePage,
    rowKey: 'id',
    title: '表单列表',
    columns,
    formConfig,
    beforeFetch: (params) => {
      //发送请求默认新增  左边树结构所选id
      return { ...params, category: selectId.value, type: FormTypeEnum.CUSTOM_FORM };
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    actionColumn: {
      width: 350,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    rowSelection: {
      onChange: onSelectChange,
    },
    customRow,
    tableSetting: {
      size: false,
    },
  });

  function onSelectChange(rowKeys: string[]) {
    selectedKeys.value = rowKeys;
    setSelectedRowKeys(selectedKeys.value);
  }

  function customRow(record: Recordable) {
    return {
      onClick: () => {
        let selectedRowKeys = [...selectedKeys.value];
        if (selectedRowKeys.indexOf(record.id) >= 0) {
          let index = selectedRowKeys.indexOf(record.id);
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys.push(record.id);
        }
        selectedKeys.value = selectedRowKeys;
        setSelectedRowKeys(selectedRowKeys);
      },
      ondblclick: () => {
        if (hasPermission('form-design:edit')) {
          handleEdit(record);
        }
      },
    };
  }

  function handleCreate() {
    openDesignModal(true, {
      title: t('添加表单'),
    });
  }

  function handleEdit(record: Recordable) {
    const info = {
      id: record.id,
      isUpdate: true,
      isDraft: record.status === 0,
    };
    switch (record.formDesignType) {
      case 0:
        openDataFirstModal(true, info);
        break;
      case 1:
        openCodeFirstModal(true, info);
        break;
      case 2:
        openSimpleTemplateModal(true, info);
        break;
      case 3:
        openNoTableModal(true, info);
        break;
    }
  }

  async function handleCopy(record: Recordable) {
    const templateJson = await getFormTemplate(record.id);
    formJson.value = JSON.parse(templateJson.formJson);
    if (record.formDesignType !== 0) {
      delete formJson.value.tableConfigs;
      changeTableName();
    }
    const params = {
      ...templateJson,
      formJson: formJson.value,
    };
    if (record.formDesignType === 0) {
      await addDataFirstFormTemplate(params);
    } else {
      await addCodeFirstFormTemplate(params);
    }

    notification.success({
      message: t('提示'),
      description: t('复制成功'),
    });
    reload();
  }

  function changeTableName() {
    const tableName = 'table_' + random(10000, 99999);
    formJson.value.tableStructureConfigs?.map((item) => {
      item.tableName = item.isMain ? tableName : `${tableName}_child_${random(1000, 9999)}`;
      changeComponentName(item);
    });
  }

  function changeComponentName(record) {
    record.tableFieldConfigs.forEach((item) => {
      changeComponentInfo(
        formJson.value.formJson.list,
        item.key,
        record.tableName,
        record.key,
        record,
        formJson.value.formJson.hiddenComponent,
      );
    });
  }

  function changeComponentInfo(list, fieldKey, name, tableKey, record, hiddenComponent?) {
    if (hiddenComponent?.length) {
      hiddenComponent?.map((component: any) => {
        if (component.key === fieldKey) {
          component.bindTable = name;
        }
      });
    }
    list?.map((component: any) => {
      if (['form', 'one-for-one', 'sun-form'].includes(component.type)) {
        if (component.key === tableKey) {
          component.bindTable = name;
          if (component.children.length) {
            component.children.map((subComponent: any) => {
              if (subComponent.type === 'sun-form') {
                subComponent.parentTable = name;
              } else {
                subComponent.bindTable = name;
              }
              if (['tab', 'grid', 'card'].includes(subComponent.type)) {
                for (const subChild of subComponent.layout!) {
                  changeComponentInfo(subChild.list, fieldKey, name, tableKey, record);
                }
              } else if (subComponent.type == 'table-layout') {
                for (const child of subComponent.layout!) {
                  for (const el of child.list!) {
                    changeComponentInfo(el.children, fieldKey, name, tableKey, record);
                  }
                }
              }
            });
          }
        } else {
          if (component.children.length) {
            component.children.map((subComponent: any) => {
              if (subComponent.type === 'sun-form') {
                if (subComponent.key === tableKey) {
                  subComponent.bindTable = name;
                }
                changeComponentInfo(subComponent.children, fieldKey, name, tableKey, record);
              } else if (['tab', 'grid', 'card'].includes(subComponent.type)) {
                for (const subChild of subComponent.layout!) {
                  changeComponentInfo(subChild.list, fieldKey, name, tableKey, record);
                }
              } else if (subComponent.type == 'table-layout') {
                for (const child of subComponent.layout!) {
                  for (const el of child.list!) {
                    changeComponentInfo(el.children, fieldKey, name, tableKey, record);
                  }
                }
              }
            });
          }
        }
      } else if (['tab', 'grid', 'card'].includes(component.type)) {
        component.bindTable = name;
        for (const child of component.layout!) {
          changeComponentInfo(child.list, fieldKey, name, tableKey, record);
        }
      } else if (component.type == 'table-layout') {
        component.bindTable = name;
        for (const child of component.layout!) {
          for (const el of child.list!) {
            changeComponentInfo(el.children, fieldKey, name, tableKey, record);
          }
        }
      } else if (component.key === fieldKey) {
        if (['time-range', 'date-range'].includes(component.type)) {
          component.bindTable = name;
        } else {
          component.bindTable = name;
        }
      }
    });
  }

  function handleDelete(record: Recordable = {}) {
    const ids = record.id ? [record.id] : selectedKeys.value;
    if (!ids.length) {
      noticeInfo('删除');
      return;
    }
    Modal.confirm({
      title: t('提示'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('确定要删除所选项吗？'),
      onOk() {
        deleteFormTemplate(ids).then(() => {
          reload();
          notification.success({
            message: t('提示'),
            description: t('删除成功'),
          });
        });
      },
      onCancel() {},
      okText: t('确认'),
      cancelText: t('取消'),
    });
  }

  function handleCodeGenerator(record) {
    openCodeGeneratorModal(true, { formId: record.id });
  }

  function handleSuccess() {
    notification.success({
      message: t('提示'),
      description: t('保存成功'),
    });
    reload();
  }

  function handleClose(modal) {
    state[modal] = !state[modal];
    setTimeout(() => {
      state[modal] = !state[modal];
    }, 100);
  }

  function handleSelect(selectIds) {
    selectId.value = selectIds[0];
    reload({ searchInfo: { category: selectIds[0] } });
  }

  function handleCategory() {
    openCategoryModal(true, { title: t('表单分类管理') });
  }

  function handleImport() {
    openImportModal(true, {
      title: t('快速导入'),
      type: 'POST',
    });
  }

  function handleExport() {
    if (!getSelectRows().length) {
      noticeInfo('导出');
      return;
    }
    getSelectRows().forEach(async (row) => {
      const res = await exportFormDesign(row.id);
      downloadByData(res, row.name + '.json');
    });
  }

  async function fetch() {
    treeData.value = (await getDicDetailList({
      itemId: dicId,
    })) as unknown as TreeItem[];
    treeData.value.unshift({
      key: '',
      id: '',
      name: '全部',
    });
  }

  async function previewForm(record) {
    const templateJson = await getFormTemplate(record.id);
    openPreviewModal(true, { title: t('预览'), formJson: templateJson.formJson });
  }

  async function queryHistory(record) {
    openHistoryModal(true, { title: t('历史记录'), formId: record.id });
  }

  function noticeInfo(info: string) {
    notification.warning({
      message: t('提示'),
      description: t(`请先选择要{notice}的数据项`, { notice: info }),
    }); //提示消息
  }

  onMounted(() => {
    fetch();
  });
</script>
<style lang="less" scoped>
  :deep(.vben-tree-header) {
    padding: 0 16px;
  }
</style>
