<script lang="ts" setup>
import type { DictEntity } from '@vben/types';

import { computed, ref } from 'vue';

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

import { ElMessage } from 'element-plus';

import { useVbenForm, z } from '#/adapter/form';
import { addDictApi, editDictApi, getDictDetailApi } from '#/api/dict';

const emit = defineEmits(['finish']);
const data = ref();
const formType = ref<'create' | 'detail' | 'edit'>('create');

const titleMap = {
  create: '新增配置',
  detail: '配置详情',
  edit: '编辑配置',
} as const;

const getTitle = computed(() => titleMap[formType.value]);

const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    labelWidth: 130,
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  wrapperClass: 'grid-cols-1 lg:grid-cols-2',
  schema: [
    {
      component: 'Input',
      fieldName: 'title',
      label: '配置名称',
      rules: z.string().min(1, '请输入配置名称'),
      componentProps: {
        placeholder: '请输入配置名称',
      },
    },
    {
      component: 'Input',
      fieldName: 'groupname',
      label: '组名称',
      componentProps: {
        placeholder: '请输入组名称',
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'baseid',
      label: '上级',
      defaultValue: 0,
      componentProps: {
        placeholder: '请输入上级ID',
        min: 0,
      },
    },
    {
      component: 'Switch',
      fieldName: 'available',
      label: '状态',
      defaultValue: 1,
      componentProps: {
        activeValue: 1,
        inactiveValue: 0,
        activeText: '可用',
        inactiveText: '不可用',
      },
    },
    {
      component: 'Switch',
      fieldName: 'ispublic',
      label: '前端可用',
      defaultValue: 0,
      componentProps: {
        activeValue: 1,
        inactiveValue: 0,
        activeText: '是',
        inactiveText: '否',
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'ranknum',
      label: '排序值',
      defaultValue: 0,
      componentProps: {
        placeholder: '请输入排序值',
        min: 0,
      },
    },
    {
      component: 'Input',
      fieldName: 'substance',
      label: '配置值',
      rules: z.string().min(1, '请输入配置值'),
      componentProps: {
        type: 'textarea',
        placeholder: '请输入配置值',
        rows: 4,
      },
      wrapperProps: {
        class: 'col-span-2',
      },
    },
    {
      component: 'Input',
      fieldName: 'describes',
      label: '描述',
      componentProps: {
        type: 'textarea',
        placeholder: '请输入描述',
        rows: 3,
      },
      wrapperProps: {
        class: 'col-span-2',
      },
    },
  ],
});

const [Modal, modalApi] = useVbenModal({
  class: 'w-8/12',
  onCancel() {
    modalApi.close();
  },
  async onConfirm() {
    // 校验输入的数据
    const formValues = await baseFormApi.getValues();
    const validate = await baseFormApi.validate();
    if (!validate.valid) {
      return;
    }

    try {
      const apiMap = {
        create: () => addDictApi(formValues as unknown as DictEntity),
        edit: () =>
          editDictApi({
            ...formValues,
            'id.value': data.value.row.id,
          } as unknown as DictEntity),
      };

      if (formType.value === 'detail') {
        modalApi.close();
        return;
      }

      await apiMap[formType.value]();
      ElMessage.success('操作成功');
      emit('finish');
      modalApi.close();
    } catch {}
  },
  async onOpenChange(isOpen) {
    if (isOpen) {
      data.value = modalApi.getData();

      formType.value = data.value.formType;

      baseFormApi.setState({
        commonConfig: { disabled: formType.value === 'detail' },
      });

      if (data.value.formType === 'create') {
        // 新增时设置默认值
        baseFormApi.setFieldValue('available', 1);
        baseFormApi.setFieldValue('ispublic', 0);
        baseFormApi.setFieldValue('baseid', 0);
        baseFormApi.setFieldValue('ranknum', 0);
        return;
      }

      try {
        modalApi.setState({ loading: true });
        const detailData = await getDictDetailApi({
          id: data.value.row.id,
        });

        baseFormApi.setValues(detailData);
      } catch {
        // console.log(error);
      }

      modalApi.setState({ loading: false });
    }
  },
});
</script>

<template>
  <Modal :title="getTitle">
    <BaseForm />
  </Modal>
</template>
