import { IconFont } from '@/components';
import MenuPathPicker from '@/components/Biz/MenuPathPicker';
import IconPicker from '@/components/Iconfont/IconPicker';
import { business } from '@/services';
import { formLayout } from '@/utils/formLayout';
import {
	DragSortTable,
	ModalForm,
	ProCard,
	ProForm,
	ProFormDigit,
	ProFormText,
} from '@ant-design/pro-components';
import { Button, Col, message, Popconfirm, Row, Space } from 'antd';
import { useState } from 'react';
import { v4 as uuidv4 } from 'uuid';

interface ICustomMenuConfigProps {
	onFinish?: (menuItems: BusinessAPI.MenuItem[]) => void;
}

export default function CustomMenuConfig(props: ICustomMenuConfigProps) {
	const { onFinish } = props;
	const [dataSource, setDataSource] = useState<BusinessAPI.MenuItem[]>([]);
	const [isModalVisible, setIsModalVisible] = useState(false);
	const [editingItem, setEditingItem] = useState<BusinessAPI.MenuItem | null>(
		null,
	);

	const handleDragSortEnd = (
		beforeIndex: number,
		afterIndex: number,
		newDataSource: any,
	) => {
		console.log('排序后的数据', newDataSource);
		setDataSource(newDataSource);
		message.success('修改列表排序成功');
	};

	const showModal = (item?: BusinessAPI.MenuItem) => {
		if (item) {
			setEditingItem(item);
		} else {
			setEditingItem(null);
		}
		setIsModalVisible(true);
	};

	const handleModalOk = (modalForm: any) => {
		if (!modalForm.menuName || !modalForm.menuIcon || !modalForm.menuRedirect) {
			message.error('请填写完整信息');
			return;
		}

		console.log('modalForm', modalForm);

		if (editingItem) {
			// 编辑现有菜单项
			const updatedDataSource = dataSource.map((item) => {
				if (item.menuId === editingItem.menuId) {
					return {
						...item,
						...modalForm,
					};
				}
				return item;
			});
			setDataSource(updatedDataSource);
			onFinish?.(updatedDataSource);
		} else {
			// 添加新菜单项
			const newItem = {
				menuId: uuidv4(),
				...modalForm,
			};
			setDataSource([...dataSource, newItem]);
			onFinish?.([...dataSource, newItem]);
		}
		setIsModalVisible(false);
	};

	const handleModalCancel = () => {
		setIsModalVisible(false);
		setEditingItem(null);
	};

	return (
		<>
			<ProCard
				style={{
					marginLeft: '16px',
				}}
				title={'自定义菜单配置'}
				extra={
					<Button type={'link'} size={'middle'} onClick={() => showModal()}>
						添加菜单
					</Button>
				}
			>
				<ProForm<BusinessAPI.CustomMenuConfigValue>
					{...formLayout()}
					request={async () => {
						const { data } = await business.setting.showSetting({
							settingShowQry: {
								settingKey: 'CUSTOM_MENU_CONFIG',
							},
						});

						const customMenuConfigValue =
							data?.settingValue as BusinessAPI.CustomMenuConfigValue;
						const menuItems = customMenuConfigValue?.menuItems || [];
						setDataSource(
							menuItems.map((item, index) => ({
								...item,
								menuId: item.menuId || uuidv4(),
								menuSort: item.menuSort !== undefined ? item.menuSort : index,
							})),
						);
						return {
							...customMenuConfigValue,
						} as BusinessAPI.CustomMenuConfigValue;
					}}
					onFinish={async (values) => {
						await business.setting.updateSetting({
							settingKey: 'CUSTOM_MENU_CONFIG',
							settingValue: {
								...values,
								menuItems: dataSource,
								settingKey: 'CUSTOM_MENU_CONFIG',
							},
						});

						message.success('更新自定义菜单配置成功');
					}}
					submitter={{
						render: (_, dom) => {
							return (
								<Row
									style={{
										marginTop: '24px',
									}}
								>
									<Col span={14} offset={4}>
										<Space>{dom}</Space>
									</Col>
								</Row>
							);
						},
					}}
				>
					<ProFormText hidden={true} name={'settingId'} />
					<ProCard ghost={true}>
						<DragSortTable
							scroll={{ x: 'max-content' }}
							rowKey={'menuId'}
							ghost={true}
							search={false}
							options={false}
							dataSource={dataSource}
							dragSortKey="sort"
							onDragSortEnd={handleDragSortEnd}
							columns={[
								{
									title: '排序',
									dataIndex: 'menuSort',
									key: 'sort',
								},
								{
									title: '菜单名称',
									dataIndex: 'menuName',
								},
								{
									title: '菜单图标',
									dataIndex: 'menuIcon',
									render: (_, record) => <IconFont type={record.menuIcon} />,
								},
								{
									title: '菜单链接',
									dataIndex: 'menuRedirect',
									render: (_, record) => {
										// @ts-ignore
										return record.menuRedirect?.path;
									},
								},
								{
									title: '操作',
									valueType: 'option',
									key: 'option',
									render: (_, record) => {
										return (
											<Space>
												<Button
													size={'small'}
													type={'link'}
													onClick={() => showModal(record)}
												>
													编辑
												</Button>
												<Popconfirm
													title="确认移除该项？"
													onConfirm={() => {
														setDataSource(
															dataSource?.filter(
																(item) => item.menuId !== record.menuId,
															),
														);

														onFinish?.(
															dataSource?.filter(
																(item) => item.menuId !== record.menuId,
															),
														);
													}}
													okText="确认"
													cancelText="取消"
												>
													<Button size={'small'} type={'link'} danger={true}>
														移除
													</Button>
												</Popconfirm>
											</Space>
										);
									},
								},
							]}
							pagination={false}
						/>
					</ProCard>
				</ProForm>

				<ModalForm
					{...formLayout()}
					title={editingItem ? '编辑菜单' : '添加菜单'}
					open={isModalVisible}
					request={async () => {
						return editingItem || {};
					}}
					onFinish={async (values) => {
						console.log('values', values);
						handleModalOk(values);
						return true;
					}}
					onOpenChange={(open) => {
						if (!open) {
							handleModalCancel();
						}
					}}
					modalProps={{
						destroyOnHidden: true,
					}}
					width={800}
				>
					<ProFormText
						name={'menuName'}
						label="菜单名称"
						required={true}
						rules={[{ required: true, message: '请输入菜单名称' }]}
					/>

					<IconPicker
						label="菜单图标"
						name="menuIcon"
						required={true}
						rules={[{ required: true, message: '请选择图标' }]}
					/>

					<MenuPathPicker
						label="菜单链接"
						name="menuRedirect"
						required={true}
						rules={[{ required: true, message: '请选择菜单链接' }]}
					/>

					<ProFormDigit
						label="菜单排序"
						name="menuSort"
						fieldProps={{
							min: 0,
						}}
					/>
				</ModalForm>
			</ProCard>
		</>
	);
}
