<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    :title="getTitle"
    :width="adaptiveWidth"
    @ok="handleSubmit"
    :showFooter="showFooter"
    destroyOnClose
  >
    <BasicForm @register="registerForm">
      <template #pwd="{ model, field }">
        <a-row :gutter="8">
          <a-col :sm="15" :md="16" :lg="17" :xl="19">
            <a-input-password v-model:value="model[field]" placeholder="请输入密码" />
          </a-col>
          <a-col :sm="9" :md="7" :lg="7" :xl="5">
            <a-button type="primary" style="width: 100%" @click="handleTest">测试</a-button>
          </a-col>
        </a-row>
      </template>
      <template #departSelect ="{model,field}">
        <a-select v-model:value="model[field]" :disabled="model['id']!=null" @change="(value,option) => handleChange(value,model)">
          <template v-for="item in departOptions" :key="`${item.code}`">
            <a-select-option :value="item.code" :label="item.departName">
              {{item.departName}}
            </a-select-option>
          </template>
        </a-select>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>

<script lang="ts" setup>
  import { defineComponent, ref, computed, unref, useAttrs } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useDrawerAdaptiveWidth } from '/@/hooks/jeecg/useAdaptiveWidth';
  import { formSchema } from './datasource.data';
  import { saveOrUpdateDataSource, getDataSourceById, testConnection, queryDeparts } from './datasource.api';
  import {useMessage} from "@/hooks/web/useMessage";
  const { createMessage } = useMessage();
  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  const attrs = useAttrs();
  const isUpdate = ref(true);
  const rowId = ref('');
  let isFormDepartUser = false;
  //表单配置
  const [registerForm, { setProps, resetFields, validateFields, getFieldsValue, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 90,
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  const showFooter = ref(true);
  const departOptions = ref<any[]>([]);
  //表单赋值
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields();
    showFooter.value = data?.showFooter ?? true;
    setDrawerProps({ confirmLoading: false, showFooter: showFooter.value });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)){
      await getDepartOptions('');
    }else{
      await getDepartOptions('1');
    }

    if (unref(isUpdate)) {

      //获取详情
      data.record = await getDataSourceById({ id: data.record.id });
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !showFooter.value });
  });
  //获取标题
  const getTitle = computed(() => {
    if (!unref(isUpdate)) {
      return '新增数据源';
    } else {
      return unref(showFooter) ? '编辑数据源' : '数据源详情';
    }
  });
  const { adaptiveWidth } = useDrawerAdaptiveWidth();

  async function getDepartOptions(addFLag){
    departOptions.value = [];
    const data = await queryDeparts({ addFLag : addFLag });
    Object.assign(departOptions.value, data);
  }

  async function handleChange(value,formData){
    if(value == null){
      formData["code"] = "";
    }else{
      formData["code"] = value;
    }
  }

  async function handleTest() {
    let keys = ['dbType', 'dbDriver', 'dbUrl', 'dbName', 'dbUsername', 'dbPassword'];
    // 获取以上字段的值，并清除校验状态
    let fieldsValues = getFieldsValue(keys);
    let setFields = {};
    keys.forEach((key) => (setFields[key] = { value: fieldsValues[key], errors: null }));
    await validateFields(keys).then((values) => {
      let loading = createMessage.loading('连接中....', 0);
      testConnection(values)
        .then((data) => {
          if (data.success) {
            createMessage.success('连接成功');
          }
        })
        .catch((error) => {})
        .finally(() => loading());
    });
  }

  //提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      setDrawerProps({ confirmLoading: true });
      await saveOrUpdateDataSource(values, isUpdate.value);
      //关闭弹窗
      closeDrawer();
      //刷新列表
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

</script>

<style scoped>

</style>
