import { business } from '@/services';
import { formatParam } from '@/utils/formatParam';
import { pagination } from '@/utils/pagination';
import { useIntl } from '@@/exports';
import {
	ActionType,
	LightFilter,
	ProColumns,
	ProFormSelect,
} from '@ant-design/pro-components';
import { SelectModal } from '@chageable/components';
import { Alert, ModalProps, Row, Space, Tag } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { OrderFormItem, OrderList } from '@/components';

export interface IOrderModalProps extends ModalProps {
	title: string;
	selectedList?: BusinessAPI.OrderVO[];
	onFinish: (orderVOList: BusinessAPI.OrderVO[]) => void;
	type: 'checkbox' | 'radio' | undefined;
	params?: BusinessAPI.DealerPageQry;
	num?: number;
	tips?: string;
	extraFilter?: React.ReactNode[];
	extraColumns?: ProColumns<BusinessAPI.OrderVO>[];
}

export default function OrderModal(props: IOrderModalProps) {
	const {
		title,
		onFinish,
		type,
		selectedList,
		params: initParams,
		num = 10,
		tips,
		extraFilter = [],
		extraColumns: initExtraColumns = [],
		...rest
	} = props;
	const actionRef = useRef<ActionType>();
	const sessionKey = `orderList`;
	const intl = useIntl();
	const intlPrefix = 'order';
	const [params, setParams] = useState<BusinessAPI.DealerPageQry>(
		initParams || {},
	);

	useEffect(() => {
		if (initParams) {
			setParams({
				...params,
				...initParams,
			});
		}
	}, [initParams]);

	const columns: ProColumns<BusinessAPI.OrderVO>[] = [
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.order' }),
			key: 'orderId',
			renderFormItem: (_, props) => {
				return (
					//@ts-ignore
					<OrderFormItem {...props} {...props?.fieldProps} />
				);
			},
			render: (_, orderVO: BusinessAPI.OrderVO) => {
				return (
					orderVO && (
						<OrderList
							ghost={true}
							mode={'detail'}
							orderId={orderVO.orderId}
							trigger={() => (
								<Space>
									<a>
										{`${orderVO.orderVehicle?.dealerName} - 第 ${orderVO.orderVehicle?.vehicleNo || '暂无'} 车 - ${orderVO.orderSn || '暂无'}`}
									</a>
								</Space>
							)}
						/>
					)
				);
			},
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.origin' }),
			dataIndex: ['orderVehicle', 'origin'],
			search: false,
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.destination' }),
			dataIndex: ['orderVehicle', 'destination'],
			search: false,
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.plate' }),
			dataIndex: ['orderVehicle', 'plate'],
			key: 'plate',
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.driver' }),
			dataIndex: ['orderVehicle', 'driver'],
			key: 'driver',
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.phone' }),
			dataIndex: ['orderVehicle', 'phone'],
			key: 'phone',
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.state' }),
			dataIndex: 'state',
			key: 'state',
			valueType: 'select',
			render: (_, record) => {
				const stateText = intl.formatMessage({
					id: `${intlPrefix}.column.state.${record.state?.toLowerCase() || 'unknown'}`,
				});

				let color = 'default';
				switch (record.state) {
					case 'DRAFT':
						color = 'default';
						break;
					case 'AUDITING':
						color = 'processing';
						break;
					case 'COMPLETED':
						color = 'success';
						break;
					default:
						color = 'default';
				}

				return <Tag color={color}>{stateText}</Tag>;
			},
		},
		...(initExtraColumns || []),
	];

	function setDealerVOStorage(orderVO: BusinessAPI.OrderVO) {
		const localOrderList = localStorage.getItem(sessionKey);
		const orderList = localOrderList
			? JSON.parse(localOrderList)
			: [];
		orderList.forEach(
			(item: BusinessAPI.OrderVO, index: number) => {
				if (item.orderId === orderVO.orderId) {
					orderList.splice(index, 1);
				}
			},
		);
		if (orderList.length < 5) {
			orderList.unshift(orderVO);
			localStorage.setItem(sessionKey, JSON.stringify(orderList));
		} else {
			orderList.pop();
			orderList.unshift(orderVO);
			localStorage.setItem(sessionKey, JSON.stringify(orderList));
		}
	}

	return (
		<SelectModal<BusinessAPI.OrderVO, BusinessAPI.OrderPageQry>
			rowKey={'orderId'}
			modalProps={{
				title: title || '选择采购单',
				...rest,
				destroyOnHidden: true,
				afterOpenChange: (open) => {
					if (!open) {
						setParams({
							...initParams,
						});
					}
				},
			}}
			selectedList={selectedList}
			tableProps={{
				rowKey: 'orderId',
				columns: columns,
				columnsState: {
					persistenceType: 'sessionStorage',
					persistenceKey: 'orderModalColumnStateKey',
				},
				params: {
					...params,
				},
				request: async (params, sorter, filter) => {
					const { data, success, totalCount } =
						await business.order.pageOrder({
							orderPageQry: formatParam<typeof params>(
								params,
								sorter,
								filter,
							),
						});

					return {
						data: data || [],
						total: totalCount,
						success,
					};
				},
				pagination: {
					...pagination(),
					position: ['bottomRight'],
				},
				tableAlertRender: ({ selectedRowKeys, selectedRows }) => {
					// selectedRows 和 selectedList 组合在一起，去重，
					const selectedRowsMap = new Map<
						string,
						BusinessAPI.OrderVO
					>();
					selectedRows.forEach((item: BusinessAPI.OrderVO) => {
						if (item) {
							if (!selectedRowsMap.has(item.orderId)) {
								selectedRowsMap.set(item.orderId, item);
							}
						}
					});
					selectedList?.forEach((item: BusinessAPI.OrderVO) => {
						if (!selectedRowsMap.has(item.orderId)) {
							selectedRowsMap.set(item.orderId, item);
						}
					});
					let selectedTempList: BusinessAPI.OrderVO[] = [];
					selectedRowsMap.forEach((item: BusinessAPI.OrderVO) => {
						if (selectedRowKeys.includes(item.orderId)) {
							selectedTempList.push(item);
						}
					});
					return (
						<Space size={12}>
							<span>已选 {selectedRowKeys.length} 项</span>
							<Space wrap={true}>
								{selectedTempList?.map((item: BusinessAPI.OrderVO) => {
									return item && <span key={item.orderId}>{item.orderSn}</span>;
								})}
							</Space>
						</Space>
					);
				},
				...(tips && {
					tableExtraRender: () => {
						return tips && <Alert type={'info'} message={tips} />;
					},
				}),
				...(type === 'radio' && {
					tableExtraRender: () => {
						const localDealerList = localStorage.getItem(sessionKey);
						if (localDealerList) {
							const dealerList = JSON.parse(localDealerList);
							return (
								<>
									{tips && <Alert type={'info'} message={tips} />}
									<Row gutter={16}>
										{dealerList.map((item: BusinessAPI.OrderVO) => {
											return (
												<Tag
													style={{
														cursor: 'pointer',
													}}
													onClick={async () => {
														const { data: orderVO } =
															await business.order.showOrder({
																orderShowQry: {
																	orderId: item.orderId,
																},
															});

														if (orderVO) {
															onFinish([orderVO]);
															setDealerVOStorage(orderVO);
														}
													}}
													key={item.orderId}
												>
													{item.orderSn}
												</Tag>
											);
										})}
									</Row>
								</>
							);
						}
					},
				}),
				actionRef: actionRef,
				toolbar: {
					filter: (
						<LightFilter
							onFinish={async (values) => {
								setParams({
									...initParams,
									...values,
								});
							}}
						>
							{extraFilter}
							<ProFormSelect
								label={'采购单状态'}
								name={'state'}
								placeholder={'请选择采购单状态'}
								valueEnum={{
									DRAFT: intl.formatMessage({
										id: intlPrefix + '.column.state.draft',
									}),
									AUDITING: intl.formatMessage({
										id: intlPrefix + '.column.state.auditing',
									}),
									COMPLETED: intl.formatMessage({
										id: intlPrefix + '.column.state.completed',
									}),
									CLOSED: intl.formatMessage({
										id: intlPrefix + '.column.state.closed',
									}),
								}}
								fieldProps={{
									showSearch: true,
									allowClear: true,
									autoClearSearchValue: true,
								}}
							/>
						</LightFilter>
					),
					search: {
						placeholder: '请输入采购单编号',
						onSearch: async (value: string) => {
							setParams({
								...params,
								//@ts-ignore
								orderSn: value,
							});
						},
					},
				},
			}}
			onFinish={(dealerVOList) => {
				if (type === 'radio') {
					if (dealerVOList.length > 0) {
						setDealerVOStorage(dealerVOList[0]);
					}
				}

				onFinish(dealerVOList);
			}}
			num={num}
			type={type}
		/>
	);
}
