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

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

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

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

	const columns: ProColumns<BusinessAPI.OrderShipVO>[] = [
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.order' }),
			dataIndex: 'orderVO',
			key: 'orderId',
			render: (_, record) => {
				const orderVO = record.orderVO;
				return (
					orderVO &&
					`${orderVO.orderVehicle?.dealerName} | 第 ${orderVO.orderVehicle?.vehicleNo || '暂无'} 车 | ${orderVO.orderSn || '暂无'}`
				);
			},
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.dealer' }),
			dataIndex: ['dealerVO', 'shortName'],
			key: 'dealerId',
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.company' }),
			dataIndex: ['companyVO', 'shortName'],
			key: 'companyId',
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.orderSn' }),
			dataIndex: 'orderSn',
			key: 'orderSn',
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.shippingAddress' }),
			dataIndex: 'shippingAddress',
			key: 'shippingAddress',
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.receivingAddress',
			}),
			dataIndex: 'receivingAddress',
			key: 'receivingAddress',
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.shippingDate' }),
			dataIndex: 'shippingDate',
			key: 'shippingDate',
			valueType: 'date',
			sorter: true,
			defaultSortOrder: 'ascend',
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.estimatedArrivalDate',
			}),
			dataIndex: 'estimatedArrivalDate',
			key: 'estimatedArrivalDate',
			valueType: 'date',
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.watermelonGrade' }),
			dataIndex: 'watermelonGrade',
			key: 'watermelonGrade',
			search: false,
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.receivableAmount',
			}),
			dataIndex: 'receivableAmount',
			key: 'receivableAmount',
			search: false,
			valueType: 'money',
			render: (_, record) => (
				<span className="text-blue-600 font-medium">
					￥{formatCurrency(record.receivableAmount)}
				</span>
			),
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.adjustedAmount' }),
			dataIndex: 'adjustedAmount',
			key: 'adjustedAmount',
			search: false,
			valueType: 'money',
			render: (_, record) => (
				<span
					className={
						record.adjustedAmount >= 0 ? 'text-green-600' : 'text-red-600'
					}
				>
					<span className="ml-1">
						￥{formatCurrency(Math.abs(record.adjustedAmount))}
					</span>
				</span>
			),
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.type' }),
			dataIndex: 'type',
			key: 'type',
			valueType: 'select',
			valueEnum: {
				PURCHASE_SHIP: intl.formatMessage({
					id: intlPrefix + '.column.type.enum.purchaseShip',
				}),
				TRANSFER_SHIP: intl.formatMessage({
					id: intlPrefix + '.column.type.enum.transferShip',
				}),
				CHANGE_SHIP: intl.formatMessage({
					id: intlPrefix + '.column.type.enum.changeShip',
				}),
				RETURN_SHIP: intl.formatMessage({
					id: intlPrefix + '.column.type.enum.returnShip',
				}),
			},
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.state' }),
			dataIndex: 'state',
			key: 'state',
			valueType: 'select',
			search: false,
			valueEnum: {
				DRAFT: intl.formatMessage({
					id: intlPrefix + '.column.state.enum.draft',
				}),
				WAIT_SHIPMENT: intl.formatMessage({
					id: intlPrefix + '.column.state.enum.waitShipment',
				}),
				WAIT_PAYMENT: intl.formatMessage({
					id: intlPrefix + '.column.state.enum.waitPayment',
				}),
				PARTIAL_PAYMENT: intl.formatMessage({
					id: intlPrefix + '.column.state.enum.partialPayment',
				}),
				FULL_PAYMENT: intl.formatMessage({
					id: intlPrefix + '.column.state.enum.fullPayment',
				}),
				REJECT_FINISH: intl.formatMessage({
					id: intlPrefix + '.column.state.enum.rejectFinish',
				}),
				FINISH: intl.formatMessage({
					id: intlPrefix + '.column.state.enum.finish',
				}),
			},
		},
		...(initExtraColumns || []),
	];

	function setOrderShipVOStorage(orderShipVO: BusinessAPI.OrderShipVO) {
		const localOrderShipList = localStorage.getItem(sessionKey);
		const orderShipList = localOrderShipList
			? JSON.parse(localOrderShipList)
			: [];
		orderShipList.forEach((item: BusinessAPI.OrderShipVO, index: number) => {
			if (item.orderShipId === orderShipVO.orderShipId) {
				orderShipList.splice(index, 1);
			}
		});
		if (orderShipList.length < 5) {
			orderShipList.unshift(orderShipVO);
			localStorage.setItem(sessionKey, JSON.stringify(orderShipList));
		} else {
			orderShipList.pop();
			orderShipList.unshift(orderShipVO);
			localStorage.setItem(sessionKey, JSON.stringify(orderShipList));
		}
	}

	return (
		<SelectModal<BusinessAPI.OrderShipVO, BusinessAPI.OrderShipPageQry>
			rowKey={'orderShipId'}
			modalProps={{
				title: title || '选择发货单',
				...rest,
				destroyOnHidden: true,
				afterOpenChange: (open) => {
					if (!open) {
						setParams({
							...initParams,
						});
					}
				},
			}}
			selectedList={selectedList}
			tableProps={{
				rowKey: 'orderShipId',
				//@ts-ignore
				columns: columns,
				columnsState: {
					persistenceType: 'sessionStorage',
					persistenceKey: 'orderShipModalColumnStateKey',
				},
				params: {
					...params,
				},
				request: async (params, sorter, filter) => {
					const { data, success, totalCount } =
						await business.orderShip.pageOrderShip({
							orderShipPageQry: formatParam<typeof params>(
								params,
								sorter,
								filter,
							),
						});

					return {
						data:
							data?.map((orderShip: BusinessAPI.OrderShipVO) => {
								return {
									...orderShip,
									dealerVO: {
										dealerId: orderShip.dealerId,
										shortName: orderShip.dealerName,
									},
									companyVO: {
										companyId: orderShip.companyId,
										fullName: orderShip.companyName,
									},
								};
							}) || [],
						total: totalCount,
						success,
					};
				},
				tableAlertRender: ({ selectedRowKeys, selectedRows }) => {
					const selectedRowsMap = new Map<string, BusinessAPI.OrderShipVO>();
					selectedRows.forEach((item: BusinessAPI.OrderShipVO) => {
						if (item) {
							if (!selectedRowsMap.has(item.orderShipId)) {
								selectedRowsMap.set(item.orderShipId, item);
							}
						}
					});
					selectedList?.forEach((item: BusinessAPI.OrderShipVO) => {
						if (!selectedRowsMap.has(item.orderShipId)) {
							selectedRowsMap.set(item.orderShipId, item);
						}
					});
					let selectedTempList: BusinessAPI.OrderShipVO[] = [];
					selectedRowsMap.forEach((item: BusinessAPI.OrderShipVO) => {
						if (selectedRowKeys.includes(item.orderShipId)) {
							selectedTempList.push(item);
						}
					});
					return (
						<Space size={12}>
							<span>已选 {selectedRowKeys.length} 项</span>
							<Space wrap={true}>
								{selectedTempList?.map((item: BusinessAPI.OrderShipVO) => {
									return (
										item && <span key={item.orderShipId}>{item.orderSn}</span>
									);
								})}
							</Space>
						</Space>
					);
				},
				...(tips && {
					tableExtraRender: () => {
						return tips && <Alert type={'info'} message={tips} />;
					},
				}),
				...(type === 'radio' && {
					tableExtraRender: () => {
						const localOrderShipList = localStorage.getItem(sessionKey);
						if (localOrderShipList) {
							const orderShipList = JSON.parse(localOrderShipList);
							return (
								<>
									{tips && <Alert type={'info'} message={tips} />}
									<Space wrap={true} style={{ marginTop: 8 }}>
										{orderShipList.map((item: BusinessAPI.OrderShipVO) => {
											return (
												<Tag
													style={{
														cursor: 'pointer',
													}}
													onClick={() => {
														// 直接使用 localStorage 中保存的数据
														onFinish([item]);
														setOrderShipVOStorage(item);
													}}
													key={item.orderShipId}
												>
													{item.orderSn}
												</Tag>
											);
										})}
									</Space>
								</>
							);
						}
					},
				}),
				actionRef: actionRef,
				toolbar: {
					filter: (
						<LightFilter
							onFinish={async (values) => {
								setParams({
									...initParams,
									...values,
								});
							}}
						>
							{extraFilter}
							{/* 发货时间筛选 */}
							<ProFormDateRangePicker
								label={'发货时间'}
								name={'shippingDate'}
								placeholder={'请选择发货时间'}
								fieldProps={{
									allowClear: true,
									picker: 'date',
								}}
							/>
							<ProFormSelect
								label={'发货单状态'}
								name={'state'}
								placeholder={'请选择发货单状态'}
								valueEnum={{
									DRAFT: intl.formatMessage({
										id: intlPrefix + '.state.draft',
									}),
									WAIT_SHIPMENT: intl.formatMessage({
										id: intlPrefix + '.state.waitShipment',
									}),
									WAIT_PAYMENT: intl.formatMessage({
										id: intlPrefix + '.state.waitPayment',
									}),
									PARTIAL_PAYMENT: intl.formatMessage({
										id: intlPrefix + '.state.partialPayment',
									}),
									FULL_PAYMENT: intl.formatMessage({
										id: intlPrefix + '.state.fullPayment',
									}),
									FINISH: intl.formatMessage({
										id: intlPrefix + '.state.finish',
									}),
								}}
								fieldProps={{
									showSearch: true,
									allowClear: true,
									autoClearSearchValue: true,
								}}
							/>
						</LightFilter>
					),
					search: {
						placeholder: '请输入发货单编号',
						onSearch: async (value: string) => {
							setParams({
								...params,
								orderSn: value,
							});
						},
					},
				},
			}}
			onFinish={(orderShipVOList) => {
				if (type === 'radio') {
					if (orderShipVOList.length > 0) {
						setOrderShipVOStorage(orderShipVOList[0]);
					}
				}

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