<template>
  <div class="step4">
    <div class="w-3/4 mx-auto" v-if="!isCustomForm">
      <BasicForm @register="register" />
    </div>
    <Divider v-if="designType === 'code' && !isFormGenerator && !isCustomForm" />
    <template v-if="designType === 'code' && !isFormGenerator">
      <div v-for="(tableConfig, index) in generatorConfig?.tableStructureConfigs" :key="index">
        <div class="fixed-box" v-if="spinning">
          更换数据表名称,同步更换表单配置json中，请稍等......
        </div>
        <a-table
          :columns="tableColumns"
          :data-source="[tableConfig]"
          :pagination="false"
          :defaultExpandAllRows="true"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'tableName'">
              <a-input
                :class="
                  isTableNotSuccess.includes(record.tableName) ? 'ant-input-status-error' : ''
                "
                v-model:value="record.tableName"
                :placeholder="t('请填写数据表名称')"
                @change="changeComponentName(record, 'table')"
                @blur="handleBlur(record)"
              />
            </template>
            <template v-else-if="column.dataIndex === 'isMain'">
              <span>
                <a-tag :color="record.isMain ? 'blue' : 'orange'">
                  {{ record.isMain ? t('主表') : t('附表') }}
                </a-tag>
              </span>
            </template>
            <template v-else-if="column.dataIndex === 'tableComment'">
              <a-input v-model:value="record.tableComment" :placeholder="t('请填写备注')" />
            </template>
          </template>
          <template #expandedRowRender>
            <a-table
              :columns="fieldColumns"
              :data-source="tableConfig.tableFieldConfigs"
              :pagination="false"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'fieldName'">
                  <a-input
                    :class="
                      isFieldNotSuccess.includes(record.fieldName) ||
                      notHasRepeatName.includes(record.fieldName)
                        ? 'ant-input-status-error'
                        : ''
                    "
                    v-model:value="record.fieldName"
                    :placeholder="t(`请填写{title}`, { title: column.title })"
                    @focus="
                      () => {
                        curFieldName = record.fieldName;
                      }
                    "
                    @change="changeComponentName(record, 'field')"
                    @blur="handleBlurField(record)"
                    :disabled="disabledFields.includes(record.key)"
                  />
                </template>
                <template v-else-if="column.dataIndex === 'fieldLength'">
                  <a-input
                    v-model:value.number="record.fieldLength"
                    :placeholder="t('请填写字段长度')"
                    :disabled="disabledFields.includes(record.key)"
                  />
                </template>
                <template v-else-if="column.dataIndex === 'fieldComment'">
                  <a-input
                    v-model:value.number="record.fieldComment"
                    :placeholder="t('请填写备注')"
                    :disabled="disabledFields.includes(record.key)"
                  />
                </template>
                <template v-else-if="column.dataIndex === 'fieldType'">
                  <a-select
                    v-model:value="record.fieldType"
                    style="width: 100%"
                    :placeholder="t('请选择数据格式')"
                    :disabled="disabledFields.includes(record.key)"
                    allowClear
                    @change="(value) => handleTypeChange(value, record)"
                  >
                    <a-select-option
                      :value="type.value"
                      v-for="(type, idx) in fieldTypeList"
                      :key="idx"
                    >
                      {{ type.label }}
                    </a-select-option>
                  </a-select>
                </template>
              </template>
            </a-table>
          </template>
        </a-table>
      </div>
    </template>
    <template v-if="designType === 'notable' && !isFormGenerator">
      <NodeHead nodeName="接口配置" class="node-title" />
      <a-tabs v-model:activeKey="methodKey">
        <a-tab-pane :key="index" :tab="item.title" v-for="(item, index) in apiConfigArr">
          <ApiFormConfig :info="item" @change-config="changeConfig" />
        </a-tab-pane>
      </a-tabs>
    </template>
    <TableNameModal @register="registerTableName" @success="handleEditSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { onMounted, inject, computed, ref, Ref, watch } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { Divider } from 'ant-design-vue';
  import { TableNameModal } from '/@/components/CreateCodeStep';
  import { debounce, cloneDeep, random, snakeCase } from 'lodash-es';
  import { GeneratorConfig } from '/@/model/generator/generatorConfig';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { validateTableName } from '/@/api/system/generator';
  import { getAuthList } from '/@/api/system/authorize';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import ApiFormConfig from './components/ApiFormConfig.vue';
  import { fieldTypeList } from '/@/components/Designer';
  const { t } = useI18n();
  const { notification } = useMessage();
  const spinning = ref<boolean>(false);
  const emit = defineEmits(['validateTable']);
  const curFieldName = ref();
  const validateTable = ref(false);
  const methodKey = ref(0);
  const dataAuthPlaceholder = computed(() => {
    return generatorConfig!.outputConfig!.isDataAuth
      ? t('请选择已有通用数据权限')
      : t('请先启用数据权限');
  });
  const dataAuthHelpMessage = `
      1.启用数据权限会判断主表是否包含RuleUserlD字段如果存在，则不进行表结构修改，如果不存在，则会对主表进行字段添加。
      2.RuleUserlD主要用来控制每一条记录的权限所属人新增时，默认将当前登录认作为权限所属人。
      3.在表单设计中会添加“批量设置权限所属人”功能启用后，拥有该按钮权限的人员可以设置每一条记录的权限所属人。
        `;
  const commonHelpMessage = `
      1.审计字段包括创建人ID、创建人名称、最后修改人、最后修改时间、逻辑删除、标记字段。
      2.如果开启“审计字段”开关，则系统会自动实现相关操作，就是在新增时操作创建人、创建时间，编辑时操作最后修改人、最后修改时间，删除时改为逻辑删除，标记字段则标记字段是否有效。
      `;

  const commonFields = [
    {
      key: 'create_user_id',
      fieldName: 'create_user_id',
      fieldType: 6,
      fieldLength: null,
      fieldComment: t('创建人ID'),
    },
    {
      key: 'create_user_name',
      fieldName: 'create_user_name',
      fieldType: 0,
      fieldLength: 500,
      fieldComment: t('创建人名称'),
    },
    {
      key: 'create_date',
      fieldName: 'create_date',
      fieldType: 5,
      fieldLength: null,
      fieldComment: t('创建时间'),
    },
    {
      key: 'modify_user_id',
      fieldName: 'modify_user_id',
      fieldType: 6,
      fieldLength: null,
      fieldComment: t('修改人'),
    },
    {
      key: 'modify_date',
      fieldName: 'modify_date',
      fieldType: 5,
      fieldLength: null,
      fieldComment: t('修改时间'),
    },
    {
      key: 'delete_mark',
      fieldName: 'delete_mark',
      fieldType: 2,
      fieldLength: null,
      fieldComment: t('删除字段'),
    },
    {
      key: 'enabled_mark',
      fieldName: 'enabled_mark',
      fieldType: 2,
      fieldLength: null,
      fieldComment: t('标记字段'),
    },
  ];
  const handleCommonChange = (val) => {
    const fields = [
      'create_user_id',
      'create_user_name',
      'create_date',
      'modify_user_id',
      'modify_date',
      'delete_mark',
      'enabled_mark',
    ];
    if (!val) {
      if (generatorConfig?.tableStructureConfigs?.length) {
        generatorConfig.tableStructureConfigs[0].tableFieldConfigs =
          generatorConfig?.tableStructureConfigs[0].tableFieldConfigs.filter(
            (x) => !fields.includes(x.key!),
          );
      }
    } else {
      const hasCommonField =
        generatorConfig?.tableStructureConfigs?.length &&
        generatorConfig?.tableStructureConfigs[0].tableFieldConfigs.find((x) =>
          fields.includes(x.key!),
        );
      if (hasCommonField) return;
      generatorConfig?.tableStructureConfigs?.length &&
        generatorConfig?.tableStructureConfigs[0].tableFieldConfigs.push(...commonFields);
    }
    generatorConfig!.outputConfig!.isCommonFields = val;
  };

  const formSchemaCode: FormSchema[] = [
    {
      field: 'className',
      label: t('功能名称'),
      required: true,
      component: 'Input',
      colProps: { span: 12 },
      componentProps: {
        placeholder: t('请填写功能名称'),
        onChange: debounce((val: ChangeEvent) => {
          if (val.target.value !== generatorConfig!.outputConfig!.className) {
            generatorConfig!.outputConfig!.className = val.target.value;
            if (designType === 'notable') return;
            const { outputConfig, tableStructureConfigs } = generatorConfig!;
            tableStructureConfigs?.map((item) => {
              const name = snakeCase(outputConfig!.className!);
              const tableName = isFieldUpper.value ? name.toUpperCase() : name;
              item.tableName = item.isMain
                ? tableName
                : isFieldUpper.value
                ? `${tableName}_CHILD_${random(1000, 9999)}`
                : `${tableName}_child_${random(1000, 9999)}`;
              changeComponentName(item, 'table');
            });
          }
        }, 200),
      },
    },
    {
      field: 'comment',
      label: t('功能描述'),
      required: true,
      component: 'Input',
      colProps: { span: 12 },
      componentProps: {
        placeholder: t('请填写功能描述'),
        onChange: debounce((val: ChangeEvent) => {
          generatorConfig!.outputConfig!.comment = val.target.value;
        }, 200),
      },
    },
    {
      field: 'outputArea',
      label: t('功能模块'),
      component: 'DicSelect',
      required: true,
      componentProps: {
        placeholder: t('请选择功能模块'),
        itemId: '1419276800524423333',
        onChange: debounce((_, obj) => {
          if (obj) {
            generatorConfig!.outputConfig!.outputArea = obj.id;
            generatorConfig!.outputConfig!.outputValue = obj.value;
          }
        }, 200),
        getPopupContainer: () => document.body,
      },
      colProps: { span: 12 },
    },
    {
      field: 'isCommonFields',
      label: t('审计字段'),
      component: 'Switch',
      required: false,
      colProps: { span: 12 },
      helpMessage: commonHelpMessage,
      helpComponentProps: { maxWidth: '400px' },
      componentProps: {
        checkedValue: true,
        unCheckedValue: false,
        onChange: handleCommonChange,
      },
    },
    {
      field: 'isDataAuth',
      label: t('数据权限'),
      component: 'Switch',
      required: false,
      colProps: { span: 12 },
      helpMessage: dataAuthHelpMessage,
      helpComponentProps: { maxWidth: '400px' },
      componentProps: {
        checkedValue: true,
        unCheckedValue: false,
        onChange: (val) => {
          if (!val) {
            setFieldsValue({ dataAuthList: [] });
            generatorConfig!.outputConfig!.dataAuthList = [];
            if (generatorConfig?.tableStructureConfigs?.length) {
              generatorConfig.tableStructureConfigs[0].tableFieldConfigs =
                generatorConfig?.tableStructureConfigs[0].tableFieldConfigs.filter(
                  (x) => x.key !== 'rule_user_id',
                );
            }
          } else {
            const hasRuleUserField =
              generatorConfig?.tableStructureConfigs?.length &&
              generatorConfig?.tableStructureConfigs[0].tableFieldConfigs.find(
                (x) => x.key === 'rule_user_id',
              );
            if (hasRuleUserField) return;
            generatorConfig?.tableStructureConfigs?.length &&
              generatorConfig?.tableStructureConfigs[0].tableFieldConfigs.push({
                key: 'rule_user_id',
                fieldName: 'rule_user_id',
                fieldLength: 500,
                fieldType: 7,
                fieldComment: t('数据权限所属人ID'),
              });
          }
          generatorConfig!.outputConfig!.isDataAuth = val;
        },
      },
    },
    {
      field: 'dataAuthList',
      label: t('权限选择'),
      component: 'ApiSelect',
      required: false,
      colProps: { span: 12 },
      componentProps: {
        mode: 'multiple',
        placeholder: dataAuthPlaceholder,
        api: getAuthList,
        labelField: 'name',
        valueField: 'id',
        getPopupContainer: () => document.body,
        onChange: (val) => {
          generatorConfig!.outputConfig!.dataAuthList = val;
        },
      },
      dynamicDisabled: ({ values }) => {
        return !values.isDataAuth;
      },
    },
    {
      field: 'toDataFirst',
      label: '转为数据优先',
      component: 'Switch',
      required: false,
      colProps: { span: 12 },
      helpMessage:
        '打开开关，在设置完成后，“界面优先模板”及“简易模板”将转化为“数据优先模板”在代码模板中存在。',
      helpComponentProps: { maxWidth: '400px' },
      componentProps: {
        checkedValue: true,
        unCheckedValue: false,
        onChange: (val) => {
          generatorConfig!.outputConfig!.toDataFirst = val;
        },
      },
    },
    {
      field: 'remarks',
      label: t('备注'),
      component: 'Input',
      required: false,
      colProps: { span: 12 },
      componentProps: {
        placeholder: t('请填写备注'),
        onChange: debounce((val) => {
          generatorConfig!.outputConfig!.remarks = val.target.value;
          if (designType === 'notable') return;
          generatorConfig!.tableStructureConfigs?.map(
            (item) => (item.tableComment = item.isMain ? val.target.value : item.tableComment),
          );
        }, 200),
      },
    },
  ];
  const formSchemaData: FormSchema[] = [
    {
      field: 'className',
      label: t('功能名称'),
      required: true,
      component: 'Input',
      colProps: { span: 12 },
      componentProps: {
        placeholder: t('请填写功能名称'),
        onChange: (val: ChangeEvent) => {
          generatorConfig!.outputConfig!.className = val.target.value;
          const { outputConfig, tableStructureConfigs } = generatorConfig!;
          tableStructureConfigs?.map((item) => {
            const name = snakeCase(outputConfig!.className!);
            const tableName = isFieldUpper.value ? name.toUpperCase() : name;
            item.tableName = item.isMain
              ? tableName
              : isFieldUpper.value
              ? `${tableName}_CHILD_${random(1000, 9999)}`
              : `${tableName}_child_${random(1000, 9999)}`;
            changeComponentName(item, 'table');
          });
        },
      },
    },
    {
      field: 'comment',
      label: t('功能描述'),
      required: true,
      component: 'Input',
      colProps: { span: 12 },
      componentProps: {
        placeholder: t('请填写功能描述'),
        onChange: debounce((val: ChangeEvent) => {
          generatorConfig!.outputConfig!.comment = val.target.value;
        }, 200),
      },
    },
    {
      field: 'outputArea',
      label: t('功能模块'),
      component: 'DicSelect',
      required: true,
      componentProps: {
        placeholder: t('请选择功能模块'),
        itemId: '1419276800524423333',
        onChange: debounce((_, obj) => {
          if (obj) {
            generatorConfig!.outputConfig!.outputArea = obj.id;
            generatorConfig!.outputConfig!.outputValue = obj.value;
          }
        }, 200),
        getPopupContainer: () => document.body,
      },
      colProps: { span: 12 },
    },
    {
      field: 'remarks',
      label: t('备注'),
      component: 'Input',
      required: false,
      colProps: { span: 12 },
      componentProps: {
        placeholder: t('请填写备注'),
        onChange: debounce((val) => {
          generatorConfig!.outputConfig!.remarks = val.target.value;
          generatorConfig!.tableStructureConfigs?.map(
            (item) => (item.tableComment = item.isMain ? val.target.value : item.tableComment),
          );
        }, 200),
      },
    },
    {
      field: 'isDataAuth',
      label: t('数据权限'),
      component: 'Switch',
      required: false,
      colProps: { span: 12 },
      helpMessage: dataAuthHelpMessage,
      helpComponentProps: { maxWidth: '400px' },
      componentProps: {
        checkedValue: true,
        unCheckedValue: false,
        onChange: (val) => {
          if (!val) {
            setFieldsValue({ dataAuthList: [] });
            generatorConfig!.outputConfig!.dataAuthList = [];
            generatorConfig?.tableStructureConfigs?.length &&
              generatorConfig?.tableStructureConfigs[0].tableFieldConfigs.map(
                (x) => x.key !== 'rule_user_id',
              );
          } else {
            const hasRuleUserField =
              generatorConfig?.tableStructureConfigs?.length &&
              generatorConfig?.tableStructureConfigs[0].tableFieldConfigs.find(
                (x) => x.key === 'rule_user_id',
              );
            if (hasRuleUserField) return;
            generatorConfig?.tableStructureConfigs?.length &&
              generatorConfig?.tableStructureConfigs[0].tableFieldConfigs.push({
                key: 'rule_user_id',
                fieldName: 'rule_user_id',
                fieldLength: 500,
                fieldType: 7,
                fieldComment: t('数据权限所属人ID'),
              });
          }
          generatorConfig!.outputConfig!.isDataAuth = val;
        },
      },
    },
    {
      field: 'dataAuthList',
      label: t('权限选择'),
      component: 'ApiSelect',
      required: false,
      colProps: { span: 12 },
      componentProps: {
        mode: 'multiple',
        placeholder: dataAuthPlaceholder,
        api: getAuthList,
        labelField: 'name',
        valueField: 'id',
        getPopupContainer: () => document.body,
        onChange: (val) => {
          generatorConfig!.outputConfig!.dataAuthList = val;
        },
      },
      dynamicDisabled: ({ values }) => {
        return !values.isDataAuth;
      },
    },
  ];
  const formSchemaNoTable: FormSchema[] = [
    {
      field: 'className',
      label: t('功能名称'),
      required: true,
      component: 'Input',
      colProps: { span: 12 },
      componentProps: {
        placeholder: t('请填写功能名称'),
        onChange: (val: ChangeEvent) => {
          generatorConfig!.outputConfig!.className = val.target.value;
          const { outputConfig, tableStructureConfigs } = generatorConfig!;
          tableStructureConfigs?.map((item) => {
            const name = snakeCase(outputConfig!.className!);
            const tableName = isFieldUpper.value ? name.toUpperCase() : name;
            item.tableName = item.isMain
              ? tableName
              : isFieldUpper.value
              ? `${tableName}_CHILD_${random(1000, 9999)}`
              : `${tableName}_child_${random(1000, 9999)}`;
            changeComponentName(item, 'table');
          });
        },
      },
    },
    {
      field: 'comment',
      label: t('功能描述'),
      required: true,
      component: 'Input',
      colProps: { span: 12 },
      componentProps: {
        placeholder: t('请填写功能描述'),
        onChange: debounce((val: ChangeEvent) => {
          generatorConfig!.outputConfig!.comment = val.target.value;
        }, 200),
      },
    },
    {
      field: 'outputArea',
      label: t('功能模块'),
      component: 'DicSelect',
      required: true,
      componentProps: {
        placeholder: t('请选择功能模块'),
        itemId: '1419276800524423333',
        onChange: debounce((_, obj) => {
          if (obj) {
            generatorConfig!.outputConfig!.outputArea = obj.id;
            generatorConfig!.outputConfig!.outputValue = obj.value;
          }
        }, 200),
        getPopupContainer: () => document.body,
      },
      colProps: { span: 12 },
    },
    {
      field: 'remarks',
      label: t('备注'),
      component: 'Input',
      required: false,
      colProps: { span: 12 },
      componentProps: {
        placeholder: t('请填写备注'),
        onChange: debounce((val) => {
          generatorConfig!.outputConfig!.remarks = val.target.value;
          generatorConfig!.tableStructureConfigs?.map(
            (item) => (item.tableComment = item.isMain ? val.target.value : item.tableComment),
          );
        }, 200),
      },
    },
  ];
  const generatorSchema: FormSchema[] = [
    {
      field: 'className',
      label: t('功能名称'),
      required: true,
      component: 'Input',
      colProps: { span: 12 },
      componentProps: {
        placeholder: t('请填写功能名称'),
        onChange: debounce((val: ChangeEvent) => {
          generatorConfig!.outputConfig!.className = val.target.value;
        }, 200),
      },
    },
    {
      field: 'comment',
      label: t('功能描述'),
      required: true,
      component: 'Input',
      colProps: { span: 12 },
      componentProps: {
        placeholder: t('请填写功能描述'),
        onChange: debounce((val: ChangeEvent) => {
          generatorConfig!.outputConfig!.comment = val.target.value;
        }, 200),
      },
    },
    {
      field: 'outputArea',
      label: t('功能模块'),
      component: 'DicSelect',
      required: true,
      componentProps: {
        placeholder: t('请选择功能模块'),
        itemId: '1419276800524423333',
        onChange: debounce((_, obj) => {
          if (obj) {
            generatorConfig!.outputConfig!.outputArea = obj.id;
            generatorConfig!.outputConfig!.outputValue = obj.value;
          }
        }, 200),
        getPopupContainer: () => document.body,
      },
      colProps: { span: 12 },
    },
    {
      field: 'remarks',
      label: t('备注'),
      component: 'Input',
      required: false,
      colProps: { span: 12 },
      componentProps: {
        placeholder: t('请填写备注'),
        onChange: debounce((val) => {
          generatorConfig!.outputConfig!.remarks = val.target.value;
        }, 200),
      },
    },
  ];

  const tableColumns = [
    {
      title: t('数据表名称'),
      dataIndex: 'tableName',
      align: 'center',
    },
    {
      title: t('数据表类别'),
      dataIndex: 'isMain',
      align: 'center',
      width: 200,
    },
    {
      title: t('备注'),
      dataIndex: 'tableComment',
      align: 'center',
    },
  ];

  const fieldColumns = [
    {
      title: t('字段名'),
      dataIndex: 'fieldName',
      align: 'center',
    },
    {
      title: t('字段长度'),
      dataIndex: 'fieldLength',
      align: 'center',
    },
    {
      title: t('数据格式'),
      dataIndex: 'fieldType',
      align: 'center',
    },
    {
      title: t('备注'),
      dataIndex: 'fieldComment',
      align: 'center',
    },
  ];

  const props = defineProps({
    //是否是自定义表单生成代码
    isFormGenerator: {
      type: Boolean,
      default: false,
    },
    //是否是编辑状态
    isUpdate: {
      type: Boolean,
      default: false,
    },
    //新增时的表名集合
    beforeTableNames: {
      type: Array,
      default: () => [],
    },
    //自定义表单生成代码使用
    designType: {
      type: String,
      default: '',
    },
  });

  const current = inject<Ref<number>>('current') as Ref<number>;
  const generatorConfig = inject<GeneratorConfig>('generatorConfig');
  const widgetForm = inject<any>('widgetForm');
  let mainTableName = inject<any>('mainTableName', '');
  const designType = inject<string>('designType', props.isFormGenerator ? props.designType : '');
  const isCustomForm = inject<boolean>('isCustomForm', false);
  const isFieldUpper = inject<Ref<boolean>>('isFieldUpper', ref(false));
  const apiConfigArr = ref<any[]>([]);
  const disabledFields = [
    'create_user_id',
    'create_user_name',
    'create_date',
    'modify_user_id',
    'modify_date',
    'delete_mark',
    'enabled_mark',
    'rule_user_id',
  ];

  //解决打包部署后  数据不回显bug
  watch(
    () => current.value,
    () => {
      if (
        designType === 'code' &&
        (generatorConfig?.outputConfig?.className ||
          generatorConfig?.outputConfig?.comment ||
          generatorConfig?.outputConfig?.outputArea)
      ) {
        const { outputConfig } = generatorConfig!;
        if (
          !isCustomForm &&
          (outputConfig?.className || outputConfig?.comment || outputConfig?.outputArea)
        ) {
          setFieldsValue({
            className: outputConfig?.className,
            comment: outputConfig?.comment,
            outputArea: outputConfig?.outputArea,
            isDataAuth: outputConfig?.isDataAuth,
            dataAuthList: outputConfig?.dataAuthList,
            toDataFirst: outputConfig?.toDataFirst,
            remarks: outputConfig?.remarks,
          });
          clearValidate();
        }
      }
      if (!props.isFormGenerator && designType === 'notable') {
        const btnsValue = ['add', 'edit', 'delete', 'view'];
        apiConfigArr.value = generatorConfig?.apiConfig!.filter((x) =>
          btnsValue.includes(x.value!),
        );
      }
    },
  );
  const schemas = computed(() => {
    if (props.isFormGenerator) {
      return generatorSchema;
    } else {
      switch (designType) {
        case 'notable':
          return formSchemaNoTable;
        case 'data':
          return formSchemaData;
        default:
          return formSchemaCode;
      }
    }
  });

  const [registerTableName, { openModal, closeModal }] = useModal();

  const [register, { validate, setFieldsValue, clearValidate }] = useForm({
    schemas,
    showActionButtonGroup: false,
    layout: 'vertical',
    rowProps: { gutter: 32 },
  });
  onMounted(() => {
    const { outputConfig } = generatorConfig!;
    if (props.isFormGenerator && designType === 'notable' && !isCustomForm) {
      const btnsValue = ['add', 'edit', 'delete', 'view'];
      apiConfigArr.value = generatorConfig?.apiConfig!.filter((x) => btnsValue.includes(x.value!));
    }
    if (
      !isCustomForm &&
      (outputConfig?.className || outputConfig?.comment || outputConfig?.outputArea)
    ) {
      setFieldsValue({
        className: outputConfig?.className,
        comment: outputConfig?.comment,
        outputArea: outputConfig?.outputArea,
        isDataAuth: outputConfig?.isDataAuth,
        dataAuthList: outputConfig?.dataAuthList,
        isCommonFields: outputConfig?.isCommonFields,
        toDataFirst: outputConfig?.toDataFirst,
        remarks: outputConfig?.remarks,
      });
    }
    if (!isCustomForm) clearValidate();
  });
  const changeComponentInfo = (list, type, fieldKey, name, tableKey, record, rangField?) => {
    const isTable = type === 'table';
    if (generatorConfig?.formJson.hiddenComponent?.length) {
      generatorConfig?.formJson.hiddenComponent?.map((component: any) => {
        if (component.key === fieldKey) {
          isTable ? (component.bindTable = name) : (component.bindField = name);
        }
      });
      widgetForm!.value.hiddenComponent = cloneDeep(generatorConfig?.formJson.hiddenComponent);
    }
    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 (isTable) {
                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,
                    type,
                    fieldKey,
                    name,
                    tableKey,
                    record,
                    rangField,
                  );
                }
              } else if (subComponent.type == 'table-layout') {
                for (const child of subComponent.layout!) {
                  for (const el of child.list!) {
                    changeComponentInfo(
                      el.children,
                      type,
                      fieldKey,
                      name,
                      tableKey,
                      record,
                      rangField,
                    );
                  }
                }
              }
            });
          }
        } else {
          if (component.children.length) {
            component.children.map((subComponent: any) => {
              if (subComponent.type === 'sun-form') {
                if (isTable && subComponent.key === tableKey) {
                  subComponent.bindTable = name;
                }
                changeComponentInfo(
                  subComponent.children,
                  type,
                  fieldKey,
                  name,
                  tableKey,
                  record,
                  rangField,
                );
              } else if (['tab', 'grid', 'card'].includes(subComponent.type)) {
                for (const subChild of subComponent.layout!) {
                  changeComponentInfo(
                    subChild.list,
                    type,
                    fieldKey,
                    name,
                    tableKey,
                    record,
                    rangField,
                  );
                }
              } else if (subComponent.type == 'table-layout') {
                for (const child of subComponent.layout!) {
                  for (const el of child.list!) {
                    changeComponentInfo(
                      el.children,
                      type,
                      fieldKey,
                      name,
                      tableKey,
                      record,
                      rangField,
                    );
                  }
                }
              } else if (subComponent.key === fieldKey) {
                if (['time-range', 'date-range'].includes(subComponent.type)) {
                  if (!isTable) {
                    subComponent[rangField] = name;
                    record[record.fieldStartName ? 'fieldStartName' : 'fieldEndName'] = name;
                  }
                } else {
                  if (!isTable) {
                    subComponent.bindField = name;
                  }
                }
              }
            });
          }
        }
      } else if (['tab', 'grid', 'card'].includes(component.type)) {
        if (
          isTable &&
          ((tableKey && component.parentTableKey === tableKey) ||
            (!tableKey && !component.parentTableKey))
        ) {
          component.bindTable = name;
        }
        for (const child of component.layout!) {
          changeComponentInfo(child.list, type, fieldKey, name, tableKey, record, rangField);
        }
      } else if (component.type == 'table-layout') {
        if (
          isTable &&
          ((tableKey && component.parentTableKey === tableKey) ||
            (!tableKey && !component.parentTableKey))
        ) {
          component.bindTable = name;
        }
        for (const child of component.layout!) {
          for (const el of child.list!) {
            changeComponentInfo(el.children, type, fieldKey, name, tableKey, record, rangField);
          }
        }
      } else if (component.key === fieldKey) {
        //修改主表名
        mainTableName!.value = name;
        if (['time-range', 'date-range'].includes(component.type)) {
          if (isTable) {
            component.bindTable = name;
          } else {
            component[rangField] = name;
            record[record.fieldStartName ? 'fieldStartName' : 'fieldEndName'] = name;
          }
        } else {
          isTable ? (component.bindTable = name) : (component.bindField = name);
        }
      } else {
        return '';
      }
    });
    widgetForm!.value.list = cloneDeep(generatorConfig!.formJson.list); //表单设计页面绑定表和字段需要同步修改
  };

  const changeComponentName = (record, type) => {
    const rangField = record.fieldStartName
      ? 'bindStartTime'
      : record.fieldEndName
      ? 'bindEndTime'
      : '';
    if (type === 'table') {
      spinning.value = true;
      setTimeout(() => {
        const name = snakeCase(record.tableName);
        record.tableFieldConfigs.forEach((item) => {
          changeComponentInfo(
            generatorConfig?.formJson.list,
            'table',
            item.key,
            isFieldUpper.value ? name.toUpperCase() : name,
            record.key,
            record,
          );
        });
        spinning.value = false;
      }, 0);
    } else {
      let filteredStr = record.fieldName.replace(/[^a-zA-Z0-9_]/g, '');
      changeComponentInfo(
        generatorConfig?.formJson.list,
        'field',
        record.key,
        filteredStr,
        '',
        record,
        rangField,
      );
    }

    notHasRepeatName.value = notHasRepeatName.value.filter((o) => o !== curFieldName.value);
  };
  function handleBlurField(record) {
    record.fieldName = record.fieldName.replace(/[^a-zA-Z0-9_]/g, '');
  }
  const handleBlur = (record) => {
    const name = snakeCase(record.tableName);
    record.tableName = isFieldUpper.value ? name.toUpperCase() : name;
  };

  const handleTypeChange = (value, record) => {
    if (value !== 0) {
      record.fieldLength = null;
    } else {
      record.fieldLength = 500;
    }
  };
  const isTableNotSuccess = ref<string[]>([]);
  const isFieldNotSuccess = ref<string[]>([]);
  const notHasRepeatName = ref<string[]>([]);
  //验证当前步骤的数据
  const validateStep = async (): Promise<boolean> => {
    isTableNotSuccess.value = [];
    isFieldNotSuccess.value = [];
    notHasRepeatName.value = [];
    try {
      const { tableStructureConfigs, outputConfig } = generatorConfig!;
      if (designType !== 'notable') {
        const sunFormList = tableStructureConfigs!.filter((x) => x.parentKey);
        sunFormList.forEach((item) => {
          tableStructureConfigs!.forEach((config) => {
            if (item.parentKey === config.key) {
              item.parentTable = config.tableName;
            }
          });
        });
      }

      if (!isCustomForm) {
        await validate();

        if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(outputConfig!.className!)) {
          notification.error({
            message: t('提示'),
            description: t('功能名称只能是数字和字母组成，必须以英文字母开头'),
          });
          return false;
        }
      }
      if (props.isFormGenerator || designType === 'notable') return true;
      const tableNames: string[] = tableStructureConfigs!.map((x) => x.tableName);

      const reg = /^[a-zA-Z0-9_]*$/;
      //判断表名是否符合要求
      tableStructureConfigs?.map((config: any) => {
        if (!reg.test(config.tableName)) {
          isTableNotSuccess.value.push(config.tableName);
        }
      });

      if (isTableNotSuccess.value.length > 0) {
        notification.error({
          message: t('提示'),
          description: '表名只能包括字母、数字、下划线',
        }); //提示消息
        return false;
      }
      //判断字段名是否符合要求
      tableStructureConfigs?.map((config: any) => {
        config.tableFieldConfigs.map((fieldConfig: any) => {
          if (!reg.test(fieldConfig.fieldName) || fieldConfig.fieldName.length > 30) {
            isFieldNotSuccess.value.push(fieldConfig.fieldName);
          }
        });
      });
      if (isFieldNotSuccess.value.length > 0) {
        notification.error({
          message: t('提示'),
          description:
            '字段名必须以小写字母开头，只能包括小写字母、数字、下划线，并且不能超过30个字符',
        }); //提示消息
        return false;
      }
      tableStructureConfigs?.map((config) => {
        config.tableFieldConfigs.map((x) => {
          let obj: any = config.tableFieldConfigs.filter((o) => o.fieldName == x.fieldName);
          if (obj.length > 1) {
            notHasRepeatName.value.push(obj[0].fieldName);
          }
        });
      });
      if (notHasRepeatName.value.length > 0) {
        notification.error({
          message: t('提示'),
          description: t('同一个表内，不能有相同字段名'),
        }); //提示消息
        return false;
      }
      const testTableNames = tableNames.filter((x) => {
        return !props.beforeTableNames.includes(x);
      });
      const params = {
        id: designType === 'code' ? generatorConfig!.databaseId! : 'master',
        tableNames: props.isUpdate ? testTableNames.toString() : tableNames.toString(),
      };
      if (!props.isUpdate || (!props.isUpdate && testTableNames.length)) {
        await validateTableName(params);
      }

      if (props.isUpdate) {
        if (!validateTable.value) {
          openModal();
          return false;
        }
      }
    } catch (error) {
      return false;
    }
    validateTable.value = false;
    return true;
  };
  async function handleEditSuccess() {
    validateTable.value = true;
    closeModal();
    emit('validateTable');
  }

  const changeConfig = (config) => {
    generatorConfig!.apiConfig[methodKey.value] = config;
  };

  defineExpose({ validateStep });
</script>
<style lang="less" scoped>
  .step4 {
    padding-top: 30px;

    p {
      color: @text-color;
    }
  }

  :deep(.ant-tag-orange),
  :deep(.ant-tag-blue) {
    background: #fff;
    font-size: 13px;
  }

  :deep(.ant-spin-nested-loading) {
    overflow: hidden; //去掉表格嵌套子表滚动条
  }

  .node-title {
    border-bottom: 1px solid #e5e7eb;
    padding: 10px;
  }

  .ant-input-status-error {
    border-color: #ff4d4f;
  }

  .fixed-box {
    position: absolute;
    z-index: 1;
    inset: 0;
    background-color: #e5e7eb;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
