import { ButtonAccess } from '@/components';
import { formLayout } from '@/utils/formLayout';
import { useIntl } from '@@/exports';
import { PlusOutlined } from '@ant-design/icons';
import { DrawerForm, ModalForm, StepsForm } from '@ant-design/pro-components';
import { Button, message, Modal, Result } from 'antd';
import { useState } from 'react';
import { BizCreateProps } from './typing';

export default function BizCreate<
	BizVO extends Record<string, any>,
	BizCreateCmd extends Record<string, any>,
	Func extends Record<string, any>,
>(props: BizCreateProps<BizVO, BizCreateCmd, Func>) {
	const {
		permission,
		intlPrefix,
		formType,
		methodUpper,
		func,
		onFinish,
		initValues,
		formContext,
		trigger,
		showNextCreate = false,
		fieldProps,
		isMobile = false,
		request,
	} = props;

	const [modalOpen, setModalOpen] = useState(false);
	const [open, setOpen] = useState(false);
	const [current, setCurrent] = useState<number>(0);

	const intl = useIntl();

	let rest = {
		title: intl.formatMessage({
			id: intlPrefix + '.modal.create.title',
		}),
		autoFocusFirstInput: true,
		submitTimeout: 2000,
		open: fieldProps?.open || open,
		onOpenChange: fieldProps?.onOpenChange || setOpen,
		request: async () =>
			Promise.resolve({
				...initValues,
			} as any),
		onFinish: async (formData: BizCreateCmd) => {
			// 移除 formData 里面的key名字带有VO的字段
			Object.keys(formData).forEach((key) => {
				if (key.includes('VO')) {
					delete formData[key];
				}
			});

			if (request) {
				const success = await request(formData);

				if (success) {
					message.success(
						intl.formatMessage({
							id: intlPrefix + '.modal.create.success',
						}),
					);
				} else {
					return;
				}

				onFinish?.(formData as any);
			} else {
				const { success, data } = await func?.[`create${methodUpper}`]?.(
					formData as any,
				);
				if (success) {
					message.success(
						intl.formatMessage({
							id: intlPrefix + '.modal.create.success',
						}),
					);

					onFinish?.(data);
				} else {
					return;
				}
			}

			if (showNextCreate) {
				setModalOpen(true);
			}

			rest.onOpenChange(false);

			return true;
		},
	};

	const renderForm = () => {
		if (formType === 'step') {
			return (
				<StepsForm<BizCreateCmd>
					containerStyle={{ width: '100%', minWidth: '0px' }}
					onFinish={rest.onFinish}
					current={current}
					onCurrentChange={setCurrent}
					stepsFormRender={(from, submitter) => {
						return (
							<DrawerForm<BizCreateCmd>
								layout={'horizontal'}
								width={isMobile ? '100%' : '85%'}
								submitter={{
									render: () => submitter,
								}}
								drawerProps={{
									destroyOnHidden: true,
									afterOpenChange: (open) => {
										if (!open) {
											setCurrent(0);
										}
									},
								}}
								{...rest}
								{...fieldProps}
							>
								{from}
							</DrawerForm>
						);
					}}
				>
					{formContext}
				</StepsForm>
			);
		}

		if (formType === 'drawer') {
			return (
				<DrawerForm<BizCreateCmd>
					{...formLayout(isMobile)}
					width={isMobile ? '100%' : '85%'}
					drawerProps={{
						destroyOnHidden: true,
					}}
					{...rest}
					{...fieldProps}
				>
					{formContext}
				</DrawerForm>
			);
		}

		if (formType === 'modal') {
			return (
				<ModalForm<BizCreateCmd>
					{...formLayout(isMobile)}
					modalProps={{
						destroyOnHidden: true,
					}}
					{...rest}
					{...fieldProps}
				>
					{formContext}
				</ModalForm>
			);
		}
	};

	const renderTrigger = () => {
		if (trigger) {
			return (
				<div
					onClick={() => {
						rest.onOpenChange(true);
					}}
				>
					{trigger?.()}
				</div>
			);
		}

		return (
			<ButtonAccess
				className="biz-create"
				permission={permission + '-create'}
				key="create"
				icon={<PlusOutlined />}
				type="primary"
				size={'middle'}
				onClick={() => {
					rest.onOpenChange(true);
				}}
			>
				{!isMobile &&
					intl.formatMessage({
						id: intlPrefix + '.modal.create.button',
					})}
			</ButtonAccess>
		);
	};

	return (
		<>
			{renderTrigger()}
			<Modal
				open={modalOpen}
				footer={false}
				destroyOnHidden={true}
				closeIcon={false}
			>
				<Result
					status="success"
					title={intl.formatMessage({
						id: intlPrefix + '.modal.create.success',
					})}
					extra={[
						<Button
							type="primary"
							key="add"
							onClick={() => {
								setModalOpen(false);
								rest.onOpenChange(true);
							}}
						>
							继续新增
						</Button>,
						<Button
							key={'list'}
							type={'default'}
							onClick={async () => {
								setModalOpen(false);
							}}
						>
							返回列表
						</Button>,
					]}
				/>
			</Modal>
			{renderForm()}
		</>
	);
}
