<script lang="ts" setup>
import type { RoleGroupEntity } 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 { addRoleApi, editRoleApi, getRoleDetailApi } from '#/api/role';

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: 120,
    // 所有表单项
    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: 'InputNumber',
    //   fieldName: 'group_sort',
    //   label: '排序',
    //   defaultValue: 0,
    //   componentProps: {
    //     placeholder: '请输入排序值',
    //     min: 0,
    //   },
    // },
    {
      component: 'Switch',
      fieldName: 'available',
      label: '状态',
      defaultValue: 1,
      componentProps: {
        activeValue: 1,
        inactiveValue: 0,
        activeText: '启用',
        inactiveText: '禁用',
      },
    },
    {
      component: 'Input',
      fieldName: 'details',
      label: '描述',
      componentProps: {
        type: 'textarea',
        placeholder: '请输入角色描述',
        rows: 4,
      },
    },
    {
      component: 'PermissionTree',
      fieldName: 'popedom',
      label: '权限设置',
      componentProps: {
        placeholder: '请选择权限',
      },
      // @ts-ignore wrapperProps属性在运行时有效，但类型定义中缺失
      wrapperProps: {
        class: 'col-span-2',
      },
      // @ts-ignore ifShow属性在运行时有效，但类型定义中缺失
      ifShow: ({ formType }: { formType: string }) => formType !== 'create',
    },
  ],
});

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: () => addRoleApi(formValues as unknown as RoleGroupEntity),
        edit: () =>
          editRoleApi({
            ...formValues,
            'id.value': data.value.row.id,
          } as unknown as RoleGroupEntity),
      };

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

      // 如果是新增，group_delcode设置默认为0
      if (formType.value === 'create') {
        formValues.group_delcode = 0;
      }

      await apiMap[formType.value]();
      ElMessage.success('操作成功');
      emit('finish');
      modalApi.close();
    } catch (error) {
      console.error('操作失败', error);
    }
  },
  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('group_sort', 0);
        return;
      }

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

        baseFormApi.setValues(detailData);
      } catch (error) {
        console.error('获取角色详情失败', error);
      }

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

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