import { CompanyList, OrderList } from '@/components';
import { business } from '@/services';
import { formatBankCard, formatIdCard, formatPhone } from '@/utils/format';
import { formatParam } from '@/utils/formatParam';
import { pagination } from '@/utils/pagination';
import { useIntl } from '@@/exports';
import { EyeInvisibleOutlined, EyeTwoTone } from '@ant-design/icons';
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';

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

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

	const [showIdCard, setShowIdCard] = useState<Record<string, boolean>>({});
	const [showBankCard, setShowBankCard] = useState<Record<string, boolean>>({});
	const [showPhone, setShowPhone] = useState<Record<string, boolean>>({});

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

	const columns: ProColumns<BusinessAPI.OrderSupplierVO>[] = [
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.order' }),
			dataIndex: ['orderVO', 'orderSn'],
			key: 'orderSn',
			search: false,
			render: (_, orderSupplierVO: BusinessAPI.OrderSupplierVO) => {
				const orderVO = orderSupplierVO.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.name' }),
			dataIndex: 'name',
			key: 'name',
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.invoiceAmount' }),
			dataIndex: 'invoiceAmount',
			key: 'invoiceAmount',
			valueType: 'money',
			search: false,
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.depositAmount' }),
			dataIndex: 'depositAmount',
			key: 'depositAmount',
			valueType: 'money',
			search: false,
		},
		// 剩余付款金额
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.remainingAmount',
			}),
			dataIndex: 'remainingAmount',
			key: 'remainingAmount',
			valueType: 'money',
			search: false,
			renderText: (_, record) => {
				return record.invoiceAmount - record.depositAmount || 0;
			},
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.idCard',
			}),
			dataIndex: 'idCard',
			key: 'idCard',
			search: false,
			render: (_, record) => (
				<div className="flex items-center">
					<span>
						{formatIdCard(record.idCard, showIdCard[record.orderSupplierId])}
					</span>
					<span
						className="ml-2 cursor-pointer"
						onClick={(e) => {
							e.stopPropagation();
							setShowIdCard((prev) => ({
								...prev,
								[record.orderSupplierId]: !prev[record.orderSupplierId],
							}));
						}}
					>
						{showIdCard[record.orderSupplierId] ? (
							<EyeTwoTone />
						) : (
							<EyeInvisibleOutlined />
						)}
					</span>
				</div>
			),
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.phone' }),
			dataIndex: 'phone',
			key: 'phone',
			search: false,
			render: (_, record) => (
				<div className="flex items-center">
					<span>
						{formatPhone(record.phone, showPhone[record.orderSupplierId])}
					</span>
					<span
						className="ml-2 cursor-pointer"
						onClick={(e) => {
							e.stopPropagation();
							setShowPhone((prev) => ({
								...prev,
								[record.orderSupplierId]: !prev[record.orderSupplierId],
							}));
						}}
					>
						{showPhone[record.orderSupplierId] ? (
							<EyeTwoTone />
						) : (
							<EyeInvisibleOutlined />
						)}
					</span>
				</div>
			),
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.bankCard' }),
			dataIndex: 'bankCard',
			key: 'bankCard',
			search: false,
			render: (_, record) => (
				<div className="flex items-center">
					<span>
						{formatBankCard(
							record?.bankCard || '',
							showBankCard[record.orderSupplierId],
						)}
					</span>
					<span
						className="ml-2 cursor-pointer"
						onClick={(e) => {
							e.stopPropagation();
							setShowBankCard((prev) => ({
								...prev,
								[record.orderSupplierId]: !prev[record.orderSupplierId],
							}));
						}}
					>
						{showBankCard[record.orderSupplierId] ? (
							<EyeTwoTone />
						) : (
							<EyeInvisibleOutlined />
						)}
					</span>
				</div>
			),
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.orderCompany' }),
			dataIndex: 'orderCompany',
			valueType: 'select',
			request: async (params) => {
				const { data } = await business.company.listCompany({
					companyListQry: {
						...params,
					},
				});

				return (
					data?.map((item) => {
						return {
							label: item.fullName,
							value: item.companyId,
						};
					}) || []
				);
			},
			render: (_, record) => {
				return (
					<CompanyList
						ghost={true}
						mode={'detail'}
						companyId={record.orderCompany.companyId}
						trigger={() => <a href={'#'}>{record.orderCompany.fullName}</a>}
					/>
				);
			},
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.isPaid' }),
			dataIndex: 'isPaid',
			key: 'isPaid',
			valueType: 'select',
			valueEnum: {
				true: {
					text: intl.formatMessage({
						id: intlPrefix + '.column.isPaid.paid',
					}),
					status: 'success',
				},
				false: {
					text: intl.formatMessage({
						id: intlPrefix + '.column.isPaid.unpaid',
					}),
					status: 'processing',
				},
			},
		},
		...(initExtraColumns || []),
	];

	function setOrderSupplierVOStorage(
		orderSupplierVO: BusinessAPI.OrderSupplierVO,
	) {
		const localOrderSupplierList = localStorage.getItem(sessionKey);
		const orderSupplierList = localOrderSupplierList
			? JSON.parse(localOrderSupplierList)
			: [];
		orderSupplierList.forEach(
			(item: BusinessAPI.OrderSupplierVO, index: number) => {
				if (item.orderSupplierId === orderSupplierVO.orderSupplierId) {
					orderSupplierList.splice(index, 1);
				}
			},
		);
		if (orderSupplierList.length < 5) {
			orderSupplierList.unshift(orderSupplierVO);
			localStorage.setItem(sessionKey, JSON.stringify(orderSupplierList));
		} else {
			orderSupplierList.pop();
			orderSupplierList.unshift(orderSupplierVO);
			localStorage.setItem(sessionKey, JSON.stringify(orderSupplierList));
		}
	}

	return (
		<SelectModal<BusinessAPI.OrderSupplierVO, BusinessAPI.OrderSupplierPageQry>
			rowKey={'orderSupplierId'}
			modalProps={{
				title: title || '选择瓜农订单',
				...rest,
				destroyOnHidden: true,
				afterOpenChange: (open) => {
					if (!open) {
						setParams({
							...initParams,
						});
					}
				},
			}}
			selectedList={selectedList}
			tableProps={{
				rowKey: 'orderSupplierId',
				columns: columns,
				columnsState: {
					persistenceType: 'sessionStorage',
					persistenceKey: 'orderSupplierModalColumnStateKey',
				},
				params: {
					...params,
					poStates: ['COMPLETED'],
				},
				request: async (params, sorter, filter) => {
					const { data, success, totalCount } =
						await business.orderSupplier.pageOrderSupplier({
							orderSupplierPageQry: formatParam<typeof params>(
								params,
								sorter,
								filter,
							),
						});

					return {
						data: data || [],
						total: totalCount,
						success,
					};
				},
				pagination: {
					...pagination(),
					position: ['bottomRight'],
				},
				tableAlertRender: ({ selectedRowKeys, selectedRows }) => {
					const selectedRowsMap = new Map<
						string,
						BusinessAPI.OrderSupplierVO
					>();
					selectedRows.forEach((item: BusinessAPI.OrderSupplierVO) => {
						if (item) {
							if (!selectedRowsMap.has(item.orderSupplierId)) {
								selectedRowsMap.set(item.orderSupplierId, item);
							}
						}
					});
					selectedList?.forEach((item: BusinessAPI.OrderSupplierVO) => {
						if (!selectedRowsMap.has(item.orderSupplierId)) {
							selectedRowsMap.set(item.orderSupplierId, item);
						}
					});
					let selectedTempList: BusinessAPI.OrderSupplierVO[] = [];
					selectedRowsMap.forEach((item: BusinessAPI.OrderSupplierVO) => {
						if (selectedRowKeys.includes(item.orderSupplierId)) {
							selectedTempList.push(item);
						}
					});
					return (
						<Space size={12}>
							<span>已选 {selectedRowKeys.length} 项</span>
							<Space wrap={true}>
								{selectedTempList?.map((item: BusinessAPI.OrderSupplierVO) => {
									return (
										item && <span key={item.orderSupplierId}>{item.name}</span>
									);
								})}
							</Space>
						</Space>
					);
				},
				...(tips && {
					tableExtraRender: () => {
						return tips && <Alert type={'info'} message={tips} />;
					},
				}),
				...(type === 'radio' && {
					tableExtraRender: () => {
						const localOrderSupplierList = localStorage.getItem(sessionKey);
						if (localOrderSupplierList) {
							const orderSupplierList = JSON.parse(localOrderSupplierList);
							return (
								<>
									{tips && <Alert type={'info'} message={tips} />}
									<Row gutter={16}>
										{orderSupplierList.map(
											(item: BusinessAPI.OrderSupplierVO) => {
												return (
													<Tag
														style={{
															cursor: 'pointer',
														}}
														onClick={() => {
															// 直接使用 localStorage 中保存的数据
															onFinish([item]);
															setOrderSupplierVOStorage(item);
														}}
														key={item.orderSupplierId}
													>
														{item.name}
													</Tag>
												);
											},
										)}
									</Row>
								</>
							);
						}
					},
				}),
				actionRef: actionRef,
				toolbar: {
					filter: (
						<LightFilter
							onFinish={async (values) => {
								setParams({
									...initParams,
									...values,
								});
							}}
						>
							{extraFilter}
							{/*<ProFormSelect*/}
							{/*	label={'供应商类型'}*/}
							{/*	name={'type'}*/}
							{/*	placeholder={'请选择供应商类型'}*/}
							{/*	valueEnum={{*/}
							{/*		FARMER: intl.formatMessage({*/}
							{/*			id: intlPrefix + '.column.type.farmer',*/}
							{/*		}),*/}
							{/*		STALL: intl.formatMessage({*/}
							{/*			id: intlPrefix + '.column.type.stall',*/}
							{/*		}),*/}
							{/*		OTHER_STALL: intl.formatMessage({*/}
							{/*			id: intlPrefix + '.column.type.otherStall',*/}
							{/*		}),*/}
							{/*	}}*/}
							{/*	fieldProps={{*/}
							{/*		showSearch: true,*/}
							{/*		allowClear: true,*/}
							{/*		autoClearSearchValue: true,*/}
							{/*	}}*/}
							{/*/>*/}
							<ProFormSelect
								label={'是否付款'}
								name={'isPaid'}
								placeholder={'请选择是否付款'}
								valueEnum={{
									true: intl.formatMessage({
										id: intlPrefix + '.column.isPaid.paid',
									}),
									false: intl.formatMessage({
										id: intlPrefix + '.column.isPaid.unpaid',
									}),
								}}
								fieldProps={{
									showSearch: true,
									allowClear: true,
									autoClearSearchValue: true,
								}}
							/>
						</LightFilter>
					),
					search: {
						placeholder: '请输入供应商姓名',
						onSearch: async (value: string) => {
							setParams({
								...params,
								//@ts-ignore
								name: value,
							});
						},
					},
				},
			}}
			onFinish={(orderSupplierVOList) => {
				if (type === 'radio') {
					if (orderSupplierVOList.length > 0) {
						setOrderSupplierVOStorage(orderSupplierVOList[0]);
					}
				}

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