import {
	BizContainer,
	BizValueType,
	CostItemList,
	ModeType,
	ProFormBizSelect,
	ProFormBizSelectHandles,
} from '@/components';
import { business } from '@/services';
import groupby from '@/utils/groupby';
import { useIntl } from '@@/exports';
import {
	ProColumns,
	ProFormDependency,
	ProFormMoney,
	ProFormRadio,
	ProFormSelect,
	ProFormText,
} from '@ant-design/pro-components';
import { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import React, { useRef, useState } from 'react';

interface ICostListProps {
	ghost?: boolean;
	costId?: BusinessAPI.CostVO['costId'];
	search?: boolean;
	onValueChange?: () => void;
	mode?: ModeType;
	trigger?: () => React.ReactNode;
}
export default function CostList(props: ICostListProps) {
	const {
		ghost = false,
		costId,
		search = true,
		mode = 'drag',
		trigger,
		onValueChange,
	} = props;
	const intl = useIntl();
	const intlPrefix = 'cost';
	const [type, setType] =
		useState<BusinessAPI.CostPageQry['type']>('MATERIAL_TYPE');
	const costRef = useRef<ProFormBizSelectHandles>(null);

	const columns: ProColumns<BusinessAPI.CostVO, BizValueType>[] = [
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.name' }),
			dataIndex: 'name',
			key: 'name',
			renderText: (text: string) => <span className="font-medium">{text}</span>,
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.unit' }),
			dataIndex: 'unit',
			key: 'unit',
			search: false,
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.price' }),
			dataIndex: 'price',
			key: 'price',
			valueType: 'money',
			search: false,
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.type' }),
			dataIndex: 'type',
			key: 'type',
			valueType: 'select',
			valueEnum: {
				MATERIAL_TYPE: intl.formatMessage({
					id: intlPrefix + '.column.type.enum.materialType',
				}),
				ARTIFICIAL_TYPE: intl.formatMessage({
					id: intlPrefix + '.column.type.enum.artificialType',
				}),
				PRODUCTION_TYPE: intl.formatMessage({
					id: intlPrefix + '.column.type.enum.productionType',
				}),
				OTHER_TYPE: intl.formatMessage({
					id: intlPrefix + '.column.type.enum.otherType',
				}),
				LOGISTICS_TYPE: intl.formatMessage({
					id: intlPrefix + '.column.type.enum.logisticsType',
				}),
			},
			search: false,
		},
		{
			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: intl.formatMessage({
					id: intlPrefix + '.column.belong.enum.workerType',
				}),
				PRODUCTION_TYPE: intl.formatMessage({
					id: intlPrefix + '.column.belong.enum.productionType',
				}),
				DRIVER_TYPE: intl.formatMessage({
					id: intlPrefix + '.form.belong.enum.driverType',
				}),
			},
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.costItemIds',
			}),
			dataIndex: 'constItemVOList',
			key: 'costItemIds',
			valueType: 'text',
			render: (_, record) => (
				<div>{record.costItemVOList?.map((item) => item.name).join(',')}</div>
			),
			search: false,
			hidden:
				type === 'PRODUCTION_TYPE' ||
				type === 'OTHER_TYPE' ||
				type === 'LOGISTICS_TYPE',
		},
	];

	const formContext = [
		<ProFormText key={'type'} name={'type'} hidden={true} />,
		<ProFormText
			key={'name'}
			name={'name'}
			label={intl.formatMessage({ id: intlPrefix + '.form.name.label' })}
			required={true}
			placeholder={intl.formatMessage({
				id: intlPrefix + '.form.name.placeholder',
			})}
			rules={[
				{
					required: true,
					message: intl.formatMessage({
						id: intlPrefix + '.form.name.required',
					}),
				},
			]}
		/>,
		<ProFormText
			key={'unit'}
			name={'unit'}
			label={intl.formatMessage({ id: intlPrefix + '.form.unit.label' })}
			placeholder={intl.formatMessage({
				id: intlPrefix + '.form.unit.placeholder',
			})}
		/>,
		<ProFormMoney
			key={'price'}
			name={'price'}
			label={intl.formatMessage({ id: intlPrefix + '.form.price.label' })}
			placeholder={intl.formatMessage({
				id: intlPrefix + '.form.price.placeholder',
			})}
			fieldProps={{
				precision: 2,
			}}
		/>,
		// type
		<ProFormSelect
			key={'type'}
			name={'type'}
			label={intl.formatMessage({ id: intlPrefix + '.form.type.label' })}
			required={true}
			placeholder={intl.formatMessage({
				id: intlPrefix + '.form.type.placeholder',
			})}
			rules={[
				{
					required: true,
					message: intl.formatMessage({
						id: intlPrefix + '.form.type.required',
					}),
				},
			]}
			valueEnum={{
				MATERIAL_TYPE: intl.formatMessage({
					id: intlPrefix + '.form.type.enum.materialType',
				}),
				ARTIFICIAL_TYPE: intl.formatMessage({
					id: intlPrefix + '.form.type.enum.artificialType',
				}),
				PRODUCTION_TYPE: intl.formatMessage({
					id: intlPrefix + '.form.type.enum.productionType',
				}),
				OTHER_TYPE: intl.formatMessage({
					id: intlPrefix + '.form.type.enum.otherType',
				}),
				LOGISTICS_TYPE: intl.formatMessage({
					id: intlPrefix + '.form.type.enum.logisticsType',
				}),
			}}
		/>,
		// belong
		<ProFormRadio.Group
			key={'belong'}
			name={'belong'}
			label={intl.formatMessage({ id: intlPrefix + '.form.belong.label' })}
			required={true}
			rules={[
				{
					required: true,
					message: intl.formatMessage({
						id: intlPrefix + '.form.belong.required',
					}),
				},
			]}
			valueEnum={{
				NONE_TYPE: intl.formatMessage({
					id: intlPrefix + '.form.belong.enum.noneType',
				}),
				WORKER_TYPE: intl.formatMessage({
					id: intlPrefix + '.form.belong.enum.workerType',
				}),
				PRODUCTION_TYPE: intl.formatMessage({
					id: intlPrefix + '.form.belong.enum.productionType',
				}),
				DRIVER_TYPE: intl.formatMessage({
					id: intlPrefix + '.form.belong.enum.driverType',
				}),
			}}
		/>,
		<ProFormDependency key={'type'} name={['type']}>
			{({ type }) => {
				return (
					(type === 'MATERIAL_TYPE' || type === 'ARTIFICIAL_TYPE') && (
						<ProFormBizSelect
							ref={costRef}
							key={'costItemIds'}
							name={'costItemIds'}
							label={intl.formatMessage({
								id: intlPrefix + '.form.costItemIds.label',
							})}
							required={true}
							placeholder={intl.formatMessage({
								id: intlPrefix + '.form.costItemIds.placeholder',
							})}
							rules={[
								{
									required: true,
									message: intl.formatMessage({
										id: intlPrefix + '.form.costItemIds.required',
									}),
								},
							]}
							params={{}}
							fetchOptions={async () => {
								const { data } = await business.costItem.listCostItem({
									costItemListQry: {},
								});

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

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

								return options || [];
							}}
							fieldProps={{
								mode: 'multiple',
								fetchDataOnSearch: false,
								showSearch: true,
								autoClearSearchValue: true,
							}}
							addonAfter={
								<CostItemList
									ghost={true}
									search={false}
									mode={'create'}
									onValueChange={async () => costRef.current?.reload()}
								/>
							}
						/>
					)
				);
			}}
		</ProFormDependency>,
	];

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

	return (
		<BizContainer<
			typeof business.cost,
			BusinessAPI.CostVO,
			BusinessAPI.CostPageQry,
			BusinessAPI.CostCreateCmd,
			BusinessAPI.CostUpdateCmd
		>
			rowKey={'costId'}
			permission={'operation-cost'}
			func={business.cost}
			method={'cost'}
			methodUpper={'Cost'}
			intlPrefix={intlPrefix}
			modeType={mode}
			onValueChange={onValueChange}
			container={{
				ghost,
				fieldProps: {
					tabActiveKey: type,
					onTabChange: (key) => {
						setType(key as BusinessAPI.CostPageQry['type']);
					},
					tabList: [
						{
							key: 'MATERIAL_TYPE',
							tab: intl.formatMessage({
								id: intlPrefix + '.type.materialType',
							}),
						},
						{
							key: 'ARTIFICIAL_TYPE',
							tab: intl.formatMessage({
								id: intlPrefix + '.type.artificialType',
							}),
						},
						{
							key: 'PRODUCTION_TYPE',
							tab: intl.formatMessage({
								id: intlPrefix + '.type.productionType',
							}),
						},
						{
							key: 'OTHER_TYPE',
							tab: intl.formatMessage({
								id: intlPrefix + '.type.otherType',
							}),
						},
						{
							key: 'LOGISTICS_TYPE',
							tab: intl.formatMessage({
								id: intlPrefix + '.type.logisticsType',
							}),
						},
					],
				},
			}}
			remark={{
				mode: 'editor',
			}}
			status
			drag={{
				fieldProps: {
					bordered: true,
					ghost,
					//@ts-ignore
					search,
					params: {
						type: type,
					},
				},
				columns,
			}}
			create={{
				formType: 'drawer',
				formContext,
				initValues: {
					type: type,
					status: true,
				},
			}}
			update={{
				formType: 'drawer',
				formContext,
			}}
			destroy={{}}
			detail={{
				rowId: costId,
				formType: 'drawer',
				columns: detailColumns,
				trigger,
			}}
		/>
	);
}
