import { EditButton, MyIcons } from '@/common';
import { PermissionTreeSelect } from '@/components/PermissionTreeSelect';
import { Apis } from '@/gen/Apis';
import { SysPermissionsTypeEnum } from '@/gen/Enums';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { useMemoizedFn } from 'ahooks';
import { Form, message, Space } from 'antd';
import { useState } from 'react';

type TableType = ApiRespTypes.SysPermissions.List;
type FormType = ApiReqTypes.SysPermissions.Update;

export default function Update(props: {
  item: TableType[0];
  title: string;
  onFinish: () => void;
}) {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const handleFinish = useMemoizedFn(async (values: FormType) => {
    setLoading(true);
    return Apis.SysPermissions.Update({
      ...values,
      guard_name: props.item.guard_name,
      id: props.item.id,
    })
      .then(() => {
        message.success('编辑成功');
        props.onFinish();
        return true;
      })
      .finally(() => {
        setLoading(false);
      });
  });

  return (
    <BetaSchemaForm<FormType>
      form={form}
      title={`编辑${props.title}`}
      layoutType="ModalForm"
      trigger={<EditButton />}
      modalProps={{
        maskClosable: false,
        destroyOnClose: true,
      }}
      onOpenChange={(open: any) => {
        if (open && props.item) {
          form.setFieldsValue(props.item);
        }
      }}
      onFinish={handleFinish}
      disabled={loading}
      loading={loading}
      columns={[
        PermissionTreeSelect(props.item.guard_name),
        {
          key: 'name',
          title: '名称',
        },
        {
          key: 'key',
          title: '前端权限识别符',
        },
        {
          key: 'icon',
          title: '图标',
          valueType: 'select',
          request: async () => {
            return Object.entries(MyIcons).map(([key, value]) => ({
              label: (
                <Space style={{ gap: '5px' }}>
                  {value}
                  <span>{key}</span>
                </Space>
              ),
              value: key,
            }));
          },
        },
        {
          key: 'type',
          title: '类型',
          valueType: 'radioButton',
          fieldProps: {
            buttonStyle: 'solid',
          },
          valueEnum: SysPermissionsTypeEnum,
        },
        { key: 'path', title: '路由' },
      ]}
    />
  );
}
