<template>
  <BasicModal
    v-bind="$attrs"
    @register="automaticModal"
    title="表结构配置"
    width="60%"
    maxHeight="80%"
    @fullscreen="onFullscreen"
    :showCancelBtn="true"
    :showOkBtn="true"
    :useWrapper="false"
    @ok="submit"
    @visible-change="
      () => {
        dbTableInfo_new = [];
        dbTableInfo_new_list = [];
        dbColumnInfo_new = [];
        dbColumnInfo_new_list = [];
        dbColumnInfo_new_children = [];
        dbColumnInfo_new_children_list = [];
      }
    "
  >
    <a-alert message="主表的字段名可进行修改，数据格式默认为 varchar" type="info" />
    <a-alert
      message="* 表名、字段名由数字、字母或下划线组成，且不能以数字，特殊字符串开头。"
      type="error"
    />
    <a-alert message="* 表名、字段名一旦生成不可修改。" type="error" />
    <a-alert message="自动建表内的图斑组件有专用geom字段负责，无需配置" type="info" />
    <a-divider />

    <BasicTable
      @register="dbMainTable"
      :columns="dbMainColumns"
      :canResize="false"
      :bordered="true"
      :showTableSetting="false"
      :pagination="false"
      :autoCreateKey="false"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'tableName'">
          <div>
            <a-input
              v-model:value="record.tableName"
              :disabled="!props.isAddVisible && !dbTableInfo_new_list.includes(record.tableName)"
              @change="record.name = record.tableName"
            />
          </div>
        </template>
        <template v-if="column.key === 'description'">
          <div>
            <a-input v-model:value="record.description" placeholder="请输入备注" />
          </div>
        </template>
      </template>
    </BasicTable>

    <CollapseContainer title="主表">
      <BasicTable
        @register="dbColumnInfoTable"
        :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="
                  !props.isAddVisible &&
                  !dbColumnInfo_new_list.includes(record.dbColumnName + record.columnDescription)
                "
              />
            </div>
          </template>
          <template v-if="column.key === 'length'">
            <div>
              <a-input v-model:value="record.length" defaultValue="200" />
            </div>
          </template>
          <template v-if="column.key === 'dataType'">
            <div>
              <a-select
                ref="select"
                placeholder="请选择"
                size="small"
                v-model:value="record.dataType"
                :options="dataTypeOptions"
                style="width: 100%; text-align: left"
              />
            </div>
          </template>
        </template>
      </BasicTable>
    </CollapseContainer>
    <div v-for="item in tableInfo_list" :key="item.tableName">
      <CollapseContainer title="子表">
        <BasicTable
          :dataSource="item.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="
                    !props.isAddVisible &&
                    !dbColumnInfo_new_children_list.includes(
                      record.dbColumnName + record.columnDescription,
                    )
                  "
                />
              </div>
            </template>
            <template v-if="column.key === 'length'">
              <div>
                <a-input v-model:value="record.length" defaultValue="200" />
              </div>
            </template>
            <template v-if="column.key === 'dataType'">
              <div>
                <a-select
                  ref="select"
                  placeholder="请选择"
                  size="small"
                  v-model:value="record.dataType"
                  :options="dataTypeOptions"
                  style="width: 100%; text-align: left"
                />
              </div>
            </template>
          </template>
        </BasicTable>
      </CollapseContainer>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, defineProps } from 'vue';
  import { CollapseContainer } from '@/components/Container';
  import { BasicTable, useTable } from '@/components/Table';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { dbMainColumns, dbColumnInfoColumns } from './modelData';
  import { cloneDeep } from 'lodash-es';
  import { functionGetForm, AddTable, AddColumn } from '@/api/demo/formScheme';

  const emit = defineEmits(['automatic-modal-submitsuccess']);

  const props = defineProps({
    isAddVisible: {
      default: false,
      type: Boolean, //判断新增还是编辑
    },
  });
  // 数据
  let saveFormDatas;
  // 表结构-模板
  let tableInfo: any = {
    dbCode: '',
    tableName: '',
    description: '',
    type: '',
    dbColumnInfoList: [],
  };
  // 主表
  let tableInfo_main: any = {
    dbCode: '',
    tableName: '',
    description: '',
    type: '',
    dbColumnInfoList: [],
  };
  // 子表
  let tableInfo_list: any = ref([]);
  let scheme_chlid_db: any = [];
  let chlidNumber: number = 0;
  // 表结构初始值
  let dbColumnInfo = {
    tableName: '',
    dbColumnName: '',
    dataType: '',
    length: 0,
    columnDescription: '',
    isNullable: 0,
    isIdentity: 0,
    isPrimarykey: 0,
    decimalDigits: 0,
  };

  // 新增表
  let dbTableInfo_new: any = [];
  let dbTableInfo_new_list: any = [];
  // 新增列
  let dbColumnInfo_new: any = [];
  let dbColumnInfo_new_list: any = [];
  let dbColumnInfo_new_children: any = [];
  let dbColumnInfo_new_children_list: any = [];
  // 数据格式-下拉框
  let dataTypeOptions = [
    { label: '字符串', value: 'varchar' },
    { label: '长文本', value: 'text' },
    { label: '数字', value: 'int8' },
    { label: '是否', value: 'bool' },
    { label: '日期', value: 'timestamp' },
  ];
  // 不需要添加表结构的
  let notComponentArray = ['Divider'];
  let fieldArray = ['MapGeom'];
  let gridArray = ['Grid', 'ChildGrid'];

  const [dbMainTable, { getDataSource: dbMain_getDataSource, setTableData: dbMain_setTableData }] =
    useTable();

  const [dbColumnInfoTable, { setTableData: dbColumnInfo_setTableData }] = useTable();

  // 异步传参
  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;
      data.saveFormDatas.scheme.scheme = JSON.stringify(data_json);
    }
    console.log(data.saveFormDatas.scheme.scheme);

    // 表名和备注
    let scheme = JSON.parse(data.saveFormDatas.scheme.scheme);
    setDefaultValue(scheme);
    // 制作表格
    scheme = getSchemasReturnScheme(scheme, data.saveFormDatas.info.DbCode, 'father', '');

    // 表格赋值
    dbMain_setTableData(scheme.db.concat(scheme_chlid_db));
    dbColumnInfo_setTableData(tableInfo_main.dbColumnInfoList);
    saveFormDatas = data.saveFormDatas;
    saveFormDatas.scheme.scheme = JSON.stringify(scheme);
  });

  // 设置初始值
  function setDefaultValue(scheme) {
    tableInfo_list.value = [];
    scheme_chlid_db = [];
    chlidNumber = scheme ? scheme.db.length - 1 : 0;
    dbTableInfo_new = [];
    dbTableInfo_new_list = [];
    dbColumnInfo_new = [];
    dbColumnInfo_new_list = [];
    dbColumnInfo_new_children = [];
    dbColumnInfo_new_children_list = [];
  }

  // 制作表格
  function getSchemasReturnScheme(scheme: any, dbCode, type, mainTableName) {
    let schemas: any = '';
    let tableInfo_temp = cloneDeep(tableInfo);
    let chlid_db: any = {};
    if (type == 'father') {
      // 主表
      schemas = scheme.formInfo.schemas;
      tableInfo_temp.name = scheme.db[0].name || scheme.db[0].tableName;
      tableInfo_temp.tableName = scheme.db[0].tableName || scheme.db[0].name;
      tableInfo_temp.description = scheme.db[0].description || '主表';
      tableInfo_temp.type = 'main';
      tableInfo_temp.dbCode = dbCode;
      tableInfo_temp.dbColumnInfoList = [];
      mainTableName = tableInfo_temp.tableName;
    } else if (type == 'chlid') {
      schemas = scheme.columns[0].children;
      if (props.isAddVisible) {
        // 新增
        // 子表
        chlidNumber++;
        tableInfo_temp.name = mainTableName + '_grid' + chlidNumber;
        tableInfo_temp.tableName = tableInfo_temp.name;
        tableInfo_temp.description = '子表';
        tableInfo_temp.type = 'chlid';
        tableInfo_temp.dbCode = dbCode;
        tableInfo_temp.dbColumnInfoList = [];
        // 表名db
        chlid_db = {
          name: tableInfo_temp.name,
          tableName: tableInfo_temp.tableName,
          description: tableInfo_temp.description,
          type: tableInfo_temp.type,
          relationName: mainTableName,
        };
        scheme_chlid_db.push(chlid_db);
      } else {
        // 编辑
        if (scheme.columns[0].child_db) {
          tableInfo_temp = scheme.columns[0].child_db;
          tableInfo_temp.dbCode = dbCode;
          tableInfo_temp.dbColumnInfoList = [];
          chlid_db = scheme.columns[0].child_db;
        } else {
          // 新增
          // 子表
          chlidNumber++;
          tableInfo_temp.name = mainTableName + '_grid' + chlidNumber;
          tableInfo_temp.tableName = tableInfo_temp.name;
          tableInfo_temp.description = '子表';
          tableInfo_temp.type = 'chlid';
          tableInfo_temp.dbCode = dbCode;
          tableInfo_temp.dbColumnInfoList = [];
          // 表名db
          chlid_db = {
            name: tableInfo_temp.name,
            tableName: tableInfo_temp.tableName,
            description: tableInfo_temp.description,
            type: tableInfo_temp.type,
            relationName: mainTableName,
          };
          scheme_chlid_db.push(chlid_db);
          dbTableInfo_new.push(tableInfo_temp);
          dbTableInfo_new_list.push(tableInfo_temp.tableName);
        }
      }
    }

    schemas.forEach((item: any, index: number) => {
      // 过滤分割线
      if (!item.component.includes(notComponentArray)) {
        if (fieldArray.includes(item.field)) {
          // 图斑组件
          item.componentProps.dataTable = tableInfo_temp.tableName;
          item.componentProps.fieldName = 'geom';
        } else if (gridArray.includes(item.component)) {
          // 栅格组件-递归
          getSchemasReturnScheme(item, dbCode, 'chlid', mainTableName);
        } else if (!item.dbColumnInfo) {
          // 新增的组件-初始默认值
          let temp = cloneDeep(dbColumnInfo);
          temp.tableName = tableInfo_temp.tableName;
          temp.dbColumnName = item.component + item.field;
          temp.length = 200;
          temp.dataType = 'varchar';
          temp.columnDescription = item.label;
          item.dbColumnInfo = temp;

          // 编辑-添加新的行
          if (type == 'father') {
            dbColumnInfo_new.push(temp);
            dbColumnInfo_new_list.push(temp.dbColumnName + temp.columnDescription);
          } else if (type == 'chlid') {
            dbColumnInfo_new_children.push(temp);
            dbColumnInfo_new_children_list.push(temp.dbColumnName + temp.columnDescription);
          }
          item.componentProps.dataTable = tableInfo_temp.tableName;
          item.componentProps.fieldName = temp.dbColumnName;

          tableInfo_temp.dbColumnInfoList.push(temp);
        } else if (item.dbColumnInfo.dbColumnName != item.component + item.field) {
          // 复制按钮产生的组件
          // 初始默认值
          let temp = cloneDeep(dbColumnInfo);
          temp.tableName = tableInfo_temp.tableName;
          temp.dbColumnName = item.component + item.field;
          temp.length = 200;
          temp.dataType = 'varchar';
          temp.columnDescription = item.label;
          item.dbColumnInfo = temp;
          // 编辑-添加新的行
          if (type == 'father') {
            dbColumnInfo_new.push(temp);
            dbColumnInfo_new_list.push(temp.dbColumnName + temp.columnDescription);
          } else if (type == 'chlid') {
            dbColumnInfo_new_children.push(temp);
            dbColumnInfo_new_children_list.push(temp.dbColumnName + temp.columnDescription);
          }
          item.componentProps.dataTable = tableInfo_temp.tableName;
          item.componentProps.fieldName = temp.dbColumnName;

          tableInfo_temp.dbColumnInfoList.push(temp);
        } else {
          tableInfo_temp.dbColumnInfoList.push(item.dbColumnInfo);
        }
        schemas[index] = item;
      }
    });

    if (type == 'father') {
      tableInfo_main = tableInfo_temp;
    } else if (type == 'chlid') {
      tableInfo_list.value.push(tableInfo_temp);
    }

    if (type == 'father') {
      scheme.formInfo.schemas = schemas;
    } else if (type == 'chlid') {
      scheme.columns[0].children = schemas;
      scheme.columns[0].child_db = chlid_db;
    }

    return scheme;
  }

  // 提交
  async function submit() {
    // 主表
    if (props.isAddVisible) {
      // 新增
      await AddTable(tableInfo_main);
    } else if (dbColumnInfo_new_list.length == tableInfo_main.dbColumnInfoList.length) {
      // 暂存后-保存
      await AddTable(tableInfo_main);
    } else if (dbColumnInfo_new) {
      // 编辑
      dbColumnInfo_new?.forEach(async (item) => {
        await AddColumn(item);
      });
    }
    // 子表
    if (props.isAddVisible) {
      // 新增
      tableInfo_list.value?.forEach(async (e) => {
        await AddTable(e);
      });
    } else {
      if (dbTableInfo_new) {
        // 编辑-新增表
        dbTableInfo_new?.forEach(async (e) => {
          await AddTable(e);
        });
      }
      console.log(dbTableInfo_new_list);
      console.log(dbColumnInfo_new_children);
      if (dbColumnInfo_new_children) {
        // 编辑-新增行
        dbColumnInfo_new_children?.forEach(async (item) => {
          if (!dbTableInfo_new_list.includes(item.tableName)) {
            await AddColumn(item);
          }
        });
      }
    }
    setDefaultValue(null);
    getFromAndTable();
  }

  // 把弹窗的信息写入saveFormDatas
  function getFromAndTable() {
    let schems = JSON.parse(saveFormDatas.scheme.scheme);
    // db
    schems.db = dbMain_getDataSource();
    saveFormDatas.scheme.scheme = JSON.stringify(schems);
    emit('automatic-modal-submitsuccess', saveFormDatas);
    closeModal();
  }
</script>
