<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :canFullscreen="false"
    :defaultFullscreen="false"
    :maskClosable="false"
    :width="800"
    title="添加SQL"
    @ok="modalSuReClick"
  >
    <BasicForm ref="myDataBaseFormRef" @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSqlSchema } from './index.data';
  import { message } from 'ant-design-vue';
  import { addFormSqlData } from '@/api/formdesign/index';

  const emit = defineEmits(['backrows']);
  const receiveParam = ref();

  const [registerModal, { closeModal }] = useModalInner((data: any) => {
    receiveParam.value = data;
    setFieldsValue({});
  });

  const [registerForm, { getFieldsValue, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    schemas: formSqlSchema,
    showActionButtonGroup: false,
    baseColProps: { lg: 24, md: 24 },
  });

  function modalSuReClick() {
    let objData = getFieldsValue();
    let param = {
      dbCode: receiveParam.value.DbCode,
      sql: objData.sql,
    };
    validate();
    if (objData.name && objData.sql) {
      addFormSqlData(param).then((res: Recordable) => {
        let arr: any = [];
        res.forEach((item) => {
          arr.push({
            label: item,
            value: item,
          });
        });
        let backObj = {
          name: objData.name,
          sql: objData.sql,
          columns: arr,
          basetable: '',
        };
        if (receiveParam.value.length > 0) {
          if (objData.sql.includes('where')) {
            backObj.basetable = objData.sql.split('from ')[1].split(' where')[1];
          } else {
            message.warning('请在语句中设置关联参数');
            return;
          }
        } else {
          backObj.basetable = objData.sql.split('from ')[1];
        }

        emit('backrows', backObj);
        closeModal();
      });
    }

    //  emit('backrows', rows);
    //  closeModal()
  }
</script>
<style lang="less"></style>
