<script lang="ts" setup>
import { onMounted, reactive, ref, unref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter';
import { EnumApi, TenantApi } from '#/api';
import { type BasicOptionResult, dbTypeOptions } from '#/api/model';

defineOptions({
  name: 'TenantEdit',
});
const emit = defineEmits(['success']);
const modelRef = ref<Record<string, any>>({});
const isUpdate = ref(true);

const state = reactive<{
  tenantTypeOptions: BasicOptionResult[];
}>({
  tenantTypeOptions: [],
});

const [Form, { validate, setValues, getValues, updateSchema }] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'RadioGroup',
      componentProps: {
        options: [],
      },
      fieldName: 'tenantType',
      label: '租户类型',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'name',
      label: '租户名称',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'adminAccount',
      label: '管理员',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'phone',
      label: '联系电话',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'email',
      label: '电子邮箱',
      rules: 'required',
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'sort',
      label: '排序',
      rules: 'required',
    },
    {
      component: 'Select',
      componentProps: {
        placeholder: '请输入',
        options: dbTypeOptions,
      },
      dependencies: {
        show(values) {
          return values.tenantType === 1;
        },
        triggerFields: ['tenantType'],
      },
      fieldName: 'dbType',
      label: '数据库类型',
      rules: 'required',
      formItemClass: 'col-span-2 items-baseline',
    },
    {
      component: 'Textarea',
      componentProps: {
        placeholder: '请输入',
      },
      dependencies: {
        show(values) {
          return values.tenantType === 1;
        },
        triggerFields: ['tenantType'],
      },
      fieldName: 'connection',
      label: '连接字符串',
      rules: 'required',
      formItemClass: 'col-span-2 items-baseline',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'remark',
      label: '备注',
      formItemClass: 'col-span-2 items-baseline',
    },
  ],
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const [Modal, { close, setState, getData }] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    close();
  },
  onConfirm: async () => {
    try {
      const { valid } = await validate();
      if (valid) {
        const values = await getValues();
        setState({ confirmLoading: true });
        const postParams = unref(modelRef);
        Object.assign(postParams, values);
        await (unref(isUpdate)
          ? TenantApi.editDetail(postParams as TenantApi.RecordItem)
          : TenantApi.addDetail(postParams as TenantApi.BasicRecordItem));
        message.success('操作成功');

        close();
        emit('success');
      }
    } catch {
      message.error('操作失败');
    } finally {
      setState({ confirmLoading: false });
    }
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      setState({ loading: true });
      const data = getData<Record<string, any>>();
      isUpdate.value = !!data.isUpdate;
      modelRef.value = { ...data.baseData };
      setState({ title: unref(isUpdate) ? '编辑租户' : '新增租户' });

      if (unref(isUpdate)) {
        const entity = await TenantApi.getDetail(data.baseData.id);
        modelRef.value = { ...entity };
        setValues(entity);
      }
      setState({ loading: false });
    }
  },
  title: '新增租户',
});

onMounted(async () => {
  state.tenantTypeOptions = await EnumApi.getList(EnumApi.EnumType.TenantType);

  updateSchema([
    {
      fieldName: 'tenantType',
      componentProps: {
        options: state.tenantTypeOptions,
      },
    },
  ]);
});
</script>
<template>
  <Modal class="w-[1000px]">
    <Form />
  </Modal>
</template>
