import React, { useState, useEffect, useRef } from 'react';
import styles from './index.less';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, message, Modal, Row, Col, Form, Input, Popconfirm, TreeSelect, Select, Switch, Tag } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import * as Icon from '@ant-design/icons';
import moduleAPI from '@/api/ModuleAPI';

const SystemManagement: React.FC = () => {

	const [currentPage, setCurrentPage] = useState<number>(1);
	const [isModalVisible, setIsModalVisible] = useState(false);
	const [currentMenu, setCurrentMenu] = useState<ModuleTypes.ModuleType>({
		category: 0,
		openType: 0,
		parentId: '',
		name: '',
		icon: '',
		url: '',
		sort: 0,
		isDisabled: true,
		id: '',
		children: []
	});
	const [menuTree, setMenuTree] = useState<ModuleTypes.ModuleType[]>([]);
	const [menuTreeSelect, setMenuTreeSelect] = useState('');

	const [menuForm] = Form.useForm();
	const tableRef = useRef<ActionType>();

	const menuColumns: ProColumns<ModuleTypes.ModuleType>[] = [
		{
			title: '菜单名称',
			dataIndex: 'name',
		},
		{
			title: '菜单路径',
			dataIndex: 'url',
			search:false
		},
		{
			title: '菜单图标',
			dataIndex: 'icon',
			search:false,
			render: (_, record) => (
				<>
					{record.icon && React.createElement(Icon[record.icon as string])}
				</>
			)
		},
		{
			title: '菜单类型',
			search:false,
			dataIndex: 'category',
			render: (_, record) => (
				<>
					{
						(() => {
							if (record.category === 1) {
								return <Tag color='green'>
									菜单
								</Tag>
							} else if (record.category === 2) {
								return <Tag color='geekblue'>
									视图
								</Tag>
							} else {
								return <Tag color='volcano'>
									功能
								</Tag>
							}
						})()
					}
				</>
			)
		},
		{
			title: '是否禁用',
			search:false,
			dataIndex: 'isDisabled',
			render: (_, record) => (
				<>
					<Switch disabled checked={record.isDisabled} checkedChildren="是" unCheckedChildren="否"></Switch>
				</>
			)
		},
		{
			title: '操作',
			valueType: 'option',
			key: 'option',
			render: (_, record) => [
				<a key="edit" onClick={() => {
					setCurrentMenu(record);
					menuForm.setFieldsValue(record);
					setIsModalVisible(true);
					setMenuTreeSelect(record.parentId);
				}}>编辑</a>,
				<Popconfirm
					key="sure"
					title="确定要删除此菜单吗？"
					onConfirm={() => onDeleteMenuItem(record)}
					okText="确定"
					cancelText="取消"
				>
					<a>删除</a>
				</Popconfirm>
			],
		}
	];

	/**
	 * 获取全部菜单树形结构
	 */
	const onGetMenuAllTree = async () => {
		const response = await moduleAPI.GetTreeGridModule(null);
		if (response.statusCode === 200) {
			setMenuTree(toTreeSelectData(response.data));
			tableRef.current?.reload();
		} else {
			message.error('获取菜单树失败');
		}
	}

	/**
	 * 将树形结构转化为 树形选择器
	 * @param menuTree 
	 * @returns 
	 */
	const toTreeSelectData = (menuTree: any) => {
		menuTree.forEach((item: any) => {
			item.title = item.name;
			item.value = item.id;
			if (item.children && item.children.length > 0) {
				toTreeSelectData(item.children);
			} else {
				delete item.children;
			}
		});
		return menuTree;
	}

	/**
	 * 新建菜单
	 */
	const onCreateMenu = () => {
		const empty: ModuleTypes.ModuleType = {
			category: 1,
			openType: 0,
			parentId: '',
			name: '',
			icon: '',
			url: '',
			sort: 0,
			isDisabled: false,
			id: '',
			children: []
		}
		setCurrentMenu(empty);
		menuForm.setFieldsValue(empty);
		setIsModalVisible(true);
	}

	/**
	 * 提交菜单表单信息
	 */
	const onFinishMenu = async (menuForm: ModuleTypes.ModuleType) => {
		if (menuForm.id === '') {//新增
			const response = await moduleAPI.SaveCreateModule(menuForm);
			if (response.statusCode === 200) {
				onGetMenuAllTree();
				setIsModalVisible(false);
				message.success('新增成功');
			} else {
				message.error(response.msg || '新增失败');
			}
		} else {//修改
			const response = await moduleAPI.SaveModifyModule(menuForm);
			if (response.statusCode === 200) {
				onGetMenuAllTree();
				setIsModalVisible(false);
				message.success('更新成功');
			} else {
				message.error(response.msg || '更新失败');
			}
		}
	}

	/**
	 * 删除菜单
	 * @param menuItem 
	 */
	const onDeleteMenuItem = async (menuItem: ModuleTypes.ModuleType) => {
		const response = await moduleAPI.DeleteModule(menuItem.id as string);
		if (response.statusCode === 200) {
			message.success('删除成功');
			onGetMenuAllTree();
		} else {
			message.error(response.msg || '删除失败');
		}
	}

	const onTreeChange = (value: string) => {
		setMenuTreeSelect(value);
	}


	useEffect(() => {
		onGetMenuAllTree();
	}, []);

	return (
		<div className={styles.container}>
			<ProTable<ModuleTypes.ModuleType>
				actionRef={tableRef}
				columns={menuColumns}
				cardBordered
				request={async (values) => {
					const params = JSON.parse(JSON.stringify(values));
					delete params.current;
					delete params.pageSize;
					
					const response:MyResponse.Content = await moduleAPI.GetTreeGridModule(params);
					const resData = response.data.filter((item: any) => {
						let isFind = false;
						if (Object.keys(params).length > 0) {
							Object.keys(params).forEach(objItem => {
								if (item[objItem].includes(params[objItem])) {
									isFind = true;
								}
							});
						} else {
							isFind = true
						}
						return isFind;
					});
					if (response.statusCode === 200) {
						return {
							data: resData,
							success: true,
						}
					} else {
						message.error(response.errors || '获取菜单列表失败');
						return {
							data: [],
							success: false,
						}
					}
				}}
				rowKey="id"
				search={{
					labelWidth: 'auto',
				}}
				options={{
					setting: {
						listsHeight: 400,
					},
				}}
				pagination={{
					current: currentPage,
					pageSize: 10,
					onChange: (page) => setCurrentPage(page),
				}}
				dateFormatter="string"
				headerTitle="菜单管理"
				toolBarRender={() => [
					<Button key="button" icon={<PlusOutlined />} type="primary" onClick={onCreateMenu}>
						新建
					</Button>
				]}
			/>
			<Modal footer={null} width={1000} title={currentMenu.id ? '编辑菜单' : '新建菜单'} open={isModalVisible} onCancel={() => setIsModalVisible(false)}>
				<Form
					form={menuForm}
					onFinish={onFinishMenu}
				>
					<Form.Item name="id" hidden={true}>
						<Input />
					</Form.Item>
					<Row gutter={20}>
						<Col span={12}>
							<Form.Item name="name" label="菜单名称" rules={[{ required: true, max: 255 }]}>
								<Input placeholder="请输入菜单名称" />
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item name="icon" label="菜单图标" >
								<Input placeholder="请输入菜单图标" />
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item name="url" label="菜单路径" rules={[{ required: true, max: 255 }]}>
								<Input placeholder="请输入菜单路径" />
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item name="parentId" label="上级菜单">
								<TreeSelect
									allowClear={true}
									style={{ width: '100%' }}
									dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
									treeData={menuTree}
									value={menuTreeSelect}
									placeholder="请选择上级菜单"
									onChange={onTreeChange}
								/>
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item name="category" label="菜单类型" rules={[{ required: true }]}>
								<Select>
									<Select.Option value={1}>菜单</Select.Option>
									<Select.Option value={2}>视图</Select.Option>
									<Select.Option value={3}>功能</Select.Option>
								</Select>
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item name="openType" label="打开方式" rules={[{ required: true }]}>
								<Select>
									<Select.Option value={0}>框架内嵌</Select.Option>
									<Select.Option value={1}>新开网页</Select.Option>
								</Select>
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item name="sort" label="菜单排序" rules={[{ required: true }]}>
								<Input placeholder="请输入菜单排序" />
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item name="isDisabled" label="是否禁用" valuePropName="checked" rules={[{ required: true }]}>
								<Switch checkedChildren="是" unCheckedChildren="否" />
							</Form.Item>
						</Col>
					</Row>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							确定
						</Button>
					</Form.Item>
				</Form>
			</Modal>
		</div>
	);
};

export default SystemManagement;
