import {
  MyBetaModalFormProps,
  MyButtons,
  MyFormItems,
  MyModalFormProps,
  rulesHelper,
} from '@/common';
import { JinGangArea } from '@/components/EmployeeJinGangBtnSelect';
import { SysSelects } from '@/components/SysSelects';
import { Apis } from '@/gen/Apis';
import { SysPermissionsTypeEnum } from '@/gen/Enums';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { Form, message } from 'antd';

export default function Update(
  props: { guardName: string } & MyBetaModalFormProps,
) {
  const [form] = Form.useForm();

  return (
    <BetaSchemaForm<ApiTypes.Permission.SysPermissions.Update>
      {...MyModalFormProps.props}
      title={`编辑${props.title}`}
      wrapperCol={{ span: 24 }}
      width="600px"
      // 确保正确弹窗，使用动态的时间参数
      key={new Date().getTime()}
      form={form}
      onOpenChange={(open: any) => {
        if (open && props.item) {
          form.setFieldsValue(props.item);
        }
      }}
      onFinish={async (values) => {
        return Apis.Permission.SysPermissions.Update({
          ...values,
          guard_name: props.guardName,
          id: props.item?.id,
        })
          .then(() => {
            props.reload?.();
            message.success(props.title + '成功');
            return true;
          })
          .catch(() => false);
      }}
      trigger={<MyButtons.Edit />}
      columns={[
        SysSelects.SysPermissionsTree({ guard_name: props.guardName }),
        {
          key: 'name',
          title: '标题',
          required: true,
          formItemProps: { ...rulesHelper.text },
        },
        {
          key: 'key',
          title: '标识(en)',
        },
        MyFormItems.IconSelect(),
        MyFormItems.EnumRadio({
          key: 'type',
          title: '类型',
          valueEnum: SysPermissionsTypeEnum,
          required: true,
        }),
        {
          valueType: 'dependency',
          name: ['type'],
          columns: ({ type }) => {
            return type === 'QuickAction'
              ? [
                  JinGangArea?.JinGangAreaSelect({
                    key: 'path',
                    title: '选择金刚区按钮',
                    required: true,
                  }),
                ]
              : [{ key: 'path', title: '路由' }];
          },
        },
        SysSelects.Api(),
      ]}
    />
  );
}
