<template>
  <PageWrapper dense contentFullHeight fixed-height>
    <BasicTable @register="registerTable" isMenuTable>
      <template #toolbar>
        <a-button type="primary" @click="handleDelete" danger>{{ t('批量删除') }}</a-button>
        <a-button type="primary" v-auth="'codeTemplate:add'" @click="handleCreate">
          <template #icon><PlusOutlined /></template>
          {{ t('新增') }}
        </a-button>
        <a-button v-auth="'codeTemplate:ectype'" type="primary" @click="handleCreateEctype"
          >创建副本</a-button
        >
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              auth: 'codeTemplate:edit',
              onClick: handleEdit.bind(null, record),
            },
            {
              label: '删除',
              auth: 'codeTemplate:delete',
              color: 'error',
              onClick: handleDelete.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>

    <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')"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';

  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';

  import DataFirstModal from '../dev/components/DataFirstModal.vue';
  import CodeFirstModal from '../dev/components/CodeFirstModal.vue';
  import SimpleTemplateModal from '../dev/components/SimpleTemplateModal.vue';
  import NoTableModal from '../dev/components/NoTableModal.vue';
  import { h, ref, createVNode, reactive, computed } from 'vue';
  import { FormDesignTypeEnum } from '/@/enums/formtypeEnum';
  import { Modal, Tag } from 'ant-design-vue';
  import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import {
    deleteCodeTemplate,
    getCodeTemplateList,
    getCodeTemplateInfo,
    saveDraftGeneratorCode,
  } from '/@/api/system/generator';
  import { SaveDraftGeneratorModel } from '/@/api/system/generator/model';
  import { useRouter } from 'vue-router';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { changeToPinyin } from '/@/utils/event/design';
  import { random } from 'lodash-es';
  import { noHaveField } from '/@/components/Designer';

  const { t } = useI18n();
  const { currentRoute } = useRouter();
  const { hasPermission } = usePermission();
  const codeType = computed(() => {
    const {
      value: { name },
    } = currentRoute;
    switch (name) {
      case 'simpleFirst':
        return FormDesignTypeEnum.SIMPLE_TEMPLATE;
      case 'styleFirst':
        return FormDesignTypeEnum.CODE_FIRST;
      case 'noTableFirst':
        return FormDesignTypeEnum.NO_TABLE;
      default:
        return FormDesignTypeEnum.DATA_FIRST;
    }
  });
  const title = computed(() => {
    switch (codeType.value) {
      case FormDesignTypeEnum.SIMPLE_TEMPLATE:
        return '简易';
      case FormDesignTypeEnum.CODE_FIRST:
        return '界面优先';
      case FormDesignTypeEnum.NO_TABLE:
        return '无表表单';
      default:
        return '数据优先';
    }
  });

  const selectedKeys = ref<string[]>([]);

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

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

    {
      dataIndex: 'description',
      title: t('功能描述'),
      resizable: true,
    },
    {
      dataIndex: 'categoryName',
      title: t('功能模块'),
      resizable: true,
    },
    {
      dataIndex: 'status',
      title: t('状态'),
      width: 120,
      resizable: true,
      customRender: ({ record }) => {
        const color = record.status == 1 ? 'blue' : 'yellow';
        const text = record.status == 1 ? '正常' : '草稿';
        return h(Tag, { color: color }, () => text);
      },
    },
    {
      dataIndex: 'remark',
      resizable: true,
      title: t('备注'),
    },
  ];

  const { notification } = useMessage();

  const [registerDataFirst, { openModal: openDataFirstModal }] = useModal();
  const [registerCodeFirst, { openModal: openCodeFirstModal }] = useModal();
  const [registerSimpleTemplate, { openModal: openSimpleTemplateModal }] = useModal();
  const [registerNoTable, { openModal: openNoTableModal }] = useModal();

  const [registerTable, { reload }] = useTable({
    title: t(title.value + '模板列表'),
    api: getCodeTemplateList,
    rowKey: 'id',
    columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [],
      showResetButton: false,
    },
    beforeFetch: (params) => {
      //发送请求默认新增
      return { ...params, type: codeType.value };
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    actionColumn: {
      width: 120,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    rowSelection: {
      type: 'checkbox',
      onChange: onSelectChange,
    },
    tableSetting: {
      size: false,
    },
    customRow: (record) => {
      return {
        ondblclick: () => {
          if (hasPermission('codeTemplate:edit')) {
            handleEdit(record);
          }
        },
      };
    },
  });

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

  function handleCreate() {
    switch (codeType.value) {
      case FormDesignTypeEnum.DATA_FIRST:
        openDataFirstModal(true, { undoAble: true });
        break;
      case FormDesignTypeEnum.CODE_FIRST:
        openCodeFirstModal(true, { undoAble: true });
        break;
      case FormDesignTypeEnum.SIMPLE_TEMPLATE:
        openSimpleTemplateModal(true, { undoAble: true });
        break;
      case FormDesignTypeEnum.NO_TABLE:
        openNoTableModal(true, { undoAble: true });
        break;
    }
  }

  function handleEdit(record: Recordable) {
    switch (codeType.value) {
      case FormDesignTypeEnum.DATA_FIRST:
        openDataFirstModal(true, {
          id: record.id,
          isUpdate: true,
        });
        break;
      case FormDesignTypeEnum.CODE_FIRST:
        openCodeFirstModal(true, {
          id: record.id,
          isUpdate: true,
        });
        break;
      case FormDesignTypeEnum.SIMPLE_TEMPLATE:
        openSimpleTemplateModal(true, {
          id: record.id,
          isUpdate: true,
        });
        break;
      case FormDesignTypeEnum.NO_TABLE:
        openNoTableModal(true, {
          id: record.id,
          isUpdate: true,
        });
        break;
    }
  }

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

  function handleSuccess() {
    reload();
  }

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

  // const templateJson = await getFormTemplate(formId.value);

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

  async function handleCreateEctype() {
    const keys = selectedKeys.value;
    if (!keys.length) {
      noticeInfo('创建副本');
      return;
    }
    if (codeType.value !== 0) {
      Modal.confirm({
        title: '提示',
        icon: createVNode(ExclamationCircleOutlined),
        content: '是否重新生成结构配置中的数据库信息？',
        okText: '是',
        cancelText: '否',
        closable: true,
        onOk() {
          copyInfo(keys, true);
        },
        onCancel() {
          copyInfo(keys, false);
        },
      });
    } else {
      copyInfo(keys);
    }
  }

  const copyInfo = async (keys, isReBuild = true) => {
    const info = await getCodeTemplateInfo(keys[keys.length - 1]);
    const content = JSON.parse(info.content);
    content.menuConfig = {};
    const params: SaveDraftGeneratorModel = {
      name: info.name,
      type: info.type, // 0-数据优先 1-界面优先 2-简易模板
      content: JSON.stringify(content),
      remark: info.remark,
    };
    if (codeType.value !== 0) {
      content.tableStructureConfigs = [];
      content.outputConfig.className = '';
      if (isReBuild) {
        changeField(content.formJson.list);
      }
      params.name = '';
      params.content = JSON.stringify(content);
    }
    await saveDraftGeneratorCode(params);
    reload();
  };

  const rangeComponents = ['time-range', 'date-range'];

  const changeField = (list) => {
    list?.map((item) => {
      if (['tab', 'grid', 'card'].includes(item.type)) {
        for (const child of item.layout!) {
          changeField(child.list);
        }
      } else if (item.type === 'table-layout') {
        for (const child of item.layout!) {
          for (const el of child.list) {
            changeField(el.children);
          }
        }
      } else if (item.type === 'form' || item.type === 'one-for-one') {
        changeField(item.children);
      } else {
        if (
          (!noHaveField.includes(item.type) && item.type !== 'input') ||
          (item.type == 'input' && !item.options.isSave)
        ) {
          item.bindField = changeToPinyin(item.label) + random(1000, 9999);
        } else if (rangeComponents.includes(item.type)) {
          item.bindStartTime = changeToPinyin(item.label) + random(1000, 9999);
          item.bindEndTime = changeToPinyin(item.label) + random(1000, 9999);
        }
      }
    });
  };
</script>
