import {
	BizContainer,
	BizValueType,
	ButtonAccess,
	ModeType,
	OrderList,
	OrderSupplierList,
	SupplierFarmerList,
} from '@/components';
import { business } from '@/services';
import { downloadImagesAsZip } from '@/utils/download';
import { useIntl } from '@@/exports';
import { DownloadOutlined, EyeOutlined } from '@ant-design/icons';
import { ProColumns } from '@ant-design/pro-components';
import { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import { Image, Modal, Space, Typography } from 'antd';
import React, { useState } from 'react';

const { Text } = Typography;

interface ISupplierInvoiceListProps {
	ghost?: boolean;
	supplierInvoiceId?: BusinessAPI.SupplierInvoiceVO['supplierInvoiceId'];
	search?: boolean;
	onValueChange?: () => void;
	mode?: ModeType;
	trigger?: () => React.ReactNode;
}

export default function SupplierInvoiceList(props: ISupplierInvoiceListProps) {
	const {
		ghost = false,
		supplierInvoiceId,
		search = true,
		mode = 'page',
		trigger,
		onValueChange,
	} = props;
	const intl = useIntl();
	const intlPrefix = 'supplierInvoice';

	// 发票预览相关状态
	const [invoiceVisible, setInvoiceVisible] = useState(false);
	const [currentRecord, setCurrentRecord] =
		useState<BusinessAPI.SupplierInvoiceVO | null>(null);

	const columns: ProColumns<BusinessAPI.SupplierInvoiceVO, BizValueType>[] = [
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.invoiceSn' }),
			dataIndex: 'invoiceSn',
			key: 'invoiceSn',
			render: (_, record) => {
				return (
					<SupplierInvoiceList
						ghost={true}
						mode={'detail'}
						supplierInvoiceId={record.supplierInvoiceId}
						trigger={() => (
							<Space>
								<a>{record.invoiceSn}</a>
							</Space>
						)}
					/>
				);
			},
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.supplierName' }),
			dataIndex: 'supplierVO',
			key: 'supplierId',
			valueType: 'supplier',
			render: (_, record) => {
				return (
					<SupplierFarmerList
						key={record.supplierId}
						ghost={true}
						mode={'detail'}
						supplierId={record.supplierId}
						trigger={() => (
							<Space>
								<a>{record.supplierName}</a>
							</Space>
						)}
					/>
				);
			},
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.invoiceAmount' }),
			dataIndex: 'orderSupplierInvoiceList',
			key: 'invoiceAmount',
			valueType: 'money',
			search: false,
			renderText: (_, record) => {
				const totalAmount = record.orderSupplierInvoiceList?.reduce(
					(sum, item) => sum + (item.invoiceAmount || 0),
					0,
				);
				return totalAmount || 0;
			},
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.supplier' }),
			dataIndex: 'supplier',
			key: 'supplier',
			search: false,
			render: (_, record) => {
				return record.orderSupplierInvoiceList?.map((item) => {
					return (
						<SupplierFarmerList
							key={item.supplierId}
							ghost={true}
							mode={'detail'}
							supplierId={item.supplierId}
							trigger={() => (
								<Space>
									<a>{item.name}</a>
								</Space>
							)}
						/>
					);
				});
			},
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.order' }),
			dataIndex: 'order',
			search: false,
			render: (_, record) => {
				return record.orderSupplierInvoiceList?.map((item) => {
					return (
						<OrderList
							key={item.orderId}
							ghost={true}
							mode={'detail'}
							orderId={item.orderId}
							trigger={() => (
								<Space>
									<a>
										{`${item?.dealerName} | 第 ${item?.vehicleNo || '暂无'} 车`}
									</a>
								</Space>
							)}
						/>
					);
				});
			},
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.registrationTime',
			}),
			dataIndex: 'registrationTime',
			key: 'registrationTime',
			valueType: 'dateTime',
			search: false,
		},
	];

	const detailColumns: ProDescriptionsItemProps<
		BusinessAPI.SupplierInvoiceVO,
		BizValueType
	>[] = columns as ProDescriptionsItemProps<
		BusinessAPI.SupplierInvoiceVO,
		BizValueType
	>[];

	// 查看发票
	const handleViewInvoice = (record: BusinessAPI.SupplierInvoiceVO) => {
		setCurrentRecord(record);
		setInvoiceVisible(true);
	};

	// 下载发票
	const handleDownloadInvoice = async (
		record: BusinessAPI.SupplierInvoiceVO,
	) => {
		if (record.invoiceImg && record.invoiceImg.length > 0) {
			const fileName = `${record.supplierName}_发票_${record.invoiceSn}`;
			await downloadImagesAsZip(record.invoiceImg, fileName);
		}
	};

	const detailContext = (supplierInvoiceVO: BusinessAPI.SupplierInvoiceVO) => {
		return [
			{
				label: `发票开具人`,
				key: 'supplierVO',
				children: (
					<SupplierFarmerList
						supplierId={supplierInvoiceVO.supplierId}
						ghost={true}
						mode={'detail'}
						trigger={() => <a>{supplierInvoiceVO.supplierName}</a>}
					/>
				),
			},
			{
				label: `关联车次`,
				key: 'orderSupplierInvoiceList',
				children: (
					<OrderSupplierList
						ghost={true}
						search={false}
						supplierInvoiceVO={supplierInvoiceVO}
					/>
				),
			},
			{
				label: `发票文件`,
				key: 'invoiceImg',
				children: (
					<Space direction="vertical" size="middle" style={{ width: '100%' }}>
						{supplierInvoiceVO.invoiceImg &&
						supplierInvoiceVO.invoiceImg.length > 0 ? (
							<>
								{supplierInvoiceVO.invoiceImg.map((item, index) => (
									<div key={index} style={{ marginBottom: 16 }}>
										<div style={{ marginBottom: 8 }}>
											<Text type="secondary">文件 {index + 1}：</Text>
											<Text>{item.fileName || `发票${index + 1}`}</Text>
										</div>
										<Image
											width={200}
											src={item.filePath}
											alt={item.fileName || `发票${index + 1}`}
											style={{
												border: '1px solid #E5E7EB',
												borderRadius: 8,
												padding: 8,
												backgroundColor: '#F9FAFB',
											}}
										/>
										<div style={{ marginTop: 8 }}>
											<ButtonAccess
												permission="operation-supplier-invoice-view-invoice"
												type="link"
												icon={<EyeOutlined />}
												onClick={() => handleViewInvoice(supplierInvoiceVO)}
											>
												预览
											</ButtonAccess>
											<ButtonAccess
												permission="operation-supplier-invoice-download-invoice"
												type="link"
												icon={<DownloadOutlined />}
												onClick={() => handleDownloadInvoice(supplierInvoiceVO)}
											>
												下载
											</ButtonAccess>
										</div>
									</div>
								))}
							</>
						) : (
							<Text type="secondary">暂无发票文件</Text>
						)}
					</Space>
				),
			},
		];
	};

	return (
		<>
			<BizContainer<
				typeof business.supplierInvoice,
				BusinessAPI.SupplierInvoiceVO,
				BusinessAPI.SupplierInvoicePageQry,
				BusinessAPI.SupplierInvoiceCreateCmd,
				BusinessAPI.SupplierInvoiceUpdateCmd
			>
				rowKey={'supplierInvoiceId'}
				permission={'operation-supplier-invoice'}
				func={business.supplierInvoice}
				method={'supplierInvoice'}
				methodUpper={'SupplierInvoice'}
				intlPrefix={intlPrefix}
				modeType={mode}
				onValueChange={onValueChange}
				container={{
					ghost,
				}}
				remark={{
					mode: 'editor',
				}}
				page={{
					fieldProps: {
						bordered: true,
						ghost,
						//@ts-ignore
						search,
						params: {
							poStates: ['COMPLETED'],
						},
					},
					columns,
					options: (supplierInvoiceVO) => {
						return [
							<ButtonAccess
								permission="operation-supplier-invoice-view-invoice"
								insertPosition={'before:view'}
								key="view-invoice"
								type="link"
								icon={<EyeOutlined />}
								onClick={() => handleViewInvoice(supplierInvoiceVO)}
							>
								查看发票
							</ButtonAccess>,
							<ButtonAccess
								permission="operation-supplier-invoice-download-invoice"
								insertPosition={'before:view'}
								key="download-invoice"
								type="link"
								icon={<DownloadOutlined />}
								onClick={() => handleDownloadInvoice(supplierInvoiceVO)}
							>
								下载发票
							</ButtonAccess>,
						];
					},
				}}
				create={false}
				update={{
					formType: 'drawer',
				}}
				destroy={{}}
				detail={{
					rowId: supplierInvoiceId,
					formType: 'drawer',
					columns: detailColumns,
					formContext: detailContext,
					formContextMode: 'flat',
					trigger,
				}}
			/>

			{/* 发票预览Modal */}
			<Modal
				title="查看发票"
				open={invoiceVisible}
				onCancel={() => setInvoiceVisible(false)}
				footer={null}
				width={800}
				centered
			>
				{currentRecord?.invoiceImg && currentRecord.invoiceImg.length > 0 ? (
					<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
						{currentRecord.invoiceImg.map((item, index) => (
							<div key={index} style={{ textAlign: 'center' }}>
								<p style={{ marginBottom: 8 }}>发票 {index + 1}</p>
								<Image
									width="100%"
									height={400}
									src={item.filePath}
									alt={item.fileName || `发票${index + 1}`}
									placeholder={
										<div style={{ color: '#9CA3AF' }}>加载中...</div>
									}
								/>
								<p
									style={{
										fontSize: 14,
										color: '#6B7280',
										marginTop: 8,
										marginBottom: 0,
									}}
								>
									{item.fileName || `发票${index + 1}`}
								</p>
							</div>
						))}
					</div>
				) : (
					<div
						style={{
							textAlign: 'center',
							padding: '32px 0',
							color: '#6B7280',
						}}
					>
						暂无发票图片
					</div>
				)}
			</Modal>
		</>
	);
}
