import { SelectModal } 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,
	ProFormText,
} from '@ant-design/pro-components';
import { Alert, ModalProps, Row, Tag } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

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

export default function SupplierModal(props: ISupplierModalProps) {
	const {
		title,
		onFinish,
		type,
		selectedList,
		params: initParams,
		num = 10,
		tips,
		extraFilter = [],
		extraColumns: initExtraColumns = [],
		...rest
	} = props;
	const actionRef = useRef<ActionType>();
	const sessionKey =
		props.params?.type === 'FARMER' ? 'supplierFarmer' : 'supplierStall';

	const [params, setParams] = useState<BusinessAPI.SupplierPageQry>(
		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 intl = useIntl();
	const intlPrefix =
		props.params?.type === 'FARMER' ? 'supplierFarmer' : 'supplierStall';

	const columns: ProColumns<BusinessAPI.SupplierVO>[] = [
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.name' }),
			dataIndex: 'name',
			key: 'name',
		},

		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.idCard',
			}),
			dataIndex: 'idCard',
			key: 'idCard',
			hidden: params?.type !== 'FARMER',
			render: (_, record) => (
				<div className="flex items-center">
					<span>
						{formatIdCard(record.idCard!, showIdCard[record.supplierId])}
					</span>
					<span
						className="ml-2 cursor-pointer"
						onClick={() => {
							setShowIdCard((prev) => ({
								...prev,
								[record.supplierId]: !prev[record.supplierId],
							}));
						}}
					>
						{showIdCard[record.supplierId] ? (
							<EyeTwoTone />
						) : (
							<EyeInvisibleOutlined />
						)}
					</span>
				</div>
			),
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.phone' }),
			dataIndex: 'phone',
			key: 'phone',
			render: (_, record) => (
				<div className="flex items-center">
					<span>{formatPhone(record.phone, showPhone[record.supplierId])}</span>
					<span
						className="ml-2 cursor-pointer"
						onClick={() => {
							setShowPhone((prev) => ({
								...prev,
								[record.supplierId]: !prev[record.supplierId],
							}));
						}}
					>
						{showPhone[record.supplierId] ? (
							<EyeTwoTone />
						) : (
							<EyeInvisibleOutlined />
						)}
					</span>
				</div>
			),
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.bankName' }),
			dataIndex: 'bankName',
			key: 'bankName',
			search: false,
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.bankCard' }),
			dataIndex: 'bankCard',
			key: 'bankCard',
			render: (_, record) => (
				<div className="flex items-center">
					<span>
						{formatBankCard(record.bankCard, showBankCard[record.supplierId])}
					</span>
					<span
						className="ml-2 cursor-pointer"
						onClick={() => {
							setShowBankCard((prev) => ({
								...prev,
								[record.supplierId]: !prev[record.supplierId],
							}));
						}}
					>
						{showBankCard[record.supplierId] ? (
							<EyeTwoTone />
						) : (
							<EyeInvisibleOutlined />
						)}
					</span>
				</div>
			),
		},
		// {
		// 	title: intl.formatMessage({ id: intlPrefix + '.column.wechatQr' }),
		// 	dataIndex: 'wechatQr',
		// 	valueType: 'image',
		// 	key: 'wechatQr',
		// 	search: false,
		// },
		...(initExtraColumns || []),
	];

	function setSupplierVOStorage(supplierVO: BusinessAPI.SupplierVO) {
		const localSupplierList = localStorage.getItem(sessionKey);
		const supplierList = localSupplierList ? JSON.parse(localSupplierList) : [];
		supplierList.forEach((item: BusinessAPI.SupplierVO, index: number) => {
			if (item.supplierId === supplierVO.supplierId) {
				supplierList.splice(index, 1);
			}
		});
		if (supplierList.length < 5) {
			supplierList.unshift(supplierVO);
			localStorage.setItem(sessionKey, JSON.stringify(supplierList));
		} else {
			supplierList.pop();
			supplierList.unshift(supplierVO);
			localStorage.setItem(sessionKey, JSON.stringify(supplierList));
		}
	}

	return (
		<SelectModal<BusinessAPI.SupplierVO, BusinessAPI.SupplierPageQry>
			rowKey={'supplierId'}
			modalProps={{
				title: title || '选择供应商',
				...rest,
				destroyOnHidden: true,
				afterOpenChange: (open) => {
					if (!open) {
						setParams({
							...initParams,
						});
					}
				},
			}}
			selectedList={selectedList}
			tableProps={{
				rowKey: 'supplierId',
				columns: columns,
				columnsState: {
					persistenceType: 'sessionStorage',
					persistenceKey: 'supplierModalColumnStateKey',
				},
				params: {
					...params,
				},
				request: async (params, sorter, filter) => {
					const { data, success, totalCount } =
						await business.supplier.pageSupplier({
							supplierPageQry: 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.SupplierVO>();
					selectedRows.forEach((item: BusinessAPI.SupplierVO) => {
						if (item) {
							if (!selectedRowsMap.has(item.supplierId)) {
								selectedRowsMap.set(item.supplierId, item);
							}
						}
					});
					selectedList?.forEach((item: BusinessAPI.SupplierVO) => {
						if (!selectedRowsMap.has(item.supplierId)) {
							selectedRowsMap.set(item.supplierId, item);
						}
					});
					let selectedTempList: BusinessAPI.SupplierVO[] = [];
					selectedRowsMap.forEach((item: BusinessAPI.SupplierVO) => {
						if (selectedRowKeys.includes(item.supplierId)) {
							selectedTempList.push(item);
						}
					});
					return (
						<span>
							已选 {selectedRowKeys.length} 项{' '}
							{selectedTempList?.map((item: BusinessAPI.SupplierVO) => {
								return item && <span key={item.supplierId}>{item.name}</span>;
							})}
						</span>
					);
				},
				...(tips && {
					tableExtraRender: () => {
						return tips && <Alert type={'info'} message={tips} />;
					},
				}),
				...(type === 'radio' && {
					tableExtraRender: () => {
						const localSupplierList = localStorage.getItem(sessionKey);
						if (localSupplierList) {
							const supplierList = JSON.parse(localSupplierList);
							return (
								<>
									{tips && <Alert type={'info'} message={tips} />}
									<Row gutter={16}>
										{supplierList.map((item: BusinessAPI.SupplierVO) => {
											return (
												<Tag
													style={{
														cursor: 'pointer',
													}}
													onClick={async () => {
														const { data: supplierVO } =
															await business.supplier.showSupplier({
																supplierShowQry: {
																	supplierId: item.supplierId,
																},
															});

														if (supplierVO) {
															onFinish([supplierVO]);
															setSupplierVOStorage(supplierVO);
														}
													}}
													key={item.supplierId}
												>
													{item.name}
												</Tag>
											);
										})}
									</Row>
								</>
							);
						}
					},
				}),
				actionRef: actionRef,
				toolbar: {
					filter: (
						<LightFilter
							onFinish={async (values) => {
								setParams({
									...initParams,
									...values,
								});
							}}
						>
							{extraFilter}
							<ProFormText
								name={'phone'}
								label={intl.formatMessage({ id: intlPrefix + '.column.phone' })}
								placeholder={intl.formatMessage({
									id: intlPrefix + '.column.phone',
								})}
							/>
						</LightFilter>
					),
					search: {
						placeholder: '请输入名称',
						onSearch: async (value: string) => {
							setParams({
								...params,
								name: value,
							});
						},
					},
				},
			}}
			onFinish={(supplierVOList) => {
				if (type === 'radio') {
					if (supplierVOList.length > 0) {
						setSupplierVOStorage(supplierVOList[0]);
					}
				}

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