import React, {useEffect, useState} from 'react';
import {
	Button,
	Card,
	Message,
	PaginationProps,
	Table,
	TableColumnProps,
	Typography
} from '@arco-design/web-react';
import {useHistory} from "react-router";
import {useQuery} from 'react-query';
import Form from './form';
import {IconPlus} from '@arco-design/web-react/icon';
import {getColumns, TableOptions} from './constants';
import {getRole,deleteRole} from "@/api/role";
import GrantRolesForm from "./grantPerm";
import SearchForm from "./searchForm";


const {Title} = Typography;

function UserManage() {
	const reactQueryKey = useHistory().location.pathname

	const [visible, setVisible] = useState(false);
	const [visibleAssignRoles, setVisibleAssignRoles] = useState(false);
	const [record, setRecord] = useState(null);
	const [pagination, setPagination] = useState<PaginationProps>({
		sizeCanChange: true,
		showTotal: true,
		pageSize: 10,
		current: 1,
		pageSizeChangeResetCurrent: true,
		total: 0
	});

	const [searchQuery, setSearchQuery] = useState<Record<string, any>>({
		page: pagination.current,
		pageSize: pagination.pageSize,
	});

	const showAssignRolesModal = (payload) => {
		setRecord(payload);
		setVisibleAssignRoles(true);
	};

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

	const onDelete = async ({id}) => {
		await deleteRole(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
			case TableOptions.ASSIGN_PERMISSION:
				showAssignRolesModal(record);
				break
		}
	}

	const columns: TableColumnProps[] = getColumns(tableCallback)

	const handleSearch = async (params) => {
		setSearchQuery(prev => ({...prev, page: 1, ...params}))
	}

	const onChangeTable = async ({current, pageSize}) => {
		setSearchQuery(prev => ({...prev, page: current, pageSize}));
	};

	const fetchData = async ({queryKey}) => {
		const [, params] = queryKey;
		const {data} = await getRole(params);
		setPagination(prev => ({
			...prev,
			total: data.count
		}))
		// 当前列表不存在数据回退1页
		if (params.page > 1 && data.list.length === 0) {
			setSearchQuery({
				...searchQuery,
				page: params.page - 1
			});
		}
		return data;
	};

	const {data, isLoading, isFetching, refetch} = useQuery(
		[reactQueryKey, {
			page: pagination.current,
			pageSize: pagination.pageSize,
			...searchQuery
		}],
		fetchData);

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

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

	useEffect(() => {
		setPagination(prev => ({
			...prev,
			current: searchQuery.page,
			pageSize: pagination.pageSize,
		}))
	}, [searchQuery])

	return (
		<>
			<Card>
				<Form
					handleConfirm={handleConfirm}
					handleCancel={handleCancel}
					visible={visible}
					record={record}
				/>
				<GrantRolesForm
				  handleConfirm={handleConfirm}
				  handleCancel={handleCancel}
				  visible={visibleAssignRoles}
				  record={record}
				/>
				<Title heading={6}>角色管理</Title>

				<SearchForm onSearch={handleSearch}/>

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

				<Table
					rowKey="id"
					loading={isLoading || isFetching}
					columns={columns}
					onChange={onChangeTable}
					pagination={pagination}
					data={data?.list}
				/>
			</Card>
		</>
	);
}


export default UserManage;
