<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :centered="true"
    :canFullscreen="false"
    :defaultFullscreen="false"
    :showCancelBtn="true"
    :showOkBtn="true"
    :draggable="false"
    :title="getTitle"
    :useWrapper="true"
    @ok="handleOk"
  >
    <BasicForm ref="registerFormRef" @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, defineEmits } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { useMessage } from '@/hooks/web/useMessage';

  // ts
  import { formSchema } from './dbsource.data';
  // api
  import { fun_AddForm, fun_UpdateForm } from '@/api/demo/dbsource';

  const emit = defineEmits(['submit']);
  const { createMessage } = useMessage();

  // 是否是修改
  const isUpdate = ref(false);
  // 标题
  const getTitle = computed(() => (unref(isUpdate) ? '编辑数据源' : '新增数据源'));
  // 窗口
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false });
    isUpdate.value = data.isUpdate;
    if (isUpdate.value) {
      setFieldsValue(data.record);
    } else {
      validate();
      resetFields();
    }
  });

  // 表单form
  const registerFormRef = ref<any>();
  const [registerForm, { setFieldsValue, getFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { lg: 24, md: 24 },
  });

  // 提交
  async function handleOk() {
    validate();
    let record = getFieldsValue();
    let params = {
      code: record.code,
      name: record.name,
      dbId: record.dbId,
      sql: record.sql,
      description: record.description,
    };
    if (isUpdate.value) {
      // 修改
      params.id = record.id;
      params.createUserName = record.createUserName;
      params.createDate = record.createDate;
      let data = await fun_UpdateForm(params);
      if (data) {
        createMessage.success('修改成功!');
        closeModal();
        emit('submit');
      }
    } else {
      // 新增
      params.createUserName = localStorage.getItem('fireUserLoginName');
      params.createDate = new Date();
      let data = await fun_AddForm(params);
      if (data) {
        createMessage.success('新增成功！');
        closeModal();
        emit('submit');
      }
    }
  }
</script>

<style lang="less" scoped>
  .l-rblock {
    width: 60%;
    height: 60%;
    background-color: @border-color-base;

    &_content {
      box-sizing: border-box;
      position: relative;
      width: 100%;
      height: 100%;
      max-width: 794px;
      overflow: hidden auto;
      background: @component-background;
      border-radius: 4px;
      margin: auto;
      padding: 24px;
    }

    &_formLine {
      height: 50px;
    }
  }
</style>
