import {
	BizContainer,
	BizValueType,
	CompanyList,
	CostList,
	ModeType,
	OrderSelect,
} from '@/components';
import { business } from '@/services';
import groupby from '@/utils/groupby';
import { useIntl } from '@@/exports';
import {
	ProColumns,
	ProFormDependency,
	ProFormMoney,
	ProFormText,
} from '@ant-design/pro-components';
import { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import { ProFormBizSelect } from '@chageable/components';
import { ProFormBizSelectHandles } from '@chageable/components/src';
import { Button, Space } from 'antd';
import React, { useRef, useState } from 'react';

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

export default function OrderCostList(props: IOrderCostListProps) {
	const {
		ghost = false,
		orderCostId,
		search = true,
		mode = 'page',
		trigger,
		onValueChange,
	} = props;
	const intl = useIntl();
	const intlPrefix = 'orderCost';
	const costRef = useRef<ProFormBizSelectHandles>(null);

	const [activeKey, setActiveKey] = useState<string>('ALL');

	const columns: ProColumns<BusinessAPI.OrderCostVO, BizValueType>[] = [
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.order' }),
			dataIndex: 'orderVO',
			key: 'orderId',
			valueType: 'order',
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.name' }),
			dataIndex: 'name',
			key: 'costId',
			valueType: 'select',
			fieldProps: {
				fetchDataOnSearch: false,
				showSearch: true,
				autoClearSearchValue: true,
			},
			request: async () => {
				const { data } = await business.cost.listCost({
					costListQry: {},
				});

				const costGroup = groupby(data || [], (item) => item.type);

				const options = Object.keys(costGroup).map((key) => ({
					label: intl.formatMessage({
						id:
							'cost.column.type.enum.' +
							key
								.toLowerCase()
								.replace(/_([a-z])/g, (_, char) => char.toUpperCase()),
					}),
					title: key,
					options: costGroup[key].map((item) => ({
						label: item.name,
						value: item.costId,
					})),
				}));

				return options || [];
			},
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.principal' }),
			dataIndex: 'principal',
			key: 'principal',
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.belong' }),
			dataIndex: 'belong',
			key: 'belong',
			valueType: 'select',
			valueEnum: {
				NONE_TYPE: intl.formatMessage({
					id: intlPrefix + '.column.belong.enum.noneType',
				}),
				WORKER_TYPE: {
					text: intl.formatMessage({
						id: intlPrefix + '.column.belong.enum.workerType',
					}),
				},
				PRODUCTION_TYPE: {
					text: intl.formatMessage({
						id: intlPrefix + '.column.belong.enum.productionType',
					}),
				},
				DRIVER_TYPE: {
					text: intl.formatMessage({
						id: intlPrefix + '.column.belong.enum.driverType',
					}),
				},
			},
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.price' }),
			dataIndex: 'price',
			key: 'price',
			valueType: 'money',
			search: false,
		},
		{
			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.enum.paid',
					}),
					status: 'success',
				},
				false: {
					text: intl.formatMessage({
						id: intlPrefix + '.column.isPaid.enum.unpaid',
					}),
					status: 'processing',
				},
			},
		},
	];

	const formContext = [
		<ProFormBizSelect
			ref={costRef}
			key={'costId'}
			name={'costId'}
			label={intl.formatMessage({
				id: intlPrefix + '.form.costId.label',
			})}
			required={true}
			placeholder={intl.formatMessage({
				id: intlPrefix + '.form.costId.placeholder',
			})}
			rules={[
				{
					required: true,
					message: intl.formatMessage({
						id: intlPrefix + '.form.costId.required',
					}),
				},
			]}
			params={{}}
			fetchOptions={async () => {
				const { data } = await business.cost.listCost({
					costListQry: {
						type: 'LOGISTICS_TYPE',
					},
				});

				const costGroup = groupby(
					data?.filter(
						(item) =>
							item.type === 'LOGISTICS_TYPE' &&
							item.name !== '主运费' &&
							item.name !== '短驳费' &&
							item.name !== '草帘费',
					) || [],
					(item) => item.type,
				);

				const options = Object.keys(costGroup).map((key) => ({
					label: intl.formatMessage({
						id:
							'cost.column.type.enum.' +
							key
								.toLowerCase()
								.replace(/_([a-z])/g, (_, char) => char.toUpperCase()),
					}),
					title: key,
					options: costGroup[key].map((item) => ({
						label: item.name,
						value: item.costId,
					})),
				}));

				return options || [];
			}}
			fieldProps={{
				fetchDataOnSearch: false,
				showSearch: true,
				autoClearSearchValue: true,
			}}
			addonAfter={
				<CostList
					ghost={true}
					search={false}
					mode={'create'}
					onValueChange={async () => costRef.current?.reload()}
				/>
			}
		/>,
		<OrderSelect key={'orderId'} />,
		<ProFormDependency key={'orderVO'} name={['orderVO']}>
			{({ orderVO }, form) => {
				form.setFieldsValue({
					principal: orderVO?.orderVehicle.driver,
				});
				return (
					<>
						{orderVO && (
							<ProFormText
								key={'principal'}
								name={'principal'}
								label={intl.formatMessage({
									id: intlPrefix + '.form.driver.label',
								})}
								placeholder={intl.formatMessage({
									id: intlPrefix + '.form.driver.placeholder',
								})}
								required={true}
								rules={[
									{
										required: true,
										message: intl.formatMessage({
											id: intlPrefix + '.form.driver.required',
										}),
									},
								]}
								readonly={true}
							/>
						)}
						{orderVO && (
							<ProFormMoney
								key={'price'}
								name={'price'}
								label={intl.formatMessage({
									id: intlPrefix + '.form.price.label',
								})}
								placeholder={intl.formatMessage({
									id: intlPrefix + '.form.price.placeholder',
								})}
								required={true}
								rules={[
									{
										required: true,
										message: intl.formatMessage({
											id: intlPrefix + '.form.price.required',
										}),
									},
								]}
								fieldProps={{
									min: 0,
									max: 999999,
									suffix: '元',
								}}
							/>
						)}
					</>
				);
			}}
		</ProFormDependency>,
		<ProFormText key={'count'} name={'count'} hidden={true} />,
		<ProFormText key={'isPaid'} name={'isPaid'} hidden={true} />,
	];

	const [selectedRows, setSelectedRows] = useState<BusinessAPI.OrderCostVO[]>(
		[],
	);

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

	return (
		<BizContainer<
			typeof business.orderCost,
			BusinessAPI.OrderCostVO,
			BusinessAPI.OrderCostPageQry
		>
			rowKey={'orderCostId'}
			permission={'operation-order-cost'}
			func={business.orderCost}
			method={'orderCost'}
			methodUpper={'OrderCost'}
			intlPrefix={intlPrefix}
			modeType={mode}
			onValueChange={onValueChange}
			container={{
				ghost,
			}}
			status={false}
			page={{
				fieldProps: {
					bordered: true,
					ghost,
					//@ts-ignore
					search,
					params: {
						...(activeKey !== 'ALL' && {
							isPaid: activeKey! as any,
						}),
						poStates: ['COMPLETED'],
					},
					rowSelection: {
						type: 'checkbox',
						preserveSelectedRowKeys: true,
						onChange: (_, selectedRows) => setSelectedRows(selectedRows),
						getCheckboxProps: (record: BusinessAPI.OrderCostVO) => ({
							disabled: record.belong === 'NONE_TYPE',
						}),
					},
					tableAlertOptionRender: (props) => {
						return (
							<Space>
								<Button
									key={'cancel'}
									type={'link'}
									onClick={() => props.onCleanSelected()}
									size={'middle'}
								>
									取消选择
								</Button>
							</Space>
						);
					},
					toolbar: {
						menu: {
							type: 'tab',
							activeKey: activeKey,
							items: [
								// 全部
								{
									key: 'ALL',
									label: intl.formatMessage({
										id: intlPrefix + '.tab.all',
									}),
								},
								// 已支付
								{
									key: 'true',
									label: intl.formatMessage({
										id: intlPrefix + '.tab.paid',
									}),
								},
								// 未支付
								{
									key: 'false',
									label: intl.formatMessage({
										id: intlPrefix + '.tab.unpaid',
									}),
								},
							],
							onChange: (key) => {
								setActiveKey(key as string);
							},
						},
					},
				},
				columns,
			}}
			create={{
				formType: 'drawer',
				formContext,
				trigger,
				initValues: {
					isPaid: false,
					count: 1,
				},
			}}
			update={false}
			destroy={false}
			detail={{
				rowId: orderCostId,
				formType: 'drawer',
				columns: detailColumns,
				trigger,
			}}
		/>
	);
}
