import { BizContainer, BizValueType, ModeType } from '@/components';
import { business } from '@/services';
import { useIntl } from '@@/exports';
import {
	ProColumns,
	ProFormDependency,
	ProFormItem,
	ProFormSelect,
	ProFormText,
	ProFormTextArea,
} from '@ant-design/pro-components';
import { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import { Button, Space, Tag, Typography } from 'antd';
import React from 'react';

interface INotifyMessageTemplateListProps {
	ghost?: boolean;
	search?: boolean;
	onValueChange?: () => void;
	mode?: ModeType;
	trigger?: () => React.ReactNode;
}

const variables = [
	// 采购单
	'经销商简称',
	'车次号',
	'车牌号',
	'目的地',
	'录入员姓名',
	'录入员提审时间',
	// 采购单审核
	'审核员姓名',
	'审核员审核时间',
	'审核员驳回原因',
	// 采购单审批
	'审批员姓名',
	'审批员审批时间',
	'审批员驳回原因',
];

export default function NotifyMessageTemplateList(
	props: INotifyMessageTemplateListProps,
) {
	const {
		ghost = false,
		search = true,
		mode = 'page',
		trigger,
		onValueChange,
	} = props;
	const intl = useIntl();
	const intlPrefix = 'notifyMessageTemplate';

	// 模板分类映射
	const templateCategoryMap: Record<string, { label: string }> = {
		PURCHASE_ORDER_MESSAGE_TEMPLATE: {
			label: intl.formatMessage({
				id: intlPrefix + '.templateCategory.purchaseOrderMessageTemplate',
			}),
		},
	};
	// 模板事件映射
	const templateSceneMap: Record<string, { label: string }> = {
		WAIT_AUDIT: {
			label: intl.formatMessage({
				id: intlPrefix + '.templateScene.waitAudit',
			}),
		},
		WAIT_APPROVE: {
			label: intl.formatMessage({
				id: intlPrefix + '.templateScene.waitApprove',
			}),
		},
		APPROVE_PASS: {
			label: intl.formatMessage({
				id: intlPrefix + '.templateScene.approvePass',
			}),
		},
		AUDIT_REJECT: {
			label: intl.formatMessage({
				id: intlPrefix + '.templateScene.auditReject',
			}),
		},
		APPROVE_REJECT: {
			label: intl.formatMessage({
				id: intlPrefix + '.templateScene.approveReject',
			}),
		},
	};

	// 表单上下文
	const formContext = [
		<ProFormText
			key={'messageTemplateId'}
			name={'messageTemplateId'}
			hidden={true}
		/>,
		<ProFormSelect
			key={'templateCategory'}
			name={'templateCategory'}
			label={intl.formatMessage({
				id: intlPrefix + '.form.templateCategory.label',
			})}
			required={true}
			placeholder={intl.formatMessage({
				id: intlPrefix + '.form.templateCategory.placeholder',
			})}
			rules={[
				{
					required: true,
					message: intl.formatMessage({
						id: intlPrefix + '.form.templateCategory.required',
					}),
				},
			]}
			options={Object.keys(templateCategoryMap).map((key) => ({
				label: templateCategoryMap[key].label,
				value: key,
			}))}
		/>,
		<ProFormSelect
			key={'templateScene'}
			name={'templateScene'}
			label={intl.formatMessage({
				id: intlPrefix + '.form.templateScene.label',
			})}
			required={true}
			placeholder={intl.formatMessage({
				id: intlPrefix + '.form.templateScene.placeholder',
			})}
			rules={[
				{
					required: true,
					message: intl.formatMessage({
						id: intlPrefix + '.form.templateScene.required',
					}),
				},
			]}
			options={Object.keys(templateSceneMap).map((key) => ({
				label: templateSceneMap[key].label,
				value: key,
			}))}
		/>,
		<ProFormText
			key={'titleTemplate'}
			name={'titleTemplate'}
			label={intl.formatMessage({
				id: intlPrefix + '.form.titleTemplate.label',
			})}
			required={true}
			placeholder={intl.formatMessage({
				id: intlPrefix + '.form.titleTemplate.placeholder',
			})}
			rules={[
				{
					required: true,
					message: intl.formatMessage({
						id: intlPrefix + '.form.titleTemplate.required',
					}),
				},
			]}
		/>,
		<ProFormTextArea
			key={'description'}
			name={'description'}
			label={intl.formatMessage({
				id: intlPrefix + '.form.description.label',
			})}
			placeholder={intl.formatMessage({
				id: intlPrefix + '.form.description.placeholder',
			})}
			fieldProps={{
				autoSize: { minRows: 3, maxRows: 6 },
				showCount: true,
				maxLength: 200,
			}}
		/>,
		<ProFormTextArea
			key={'contentTemplate'}
			name={'contentTemplate'}
			label={intl.formatMessage({
				id: intlPrefix + '.form.contentTemplate.label',
			})}
			required={true}
			placeholder={intl.formatMessage({
				id: intlPrefix + '.form.contentTemplate.placeholder',
			})}
			rules={[
				{
					required: true,
					message: intl.formatMessage({
						id: intlPrefix + '.form.contentTemplate.required',
					}),
				},
			]}
			tooltip={intl.formatMessage({
				id: intlPrefix + '.form.contentTemplate.tooltip',
			})}
			fieldProps={{
				autoSize: { minRows: 5, maxRows: 10 },
				showCount: true,
				maxLength: 2000,
			}}
		/>,
		<ProFormDependency key={'variables'} name={['contentTemplate']}>
			{({ contentTemplate }, form) => (
				<ProFormItem
					style={{
						width: '100%',
					}}
					label={'模板变量'}
					tooltip={intl.formatMessage({
						id: intlPrefix + '.form.contentTemplate.insertVariable',
					})}
				>
					<>
						{variables.length === 0 ? (
							<Typography.Text type="secondary" className="text-sm">
								{intl.formatMessage({
									id: intlPrefix + '.form.contentTemplate.noVariables',
								})}
							</Typography.Text>
						) : (
							<Space wrap size={[8, 8]}>
								{variables.map((variable: string) => (
									<Button
										key={variable}
										type="dashed"
										size="small"
										onClick={() => {
											form.setFieldValue(
												'contentTemplate',
												`${contentTemplate || ''}{{${variable}}}`,
											);
										}}
									>
										{`{{${variable}}}`}
									</Button>
								))}
							</Space>
						)}
					</>
				</ProFormItem>
			)}
		</ProFormDependency>,
		<ProFormSelect
			key={'roleIds'}
			name={'roleIds'}
			label={'关联角色'}
			placeholder="请选择关联角色"
			required={true}
			rules={[
				{
					required: true,
					message: '请选择角色',
				},
			]}
			showSearch={true}
			fieldProps={{
				mode: 'multiple',
			}}
			request={async (params) => {
				const data = await business.role.listRole({
					roleListQry: {
						...params,
					},
				});

				return (
					data?.data?.map((item) => ({
						label: item.platformVO?.platformName + '-' + item.name,
						value: item.roleId,
					})) ?? []
				);
			}}
		/>,
	];

	const columns: ProColumns<BusinessAPI.MessageTemplateVO, BizValueType>[] = [
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.templateCategory',
			}),
			dataIndex: 'templateCategory',
			key: 'templateCategory',
			valueType: 'select',
			valueEnum: Object.entries(templateCategoryMap).reduce(
				(acc, [key, value]) => ({
					...acc,
					[key]: { text: value.label },
				}),
				{},
			),
			render: (_, record) => {
				const categoryInfo = templateCategoryMap[record.templateCategory];
				return categoryInfo ? (
					<Tag>{categoryInfo.label}</Tag>
				) : (
					<Tag>{record.templateCategory}</Tag>
				);
			},
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.templateScene',
			}),
			dataIndex: 'templateScene',
			key: 'templateScene',
			valueType: 'select',
			valueEnum: Object.entries(templateSceneMap).reduce(
				(acc, [key, value]) => ({
					...acc,
					[key]: { text: value.label },
				}),
				{},
			),
			render: (_, record) => {
				const sceneInfo = templateSceneMap[record.templateScene];
				return sceneInfo ? (
					<Tag>{sceneInfo.label}</Tag>
				) : (
					<Tag>{record.templateScene}</Tag>
				);
			},
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.titleTemplate' }),
			dataIndex: 'titleTemplate',
			key: 'titleTemplate',
			valueType: 'text',
			ellipsis: true,
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.contentTemplate' }),
			dataIndex: 'contentTemplate',
			key: 'contentTemplate',
			valueType: 'text',
			ellipsis: true,
			render: (_, record) => {
				return <pre>{record.contentTemplate}</pre>;
			},
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.description' }),
			dataIndex: 'description',
			key: 'description',
			valueType: 'text',
			ellipsis: true,
			search: false,
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.role' }),
			dataIndex: 'roleIds',
			key: 'roleIds',
			valueType: 'select',
			request: async (params) => {
				const data = await business.role.listRole({
					roleListQry: {
						...params,
					},
				});

				return (
					data?.data?.map((item) => ({
						label: item.platformVO?.platformName + '-' + item.name,
						value: item.roleId,
					})) ?? []
				);
			},
		},
	];

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

	return (
		<BizContainer<
			typeof business.messageTemplate,
			BusinessAPI.MessageTemplateVO,
			BusinessAPI.MessageTemplatePageQry
		>
			rowKey={'messageTemplateId'}
			permission={'operation-notify-message-template'}
			func={business.messageTemplate}
			method={'messageTemplate'}
			methodUpper={'MessageTemplate'}
			intlPrefix={intlPrefix}
			modeType={mode}
			onValueChange={onValueChange}
			container={{ ghost }}
			remark={{
				mode: 'editor',
			}}
			status={true}
			page={{
				fieldProps: {
					bordered: true,
					ghost,
					//@ts-ignore
					search,
				},
				columns,
				options: () => [],
			}}
			create={{
				formType: 'drawer',
				formContext,
				initValues: {
					status: true,
				},
			}}
			update={{
				formType: 'drawer',
				formContext,
			}}
			destroy={false}
			detail={{
				formType: 'drawer',
				columns: detailColumns,
				trigger,
			}}
		/>
	);
}
