import React, {useState} from 'react';
import {
	Card,
	Table,
	Typography,
	TableColumnProps,
	Button,
	Space,
	Message
} from '@arco-design/web-react';
import {useQuery} from 'react-query';
import Form from './form';
import {deleteMenu, getTreeMenu} from '@/api/menu';
import {getColumns, TableOptions} from './constants';
import {useHistory} from "react-router";

const {Title} = Typography;

function ConfigManage() {
	const reactQueryKey = useHistory().location.pathname;
	const [visible, setVisible] = useState(false);
	const [record, setRecord] = useState(null);

	const onDelete = async ({id}) => {
		await deleteMenu(id);
		Message.success('删除成功！');
		await refetch();
	};

	const tableCallback = async (type: TableOptions, record: any) => {
		switch (type) {
			case TableOptions.EDIT:
				showModal(record)
				break;
			case TableOptions.DELETE:
				await onDelete(record);
				break
		}
	}

	const columns: TableColumnProps[] = getColumns(tableCallback)

	const fetchData = async () => {
		const {data} = await getTreeMenu();
		return data
	};

	const {
		data,
		isLoading,
		isFetching,
		refetch
	} = useQuery(
		[reactQueryKey], fetchData);

	const showModal = (payload?) => {
		payload && setRecord(payload);
		setVisible(true);
	};

	const handleConfirm = async () => {
		setRecord(null);
		setVisible(false);
		await refetch();
	};

	const handleCancel = () => {
		setRecord(null);
		setVisible(false);
	};

	return (
		<>
			<Card>
				<Form
					handleConfirm={handleConfirm}
					handleCancel={handleCancel}
					visible={visible}
					record={record}
				/>
				<Title heading={6}>菜单管理</Title>

				<Space style={{marginBottom: 12}}>
					<Button type="primary" onClick={() => showModal()}>新建菜单</Button>
				</Space>

				<Table
					rowKey="id"
					loading={isLoading || isFetching}
					columns={columns}
					pagination={false}
					data={data}
				/>
			</Card>
		</>
	);
}


export default ConfigManage;
