import { BizValueType, ButtonAccess } from '@/components';
import { formLayout } from '@/utils/formLayout';
import { useIntl } from '@@/exports';
import {
	DrawerForm,
	ModalForm,
	ProCard,
	ProDescriptions,
	ProFormDependency,
} from '@ant-design/pro-components';
import { useState } from 'react';
import { BizDetailProps } from './typing';

export default function BizDetail<
	BizVO extends Record<string, any>,
	Func extends Record<string, any>,
>(props: BizDetailProps<BizVO, Func>) {
	const {
		row,
		rowId,
		rowKey,
		permission,
		intlPrefix,
		formType,
		method,
		methodUpper,
		func,
		formContext,
		formContextMode = 'tab',
		trigger,
		fieldProps,
		initValues,
		isMobile,
		columns,
		positionKey,
		showDetail = true,
	} = props;

	const [open, setOpen] = useState(false);

	const intl = useIntl();

	/** 渲染 formContext 内容 */
	const renderFormContext = (data: any, form: any, colSpan: number) => {
		if (!formContext) return null;

		const contextItems = formContext(data?.[`${method}VO`], async () => {
			const { data } = await func?.[`show${methodUpper}`]({
				[`${method}ShowQry`]: {
					[`${rowKey}`]: rowId,
				},
			});
			form.setFieldValue(`${method}VO`, data);
		})?.filter((item) => {
			// @ts-ignore
			return !item.display || item.display(data?.[`${method}VO`]);
		});

		// 平铺模式：直接垂直堆叠所有内容
		if (formContextMode === 'flat') {
			return contextItems?.map((item, index) => (
				<ProCard
					key={item.key || index}
					bordered={true}
					headerBordered={false}
					title={item.label}
					style={{
						marginBottom: 16,
					}}
					// @ts-ignore
					subTitle={item.subTitle}
				>
					{item.children}
				</ProCard>
			));
		}

		// Tab 模式：使用 tabs 渲染
		return (
			<ProCard
				bordered={true}
				headerBordered={true}
				colSpan={colSpan}
				tabs={{
					tabPosition: 'top',
					activeKey: data.activeKey,
					items: contextItems,
					onChange: (key) => {
						form.setFieldValue('activeKey', key);
					},
				}}
			/>
		);
	};

	let rest = {
		title: intl.formatMessage({
			id: intlPrefix + '.modal.view.title',
		}),
		autoFocusFirstInput: true,
		submitTimeout: 2000,
		open: fieldProps?.open || open,
		onOpenChange: fieldProps?.onOpenChange || setOpen,
		request: async (): Promise<any> => {
			const { data } = await func?.[`show${methodUpper}`]({
				[`${method}ShowQry`]: {
					[`${rowKey}`]: rowId,
				},
			});

			const extra = await initValues?.(rowId!);
			return {
				[`${rowKey}`]: rowId,
				[`${method}VO`]: data,
				...extra,
				isMobile,
			};
		},
	};

	const renderForm = () => {
		if (formType === 'drawer' || formType === 'step') {
			return (
				<DrawerForm<BizVO>
					{...fieldProps}
					{...formLayout(isMobile)}
					width={isMobile ? '100%' : '85%'}
					drawerProps={{
						destroyOnHidden: true,
					}}
					submitter={{
						searchConfig: {
							resetText: '关闭',
						},
						submitButtonProps: {
							style: {
								display: 'none',
							},
						},
					}}
					{...rest}
				>
					{columns && showDetail && (
						<ProFormDependency name={[`${method}VO`, 'isMobile', 'activeKey']}>
							{(data, form) => {
								return (
									<ProCard ghost={true} gutter={24} direction={'column'}>
										<ProCard
											bordered={true}
											headerBordered={true}
											colSpan={24}
											style={{
												marginBottom: 16,
											}}
										>
											<ProDescriptions<BizVO, BizValueType>
												params={{ data: data[`${method}VO`] }}
												request={async (params) =>
													Promise.resolve({
														success: true,
														data: params?.data,
													})
												}
												columns={[...columns]}
											/>
										</ProCard>
										{renderFormContext(data, form, 24)}
									</ProCard>
								);
							}}
						</ProFormDependency>
					)}
				</DrawerForm>
			);
		}

		if (formType === 'modal') {
			return (
				<ModalForm<BizVO>
					{...fieldProps}
					{...formLayout(isMobile)}
					modalProps={{
						destroyOnHidden: true,
					}}
					submitter={{
						searchConfig: {
							resetText: '关闭',
						},
						submitButtonProps: {
							style: {
								display: 'none',
							},
						},
					}}
					{...rest}
				>
					{columns && (
						<ProFormDependency name={[`${method}VO`, 'isMobile', 'activeKey']}>
							{(data, form) => {
								return (
									<ProCard ghost={true} gutter={24} direction={'column'}>
										<ProCard
											bordered={true}
											headerBordered={true}
											colSpan={24}
											style={{
												marginBottom: 16,
											}}
										>
											<ProDescriptions<BizVO, BizValueType>
												params={{ data: data[`${method}VO`] }}
												request={async (params) =>
													Promise.resolve({
														success: true,
														data: params?.data,
													})
												}
												columns={[...columns]}
											/>
										</ProCard>
										{renderFormContext(data, form, 24)}
									</ProCard>
								);
							}}
						</ProFormDependency>
					)}
				</ModalForm>
			);
		}
	};

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

		return (
			<ButtonAccess
				permission={permission + '-view'}
				key="view"
				type="link"
				onClick={(event) => {
					setOpen(true);
					event.stopPropagation();
				}}
				positionKey={positionKey}
			>
				{intl.formatMessage({
					id: intlPrefix + '.modal.view.button',
				})}
			</ButtonAccess>
		);
	};

	return (
		<>
			{renderTrigger()}
			{renderForm()}
		</>
	);
}
