<template>
  <BasicModal
    v-bind="$attrs"
    @register="automaticModal"
    title="表结构配置"
    width="60%"
    maxHeight="80%"
    @fullscreen="onFullscreen"
    :showCancelBtn="true"
    :showOkBtn="true"
    @ok="submit"
    @cancel="closeModalDeleteGrid"
    @visible-change="
      () => {
        db_list.value = [];
        chlidTableName = '';
        isCloseSubmit.value = false;
      }
    "
  >
    <a-alert message="主表的字段名可进行修改，数据格式默认为 varchar" type="info" />
    <a-alert message="自动建表内的线索组件有专用geom字段负责，无需配置" type="info" />
    <a-alert
      message="* 表名、字段名由数字、字母或下划线组成，且不能以数字，特殊字符串开头。"
      type="error"
    />
    <a-alert message="* 表名、字段名一旦生成不可修改。" type="error" />
    <a-divider />
    <div v-for="db in db_list" :key="db.dbColumnName">
      <CollapseContainer :title="db.tableName">
        <a-row :gutter="16">
          <a-col class="gutter-row" :span="2">
            <a-tag :color="db.type == 'main' ? '#67c23a' : '#e6a23c'">
              {{ db.type == 'main' ? '主表' : '子表' }}
            </a-tag>
          </a-col>
          <a-col class="gutter-row" :span="11">
            <a-input
              v-model:value="db.tableName"
              :disabled="!isNewTable(db)"
              @change="db.tableName = db.tableName.toLowerCase()"
            />
          </a-col>
          <a-col class="gutter-row" :span="11">
            <a-input
              v-model:value="db.description"
              placeholder="请输入备注"
              :disabled="!isNewTable(db)"
            />
          </a-col>
        </a-row>
        <BasicTable
          :dataSource="db.dbColumnInfoList"
          :columns="dbColumnInfoColumns"
          :canResize="false"
          :bordered="true"
          :showTableSetting="false"
          :pagination="false"
          :autoCreateKey="false"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'dbColumnName'">
              <div>
                <a-input
                  v-model:value="record.dbColumnName"
                  :disabled="!isNewFormItem(record)"
                  @change="record.dbColumnName = record.dbColumnName.toLowerCase()"
                  @focus="focusDbColumnName = record.dbColumnName"
                  @blur="replaceInJsonDbColumnName(record.dbColumnName)"
                />
              </div>
            </template>
            <template v-if="column.key === 'length'">
              <div>
                <a-input-number
                  v-model:value="record.length"
                  defaultValue="200"
                  :disabled="
                    !isNewFormItem(record) || (record.length == 0 && record.dataType == 'bool')
                  "
                  @change="if (!record.length) record.length = 0;"
                />
              </div>
            </template>
            <template v-if="column.key === 'dataType'">
              <div>
                <a-select
                  ref="select"
                  size="small"
                  placeholder="请选择"
                  style="width: 100%; text-align: left"
                  v-model:value="record.dataType"
                  :options="dataTypeOptions"
                  :disabled="!isNewFormItem(record)"
                  @change="isBoolChangeLength(record)"
                />
              </div>
            </template>
            <template v-if="column.key === 'columnDescription'">
              <div>
                <a-input
                  v-model:value="record.columnDescription"
                  :disabled="!isNewFormItem(record)"
                />
              </div>
            </template>
          </template>
        </BasicTable>
      </CollapseContainer>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, defineProps } from 'vue';
  import { CollapseContainer } from '@/components/Container';
  import { BasicTable } from '@/components/Table';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { useMessage } from '@/hooks/web/useMessage';
  import { cloneDeep } from 'lodash-es';
  import { dbColumnInfoColumns } from './modelData';
  import { functionGetForm, AddTable, AddColumn } from '@/api/demo/formScheme';
  import { CheckTableExist } from '@/api/database/index';

  const emit = defineEmits(['automatic-modal-submitsuccess']);
  const { createMessage } = useMessage();

  const props = defineProps({
    isAddVisible: {
      default: false,
      type: Boolean, //判断新增还是编辑
    },
  });
  // 数据
  let saveFormDatas: any;
  // 表结构-模板
  let tableInfo: any = {
    type: '',
    name: '',
    tableName: '',
    description: '',
    dbCode: '',
    dbColumnInfoList: [],
  };
  // 子表
  let db_list: any = ref([]);
  // 主键
  let primaryKey = '';
  // dbCode
  let forminfoDbCode = '';
  // 上一次保存的表单db信息
  let oldDb: any = [];

  // 表结构初始值
  let dbColumnInfo = {
    tableName: '',
    dbColumnName: '',
    field: '',
    dataType: '',
    length: 0,
    columnDescription: '',
    isNullable: 1,
    isIdentity: 0,
    isPrimarykey: 0,
    decimalDigits: 0,
  };
  // 数据格式-下拉框
  let dataTypeOptions = [
    { label: '字符串', value: 'varchar' },
    { label: '长文本', value: 'text' },
    { label: '数字', value: 'int8' },
    { label: '是否', value: 'bool' },
    { label: '日期', value: 'timestamp' },
  ];
  // 不需要添加的表结构
  let notComponentArray = ['Divider', 'Button'];
  // 需要特殊处理的表结构
  let mapGeomArray = 'MapGeom';
  let gridArray = ['Grid', 'Card', 'CardGroup', 'Tabs'];

  // 异步传参
  const [automaticModal, { closeModal }] = useModalInner(async (data) => {
    // 获取db
    if (!props.isAddVisible) {
      let query: any = { id: data.saveFormDatas.info.id };
      let result: any = await functionGetForm(query);
      let result_json = JSON.parse(result.scheme.scheme);
      let data_json = JSON.parse(data.saveFormDatas.scheme.scheme);
      data_json.db = result_json.db;
      // 上一次保存的表单db信息
      oldDb = result_json.db;
      data.saveFormDatas.scheme.scheme = JSON.stringify(data_json);
    }
    // 表名和备注
    let scheme = JSON.parse(data.saveFormDatas.scheme.scheme);
    // console.log(160, scheme);
    // 分析表单
    db_list.value = [];
    // dbCode
    forminfoDbCode = data.saveFormDatas.info.DbCode;
    // 分析表单
    scheme = getSchemeByscheme(
      scheme,
      forminfoDbCode,
      'main',
      scheme.db,
      scheme.db[0].tableName,
      '',
      'main',
      cloneDeep(tableInfo),
    );
    // 切换旧的db到新分析的db上
    if (!props.isAddVisible) {
      replaceOldDb();
    }
    saveFormDatas = data.saveFormDatas;
    saveFormDatas.scheme.scheme = JSON.stringify(scheme);
  });

  // 分析表单
  function getSchemeByscheme(
    scheme: any,
    dbCode,
    type, // 主表还是子表
    schemedb,
    mainTableName, // 主表名
    chlidTableName, // 子表名
    gridType, // 布局类型
    db_temp,
  ) {
    let schemas: any = '';
    // 主表-db
    if (type == 'main') {
      // 新增时使用
      if (props.isAddVisible) {
        db_temp.name = scheme.db[0].name || scheme.db[0].tableName;
        db_temp.tableName = scheme.db[0].tableName || scheme.db[0].name;
        db_temp.description = '主表';
        db_temp.type = 'main';
        db_temp.dbCode = dbCode;
        db_temp.dbColumnInfoList = [];
        mainTableName = db_temp.tableName;
      } else {
        // 编辑主体表时使用
        if (gridType == 'main') {
          db_temp = schemedb[0];
          db_temp.dbColumnInfoList = [];
          // } else {
          //   // 编辑主体表的布局组件时使用
          //   console.log(207, db_temp);
        }
        mainTableName = db_temp.tableName;
      }
    }
    // 子表-db
    if (type == 'chlid') {
      // 是否是新的子表
      if (!chlidTableName && gridType == 'chlid') {
        db_temp.name = mainTableName + scheme.field;
        db_temp.tableName = db_temp.name;
        db_temp.description = '子表';
        db_temp.type = 'chlid';
        db_temp.dbCode = dbCode;
        db_temp.relationName = mainTableName;
        db_temp.dbColumnInfoList = [];
      } else {
        // 是否是保存到数据库里的子表
        let schemedb_temp: any = schemedb.find((item) => {
          return item.tableName == chlidTableName;
        });
        if (schemedb_temp) {
          db_temp = schemedb_temp;
          db_temp.dbColumnInfoList = [];
        } else {
          db_temp.name = mainTableName + scheme.field;
          db_temp.tableName = db_temp.name;
          db_temp.description = '子表';
          db_temp.type = 'chlid';
          db_temp.dbCode = dbCode;
          db_temp.relationName = mainTableName;
          db_temp.dbColumnInfoList = [];
        }
      }
    }

    // 主表-table
    if (type == 'main') {
      let mainEach: any = [];
      if (gridType == 'main') {
        mainEach = scheme.formInfo.tabList;
      } else if (gridType == 'Tabs') {
        let temp: any = [];
        temp.push(scheme);
        mainEach.push({
          schemas: temp,
        });
      }
      mainEach.forEach((sch, i) => {
        schemas = sch.schemas;
        schemas?.forEach((item: any, index: number) => {
          // 过滤分割线、按钮
          if (item.component && !notComponentArray.includes(item.component)) {
            // 线索组件
            if (mapGeomArray == item.component) {
              db_temp.dbColumnInfoList.push({
                tableName: db_temp.tableName,
                dbColumnName: 'gid',
                field: item.field,
                dataType: 'varchar',
                length: 200,
                columnDescription: '线索组件id',
                isNullable: 1,
                isIdentity: 0,
                isPrimarykey: 0,
                decimalDigits: 0,
              });
              db_temp.dbColumnInfoList.push({
                tableName: db_temp.tableName,
                dbColumnName: 'geom',
                field: item.field,
                dataType: 'geometry(GEOMETRY)',
                length: 0,
                columnDescription: '线索组件',
                isNullable: 1,
                isIdentity: 0,
                isPrimarykey: 0,
                decimalDigits: 0,
              });

              item.componentProps.dataTable = db_temp.tableName;
              item.componentProps.fieldName = 'gid';
              item.csType = 'string';
            }
            // 子表-递归
            else if (item.component == 'Grid' && item.type == 'subTable') {
              let res = getSchemeByscheme(
                item,
                dbCode,
                'chlid',
                schemedb,
                mainTableName,
                item.componentProps.dataTable || undefined,
                'chlid',
                cloneDeep(tableInfo),
              );
              item.componentProps.dataTable =
                res?.columns[0]?.children[0]?.componentProps?.dataTable;
              item.csType = 'string';
            }
            // 布局控件
            else if (gridArray.includes(item.component)) {
              // 选项卡
              if (item.component == 'Tabs') {
                item.componentProps.options.forEach((op) => {
                  op.children.forEach((ch) => {
                    // 过滤分割线、按钮
                    if (ch.component && !notComponentArray.includes(ch.component)) {
                      // 选项卡-子表-递归
                      if (ch.component == 'Grid' && ch.type == 'subTable') {
                        let res = getSchemeByscheme(
                          ch,
                          dbCode,
                          'chlid',
                          schemedb,
                          mainTableName,
                          ch.componentProps.dataTable || undefined,
                          'Tabs',
                          cloneDeep(tableInfo),
                        );
                        ch.componentProps.dataTable =
                          res?.columns[0]?.children[0]?.componentProps?.dataTable;
                        ch.csType = 'string';
                      }
                      // 选项卡-线索组件/布局组件
                      else if (mapGeomArray == ch.component || gridArray.includes(ch.component)) {
                        getSchemeByscheme(
                          ch,
                          dbCode,
                          'chlid',
                          schemedb,
                          mainTableName,
                          ch.componentProps.dataTable || undefined,
                          'Tabs',
                          db_temp,
                        );
                      }
                      // 普通组件
                      else {
                        let temp = cloneDeep(dbColumnInfo);
                        temp.tableName = db_temp.tableName.toLowerCase();
                        temp.dbColumnName =
                          getDbColumnNameFormOldDb(db_temp.tableName, ch.field) ||
                          (ch.component + ch.field).toLowerCase();
                        temp.field = ch.field;
                        temp.length = 200;
                        temp.dataType = 'varchar';
                        temp.columnDescription = ch.label;
                        // 主键
                        if (
                          ch.component == 'InputGuid' &&
                          temp.tableName === mainTableName &&
                          props.isAddVisible
                        ) {
                          temp.isPrimarykey = 1;
                        }
                        // componentProps
                        ch.componentProps.dataTable = temp.tableName;
                        ch.componentProps.fieldName = temp.dbColumnName;
                        ch.csType = 'string';

                        db_temp.dbColumnInfoList.push(temp);
                      }
                    }
                  });
                });
              }
              // 卡片
              else if (item.component == 'Card') {
                // 卡片布局的组件会自动进入主组件表内
              }
              // 栅格布局
              else if (item.component == 'Grid') {
                // 栅格布局的组件会进入主组件表内
              }
            } else {
              // 普通组件
              let temp = cloneDeep(dbColumnInfo);
              temp.tableName = db_temp.tableName.toLowerCase();
              temp.dbColumnName =
                getDbColumnNameFormOldDb(db_temp.tableName, item.field) ||
                (item.component + item.field).toLowerCase();
              temp.field = item.field;
              temp.length = 200;
              temp.dataType = 'varchar';
              temp.columnDescription = item.label;
              // 主键
              if (
                item.component == 'InputGuid' &&
                temp.tableName === mainTableName &&
                props.isAddVisible
              ) {
                temp.isPrimarykey = 1;
              }
              // componentProps
              item.componentProps.dataTable = temp.tableName;
              item.componentProps.fieldName = temp.dbColumnName;
              item.csType = 'string';

              // 主表不添加重复的普通组件（编辑情况下的栅格）
              let gridFlag = true;
              db_temp.dbColumnInfoList.forEach((dbColumn) => {
                if (dbColumn.dbColumnName == temp.dbColumnName) {
                  gridFlag = false;
                }
              });
              if (gridFlag) {
                db_temp.dbColumnInfoList.push(temp);
              }
            }
          }
          schemas[index] = item;
        });
        if (gridType == 'main') {
          scheme.formInfo.tabList[i].schemas = schemas;
        } else if (gridType == 'Tabs') {
          scheme = schemas;
        }
      });
      if (gridType == 'main') {
        // 筛掉重复项
        let dbFlag = true;
        db_list.value.forEach((db) => {
          if (db.tableName == db_temp.tableName) {
            dbFlag = false;
          }
        });
        if (dbFlag) {
          db_list.value.unshift(db_temp);
        }
      }
    }

    // 子表-table
    if (type == 'chlid') {
      let mainEach: any = [];
      if (gridType == 'chlid') {
        mainEach = scheme.columns;
      } else if (gridType == 'Tabs') {
        let temp: any = [];
        temp.push(scheme);
        mainEach.push({
          children: temp,
        });
      } else if (gridType == 'Card') {
        let temp: any = [];
        temp.push(scheme);
        mainEach.push({
          children: temp,
        });
      }
      // 子表
      mainEach.forEach((sch, i) => {
        schemas = sch.children;
        schemas?.forEach((item: any, index: number) => {
          // 过滤分割线、按钮
          if (item.component && !notComponentArray.includes(item.component)) {
            if (mapGeomArray == item.component) {
              // 子表-线索组件
              item.componentProps.dataTable = db_temp.tableName;
              item.componentProps.fieldName = 'gid';
              item.csType = 'string';
              // item.componentProps.fieldName = 'geom';
            } else if (item.component == 'Grid' && item.type == 'subTable') {
              // 子表-递归
              let res = getSchemeByscheme(
                item,
                dbCode,
                'chlid',
                schemedb,
                mainTableName,
                item.componentProps.dataTable || undefined,
                'chlid',
                cloneDeep(tableInfo),
              );
              item.componentProps.dataTable =
                res?.columns[0]?.children[0]?.componentProps?.dataTable;
              item.csType = 'string';
            } else if (gridArray.includes(item.component)) {
              // 选项卡
              if (item.component == 'Tabs') {
                item.componentProps.options.forEach((op) => {
                  op.children.forEach((ch) => {
                    // 过滤分割线、按钮
                    if (ch.component && !notComponentArray.includes(ch.component)) {
                      // 选项卡-子表-递归
                      if (ch.component == 'Grid' && ch.type == 'subTable') {
                        let res = getSchemeByscheme(
                          ch,
                          dbCode,
                          'chlid',
                          schemedb,
                          mainTableName,
                          ch.componentProps.dataTable || undefined,
                          'Tabs',
                          cloneDeep(tableInfo),
                        );
                        ch.componentProps.dataTable =
                          res?.columns[0]?.children[0]?.componentProps?.dataTable;
                        ch.csType = 'string';
                      }
                      // 选项卡-线索组件/布局组件
                      else if (mapGeomArray == ch.component || gridArray.includes(ch.component)) {
                        getSchemeByscheme(
                          ch,
                          dbCode,
                          'chlid',
                          schemedb,
                          mainTableName,
                          ch.componentProps.dataTable || undefined,
                          'Tabs',
                          db_temp,
                        );
                      }
                      // 选项卡-普通组件
                      else {
                        let temp = cloneDeep(dbColumnInfo);
                        temp.tableName = db_temp.tableName.toLowerCase();
                        temp.dbColumnName =
                          getDbColumnNameFormOldDb(db_temp.tableName, ch.field) ||
                          (ch.component + ch.field).toLowerCase();
                        temp.field = ch.field;
                        temp.length = 200;
                        temp.dataType = 'varchar';
                        temp.columnDescription = ch.label;
                        // componentProps
                        ch.componentProps.dataTable = temp.tableName;
                        ch.componentProps.fieldName = temp.dbColumnName;
                        ch.csType = 'string';

                        db_temp.dbColumnInfoList.push(temp);
                      }
                    }
                  });
                });
              }
              // 卡片布局
              else if (item.component == 'Card') {
                item.columns[0].children.forEach((ch) => {
                  // 过滤分割线、按钮
                  if (ch.component && !notComponentArray.includes(ch.component)) {
                    // 卡片布局-子表-递归
                    if (ch.component == 'Grid' && ch.type == 'subTable') {
                      let res = getSchemeByscheme(
                        ch,
                        dbCode,
                        'chlid',
                        schemedb,
                        mainTableName,
                        ch.componentProps.dataTable || undefined,
                        'Card',
                        cloneDeep(tableInfo),
                      );
                      ch.componentProps.dataTable =
                        res?.columns[0]?.children[0]?.componentProps?.dataTable;
                      ch.csType = 'string';
                    }
                    // 卡片布局-线索组件/布局组件
                    else if (mapGeomArray == ch.component || gridArray.includes(ch.component)) {
                      getSchemeByscheme(
                        ch,
                        dbCode,
                        'chlid',
                        schemedb,
                        mainTableName,
                        ch.componentProps.dataTable || undefined,
                        'Card',
                        db_temp,
                      );
                    }
                    // 卡片布局-普通组件
                    else {
                      let temp = cloneDeep(dbColumnInfo);
                      temp.tableName = db_temp.tableName.toLowerCase();
                      temp.dbColumnName =
                        getDbColumnNameFormOldDb(db_temp.tableName, ch.field) ||
                        (ch.component + ch.field).toLowerCase();
                      temp.field = ch.field;
                      temp.length = 200;
                      temp.dataType = 'varchar';
                      temp.columnDescription = ch.label;
                      // componentProps
                      ch.componentProps.dataTable = temp.tableName;
                      ch.componentProps.fieldName = temp.dbColumnName;
                      ch.csType = 'string';

                      db_temp.dbColumnInfoList.push(temp);
                    }
                  }
                });
              }
              // 栅格布局
              else if (item.component == 'Grid') {
                item.columns.forEach((col) => {
                  col.children.forEach((ch) => {
                    // 过滤分割线、按钮
                    if (ch.component && !notComponentArray.includes(ch.component)) {
                      // 栅格布局-子表-递归
                      if (ch.component == 'Grid' && ch.type == 'subTable') {
                        let res = getSchemeByscheme(
                          ch,
                          dbCode,
                          'chlid',
                          schemedb,
                          mainTableName,
                          ch.componentProps.dataTable || undefined,
                          'Grid',
                          cloneDeep(tableInfo),
                        );
                        ch.componentProps.dataTable =
                          res?.columns[0]?.children[0]?.componentProps?.dataTable;
                        ch.csType = 'string';
                      }
                      // 栅格布局-线索组件/布局组件
                      else if (mapGeomArray == ch.component || gridArray.includes(ch.component)) {
                        getSchemeByscheme(
                          ch,
                          dbCode,
                          'chlid',
                          schemedb,
                          mainTableName,
                          ch.componentProps.dataTable || undefined,
                          'Grid',
                          db_temp,
                        );
                      }
                      // 栅格布局-普通组件
                      else {
                        let temp = cloneDeep(dbColumnInfo);
                        temp.tableName = db_temp.tableName.toLowerCase();
                        temp.dbColumnName =
                          getDbColumnNameFormOldDb(db_temp.tableName, ch.field) ||
                          (ch.component + ch.field).toLowerCase();
                        temp.field = ch.field;
                        temp.length = 200;
                        temp.dataType = 'varchar';
                        temp.columnDescription = ch.label;
                        // componentProps
                        ch.componentProps.dataTable = temp.tableName;
                        ch.componentProps.fieldName = temp.dbColumnName;
                        ch.csType = 'string';
                        db_temp.dbColumnInfoList.push(temp);
                      }
                    }
                  });
                });
              }
              // 卡片组
              else if (item.component == 'CardGroup') {
                item.componentProps.options.forEach((op) => {
                  let children_CardGroup = op.children;
                  children_CardGroup.forEach((ch) => {
                    // 过滤分割线、按钮
                    if (ch.component && !notComponentArray.includes(ch.component)) {
                      // 卡片组-子表-递归
                      if (ch.component == 'Grid' && ch.type == 'subTable') {
                        let res = getSchemeByscheme(
                          ch,
                          dbCode,
                          'chlid',
                          schemedb,
                          mainTableName,
                          ch.componentProps.dataTable || undefined,
                          'Grid',
                          cloneDeep(tableInfo),
                        );
                        ch.componentProps.dataTable =
                          res?.columns[0]?.children[0]?.componentProps?.dataTable;
                        ch.csType = 'string';
                      }
                      // 卡片组-线索组件/布局组件
                      else if (mapGeomArray == ch.component || gridArray.includes(ch.component)) {
                        getSchemeByscheme(
                          ch,
                          dbCode,
                          'chlid',
                          schemedb,
                          mainTableName,
                          ch.componentProps.dataTable || undefined,
                          'Grid',
                          db_temp,
                        );
                      }
                      // 卡片组-普通组件
                      else {
                        let temp = cloneDeep(dbColumnInfo);
                        temp.tableName = db_temp.tableName.toLowerCase();
                        temp.dbColumnName =
                          getDbColumnNameFormOldDb(db_temp.tableName, ch.field) ||
                          (ch.component + ch.field).toLowerCase();
                        temp.field = ch.field;
                        temp.length = 200;
                        temp.dataType = 'varchar';
                        temp.columnDescription = ch.label;
                        // componentProps
                        ch.componentProps.dataTable = temp.tableName;
                        ch.componentProps.fieldName = temp.dbColumnName;
                        ch.csType = 'string';

                        db_temp.dbColumnInfoList.push(temp);
                      }
                    }
                  });
                });
              }
            }
            // 子表-普通组件
            else {
              let temp = cloneDeep(dbColumnInfo);
              temp.tableName = db_temp.tableName.toLowerCase();
              temp.dbColumnName =
                getDbColumnNameFormOldDb(db_temp.tableName, item.field) ||
                (item.component + item.field).toLowerCase();
              temp.field = item.field;
              temp.length = 200;
              temp.dataType = 'varchar';
              temp.columnDescription = item.label;
              // componentProps
              item.componentProps.dataTable = temp.tableName;
              item.componentProps.fieldName = temp.dbColumnName;
              item.csType = 'string';

              db_temp.dbColumnInfoList.push(temp);
            }
          }
          schemas[index] = item;
        });
        if (gridType == 'chlid') {
          scheme.columns[i].children = schemas;
        } else if (gridType == 'Tabs') {
          console.log(schemas);
        }
      });
      if (gridType == 'chlid') {
        // 筛掉重复项
        let dbFlag = true;
        db_list.value.forEach((db) => {
          if (db.tableName == db_temp.tableName) {
            dbFlag = false;
          }
        });
        if (dbFlag) {
          db_list.value.push(db_temp);
        }
      }
    }
    return scheme;
  }

  // 切换旧的db到新分析的db上
  function replaceOldDb() {
    // 上一次保存的db的表名
    let oldTableNameArray = oldDb.map((old) => old.tableName);
    // 遍历新分析的表单db信息
    db_list.value.forEach((db, db_index) => {
      // 是旧表
      if (oldTableNameArray.includes(db.tableName)) {
        let oldTable = oldDb.find((old) => {
          return old.tableName == db.tableName;
        });
        // 遍历
        db.dbColumnInfoList?.forEach((dbColumn, dbColumn_index) => {
          oldTable.dbColumnInfoList?.forEach((oldDbColumn) => {
            if (dbColumn.dbColumnName == oldDbColumn.dbColumnName) {
              // 把保存过的长度和数据格式（默认varchar）赋值给新分析的表格
              db_list.value[db_index].dbColumnInfoList[dbColumn_index] = oldDbColumn;
            }
          });
        });
      }
    });
  }
  // 获取上一次保存的字段名
  function getDbColumnNameFormOldDb(tableName, field) {
    let dbColumnNameFromOldDb = '';
    oldDb.forEach((old) => {
      if (old.tableName == tableName) {
        old.dbColumnInfoList.forEach((dbColumnInfo) => {
          if (dbColumnInfo.field == field) {
            dbColumnNameFromOldDb = dbColumnInfo.dbColumnName;
          }
        });
      }
    });
    return dbColumnNameFromOldDb;
  }

  // 提交
  async function submit() {
    // 检测：数据表名和字段名
    let results = checkTablesAndWarn();
    const checkflag = (await results).some(Boolean);
    if (checkflag) {
      return;
    }

    // 表名变化后修改表单里的表名
    db_list.value.forEach((db, db_index) => {
      if (db.name != db.tableName) {
        // scheme
        let scheme_replace = saveFormDatas.scheme.scheme;
        scheme_replace = replaceInJsonTableName(scheme_replace, db.name, db.tableName);
        saveFormDatas.scheme.scheme = scheme_replace;

        // db
        db.name = db.tableName;
        db.dbColumnInfoList?.forEach((d, d_index) => {
          d.tableName = db.tableName;
          db.dbColumnInfoList[d_index] = d;
        });
        db_list.value[db_index] = db;
      }
    });

    // 设置子表的relationField
    getRelationField();

    if (props.isAddVisible) {
      db_list.value.forEach(async (db) => {
        // 新增
        await AddTable(db);
      });
    } else {
      // 旧表单的表格名的数组
      let oldTableNameArray = oldDb.map((old) => old.tableName);
      db_list.value.forEach(async (db) => {
        // 是新建立的子表
        if (!oldTableNameArray.includes(db.tableName)) {
          await AddTable(db);
        } else {
          //遍历旧的表格列表
          oldDb.forEach((old) => {
            // 找到同名字的表格
            if (old.tableName == db.tableName) {
              // 旧表单的表格的列名的数组
              let oldDbColumnArray = old.dbColumnInfoList.map((o) => o.dbColumnName);
              db.dbColumnInfoList.forEach(async (dbColumn) => {
                if (!oldDbColumnArray.includes(dbColumn.dbColumnName)) {
                  dbColumn.isNullable = 1;
                  let query: any = {
                    dbCode: forminfoDbCode || 'hcsystemdb',
                    dbColumn: dbColumn,
                  };
                  await AddColumn(query);
                }
              });
            }
          });
        }
      });
    }
    // 把弹窗的信息写入saveFormDatas
    getFromAndTable();
  }

  // 检测：数据库是否有此表
  async function checkTablesAndWarn() {
    const promises = db_list.value.map(async (db) => {
      let flag = false;
      if (isNewTable(db)) {
        // 删除两端空格、制表符和换行符
        db.tableName = db.tableName.trim();

        // 检测：表名
        if (!db.tableName) {
          createMessage.warn('表名是必填项!');
          flag = true;
        }

        // 检测：数据库表名的命名规则
        if (db.tableName && !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(db.tableName)) {
          createMessage.warn('表名不符合数据库表名的命名规则!');
          flag = true;
        }

        // 检测：数据库是否有此表
        if (db.tableName) {
          let query: any = { tableName: db.tableName };
          let res = await CheckTableExist(query);
          if (res) {
            createMessage.warn('数据库已有表' + db.tableName);
            flag = true;
          }
        }

        if (!flag) {
          let dbColumns: any = [];
          // 检测：行
          db.dbColumnInfoList.forEach((dbColumn) => {
            // 删除两端空格、制表符和换行符
            dbColumn.dbColumnName = dbColumn.dbColumnName.trim();

            // 检测：字段名不为空
            if (!dbColumn.dbColumnName) {
              createMessage.warn('字段名不能为空!');
              flag = true;
            }

            // 检测：字段名中不能含有中文!
            if (dbColumn.dbColumnName && /[\u4e00-\u9fa5]/.test(dbColumn.dbColumnName)) {
              createMessage.warn('字段名中不能含有中文!');
              flag = true;
            }

            // 检测：数据库字段名的命名规则
            if (dbColumn.dbColumnName && !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(dbColumn.dbColumnName)) {
              createMessage.warn('字段名不符合数据库字段名的命名规则!');
              flag = true;
            }

            // 检测：字段名不能重复
            if (dbColumn.dbColumnName && !dbColumns.includes(dbColumn.dbColumnName)) {
              dbColumns.push(dbColumn.dbColumnName);
            } else {
              createMessage.warn('同表内的字段名不能重复!');
              flag = true;
            }
          });
        }
      }
      return flag;
    });

    const results = await Promise.all(promises);
    return results;
  }

  // 表名变化后修改表单里的表名
  function replaceInJsonTableName(jsonString, itemToReplace, newItem) {
    // 使用动态生成的正则表达式进行全局替换
    // 注意需要对itemToReplace中的特殊字符进行转义
    let escapedItem = ('"dataTable":"' + itemToReplace + '"').replace(
      /[-/\\^$*+?.()|[\]{}]/g,
      '\\$&',
    );
    let regex = new RegExp(escapedItem, 'g');
    let replacedJsonString = jsonString.replace(regex, '"dataTable":"' + newItem + '"');
    return replacedJsonString;
  }

  // 当前获取焦点的字段名
  let focusDbColumnName = '';
  // 字段名变化后修改表单里的字段名
  function replaceInJsonDbColumnName(newItem) {
    // 使用动态生成的正则表达式进行全局替换
    // 注意需要对focusDbColumnName中的特殊字符进行转义
    let scheme_replace = saveFormDatas.scheme.scheme;
    let escapedItem = ('"fieldName":"' + focusDbColumnName + '"').replace(
      /[-/\\^$*+?.()|[\]{}]/g,
      '\\$&',
    );
    let regex = new RegExp(escapedItem, 'g');
    saveFormDatas.scheme.scheme = scheme_replace.replace(regex, '"fieldName":"' + newItem + '"');
  }

  // 设置子表的relationField
  function getRelationField() {
    // 确定primaryKey
    if (db_list.value[0].dbColumnInfoList.length > 0) {
      db_list.value.forEach((item) => {
        item.dbColumnInfoList.forEach((i) => {
          if (i.isPrimarykey == 1) {
            primaryKey = i.dbColumnName;
          }
        });
      });
    }
    // 设置relationField
    let schems = JSON.parse(saveFormDatas.scheme.scheme);
    schems.primaryKey = primaryKey;
    db_list.value.forEach((item) => {
      if (item.type == 'chlid') {
        item.relationField = primaryKey;
      }
    });
    schems.db = db_list.value;
    saveFormDatas.scheme.scheme = JSON.stringify(schems);
  }

  // submit提交关闭的
  const isCloseSubmit = ref(false);
  // 把弹窗的信息写入saveFormDatas
  function getFromAndTable() {
    let schems = JSON.parse(saveFormDatas.scheme.scheme);
    // db
    schems.db = db_list.value;
    schems.db.forEach((item) => {
      if (item.type == 'chlid') {
        item.relationField = primaryKey;
      }
    });
    saveFormDatas.scheme.scheme = JSON.stringify(schems);
    emit('automatic-modal-submitsuccess', saveFormDatas);
    isCloseSubmit.value = true;
    closeModalDeleteGrid();
  }

  // 非提交关闭窗口时，栅格布局清除取出来的表单组件删除掉
  function closeModalDeleteGrid() {
    // 非提交
    if (!isCloseSubmit.value) {
      let scheme_close = JSON.parse(saveFormDatas.scheme.scheme);
      let tabList_close = scheme_close.formInfo.tabList;
      // tabList遍历
      tabList_close.forEach((list, list_index) => {
        let schemas_temp: any = [];
        let schemas_close = list.schemas;
        // schemas遍历
        schemas_close.forEach((sch) => {
          if (!sch.ptype || sch.ptype != 'gridlayout') {
            // schemas添加
            schemas_temp.push(sch);
          }
        });
        tabList_close[list_index].schemas = schemas_temp;
      });
      // scheme赋值
      scheme_close.formInfo.tabList = tabList_close;
      saveFormDatas.scheme.scheme = JSON.stringify(scheme_close);
    }
    closeModal();
  }

  // 数据格式（默认varchar）变化后修改字段长度
  function isBoolChangeLength(record: Recordable) {
    if (record.dataType == 'bool') {
      record.length = 0;
    } else {
      record.length = 200;
    }
  }

  // 判定是否是新建的表格
  function isNewTable(item: any) {
    let flag = true;
    oldDb.forEach((old) => {
      if (old.tableName == item.tableName) {
        flag = false;
      }
    });
    return flag;
  }

  // 判定是否是新建的组件
  function isNewFormItem(item: any) {
    let flag = true;
    oldDb?.forEach((old) => {
      old?.dbColumnInfoList?.forEach((li) => {
        if (li.dbColumnName == item.dbColumnName) {
          flag = false;
        }
      });
    });
    // 线索组件特殊处理
    if (['gid', 'geom'].includes(item.dbColumnName)) {
      flag = false;
    }
    return flag;
  }
</script>
