<template>
  <div class="l-from-body">
    <a-form
      ref="formRef"
      :rules="data.rules"
      :model="formData"
      labelAlign="left"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item label="条件名称" name="name">
        <a-input v-model:value="formData.name" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="数据库" name="dbCode">
        <a-select
          v-model:value="formData.dbCode"
          placeholder="请选择"
          :options="sqlOptions"
          :field-names="{ label: 'text', value: 'id', options: 'childNodes' }"
        />
      </a-form-item>
      <a-form-item label="SQL语句" name="sql">
        <a-textarea v-model:value="formData.sql" placeholder="请输入" :rows="4" />
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
  import { reactive, ref, onMounted } from 'vue';
  import { getLoadDataBaseLinkTree } from '@/api/demo/system';

  const labelCol = { span: 5 };
  const wrapperCol = { span: 17 };
  const formRef = ref<any>();
  let formData: any = ref({});
  const props = defineProps({
    propsData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });
  formData.value = props.propsData;
  const data = reactive({
    rules: {
      dbCode: [{ required: true, message: '请选择数据库' }],
      sql: [{ required: true, message: '请填写sql语句' }],
      name: [{ required: true, message: '请填写条件名称' }],
    },
  });
  const sqlOptions = ref([]);
  async function getSQL() {
    const data = await getLoadDataBaseLinkTree();
    let res: any = [];
    data.forEach((element) => {
      if (element.childNodes == null) {
        element.childNodes = [];
      }
      let point = {};
      if (element.id == 'hcsystemdb') {
        point = {
          id: '1',
          text: '常用数据库',
          childNodes: [
            {
              id: element.id,
              text: element.text,
            },
          ],
        };
        res.push(point);
      } else {
        res.push(element);
      }
    });
    sqlOptions.value = res;
  }
  function setForm(data) {
    formData.value = data;
  }
  // 校验表单
  function validateForm() {
    formRef.value
      .validate()
      .then(async () => {
        return true;
      })
      .catch(async () => {
        return false;
      });
  }
  function getForm() {
    return formData.value;
  }
  defineExpose({
    getForm,
    validateForm,
    setForm,
  });
  onMounted(() => {
    getSQL();
  });
</script>
<style scoped>
  .l-from-body {
    padding: 10px 30px;
  }
</style>
