import { useCallback, useMemo } from "react";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import Checkbox from "@mui/material/Checkbox";
import MyPagination from "@/components/mui/MyPagination";
import ascIcon from "@/assets/project/ascIcon.svg";
import descIcon from "@/assets/project/descIcon.svg";
import sortIcon from "@/assets/project/sort.svg";
import { createTheme, ThemeProvider } from "@mui/material";

type Order = "asc" | "desc"; // 升序为asc，降序为desc。

export type sortState = {
	field: string | null | undefined | ""; // 根据哪个属性来排序
	order: Order | null | undefined | "";
};

interface IMyTableProps {
	rows: Array<any>; // 表格数据
	headCells: Array<any>; // 表头配置
	key?: string; // 表格数据的key
	hasCheckbox?: boolean; // 是否有复选框
	selectItems?: Array<any>; // 选中的项
	setSelectItems?: any; // 设置选中的项
	fixedHead?: boolean; // 是否是固定表头
	noDataText?: string; // 无数据提示文案
	hasTableFooter?: boolean; // 是否有分页组件
	page?: number; // 当前页
	pageChange?: any; // 页码改变
	count?: number; // 总页数
	randerTooterContent?: any; // 分页左侧内容渲染
	sortState?: sortState; // 排序状态
	setSortState?: any; // 设置排序状态
}

const MyTable = (props: IMyTableProps) => {
	// tode    loading    nodata
	const {
		rows,
		headCells,
		key = "id",
		hasCheckbox = false,
		selectItems = [],
		setSelectItems,
		fixedHead,
		hasTableFooter = false,
		page = 0,
		pageChange = () => {},
		count = 1,
		randerTooterContent = null,
		sortState,
		setSortState,
	} = props;

	const theme = useMemo(() => {
		return createTheme({
			components: {
				MuiTableHead: {
					styleOverrides: {
						root: {
							background: "rgba(247, 248, 250, 1)",
							"& .MuiTableRow-head": {
								borderRadius: "4px 4px 0 0",
								borderBottom: "1px solid rgba(240, 242, 245, 1)",
							},
						},
					},
				},
				MuiTableRow: {
					styleOverrides: {
						root: {
							":hover": {
								background: "rgba(245, 246, 247, 1)",
							},
							"& .MuiTableCell-root": {
								"&.MuiTableCell-head": {
									fontSize: "12px",
									lineHeight: "20px",
									color: "rgba(138, 144, 153, 1)",
									padding: "12px 16px",
								},
								"&.MuiTableCell-head:nth-of-type(1)": {
									paddingRight: hasCheckbox ? "8px" : "16px",
								},
							},
							"&.MuiTableRow-footer": {
								// 分页的那一行不要hover效果
								":hover": {
									background: "#fff",
								},
							},
						},
					},
				},
				MuiPaper: {
					styleOverrides: {
						root: {
							"&.MuiTableContainer-root": {
								boxShadow: "none",
							},
						},
					},
				},
				MuiTableCell: {
					styleOverrides: {
						root: {
							fontSize: "14px",
							lineHeight: "22px",
							color: "rgba(86, 92, 102, 1)",
							padding: "16px",
							borderBottom: "1px solid rgba(240, 242, 245, 1)",
						},
					},
				},
				MuiTableBody: {
					styleOverrides: {
						root: {
							"& .MuiTableRow-root:nth-last-of-type(1) .MuiTableCell-root": {
								borderBottom: "none",
							},
						},
					},
				},

				// 复选框样式
				MuiSvgIcon: {
					styleOverrides: {
						root: {
							color: "rgba(209, 214, 222, 1)",
							fontSize: "18px",
						},
					},
				},
				MuiCheckbox: {
					styleOverrides: {
						root: {
							"&.Mui-checked .MuiSvgIcon-root": {
								color: "rgba(19, 110, 250, 1)",
							},
						},
					},
				},
				MuiButtonBase: {
					styleOverrides: {
						root: {
							"&.MuiCheckbox-root": {
								padding: 0,
							},
						},
					},
				},
			},
		});
	}, [hasCheckbox]);

	const onSelectAllClick = useCallback(() => {
		return (e: any) => {
			if (e.target.checked) {
				setSelectItems && setSelectItems(rows.map((row) => row[key]));
			} else {
				setSelectItems && setSelectItems([]);
			}
		};
	}, [setSelectItems, key, rows]);

	const onSelectRowClick = useCallback(
		(e: any, itemValue: string) => {
			if (e.target.checked) {
				setSelectItems && setSelectItems([...selectItems, itemValue]);
			} else {
				const selectItemIndex = selectItems.indexOf(itemValue);
				const newSelectItems = [
					...selectItems.slice(0, selectItemIndex),
					...selectItems.slice(selectItemIndex + 1, selectItems.length),
				];
				setSelectItems && setSelectItems(newSelectItems);
			}
		},
		[selectItems, setSelectItems]
	);

	const handleSort = useCallback(
		(field: string) => {
			if (sortState?.field === field) {
				if (sortState?.order === "asc") {
					setSortState({
						field,
						order: "desc",
					});
				} else if (sortState?.order === "desc") {
					setSortState({
						field,
						order: "asc",
					});
				} else {
					setSortState({
						field,
						order: "desc",
					});
				}
			} else {
				setSortState({
					field,
					order: "desc",
				});
			}
		},
		[sortState, setSortState]
	);

	const randerTableHead = useMemo(() => {
		return (
			<TableHead>
				<TableRow>
					{hasCheckbox && (
						<TableCell align="left" sx={{ width: "18px", paddingRight: "8px" }}>
							<Checkbox
								indeterminate={
									selectItems.length > 0 && selectItems.length < rows.length
								}
								checked={rows.length > 0 && selectItems.length === rows.length}
								onChange={onSelectAllClick}
							/>
						</TableCell>
					)}
					{headCells.map((headCell, index) => (
						<TableCell key={index} align="left" width={headCell.width}>
							{headCell.sort && (
								<>
									<span>{headCell.label}</span>
									<img
										src={
											sortState?.field === headCell.id
												? sortState?.order === "asc"
													? ascIcon
													: sortState?.order === "desc"
													? descIcon
													: sortIcon
												: sortIcon
										}
										alt=""
										onClick={() => handleSort(headCell.id)}
										style={{
											marginLeft: "8px",
											cursor: "pointer",
											position: "relative",
											top: "3px",
										}}
									/>
								</>
							)}
							{!headCell.sort && headCell.label}
						</TableCell>
					))}
				</TableRow>
			</TableHead>
		);
	}, [
		hasCheckbox,
		headCells,
		selectItems,
		onSelectAllClick,
		rows.length,
		handleSort,
		sortState,
	]);

	const randerTableBody = useMemo(() => {
		return (
			<TableBody>
				{rows.map((row) => (
					<TableRow key={row[key]}>
						{hasCheckbox && (
							<TableCell
								align="left"
								sx={{ width: "18px", paddingRight: "8px" }}
							>
								<Checkbox
									checked={
										selectItems.filter((selectItem) => selectItem === row[key])
											.length > 0
									}
									onChange={(e) => onSelectRowClick(e, row[key])}
								/>
							</TableCell>
						)}
						{headCells.map((headCell, index) => (
							<TableCell key={index} align="left" width={headCell.width}>
								{row[headCell.id]}
							</TableCell>
						))}
					</TableRow>
				))}
			</TableBody>
		);
	}, [rows, key, hasCheckbox, selectItems, onSelectRowClick, headCells]);

	const randerTableFooter = useMemo(() => {
		if (hasTableFooter) {
			return (
				<div
					style={{
						padding: "20px 0",
						display: "flex",
						justifyContent: "space-between",
						alignItems: "center",
						borderTop: "1px solid rgba(240, 242, 245, 1)",
					}}
				>
					<div>{randerTooterContent}</div>
					<MyPagination page={page} pageChange={pageChange} count={count} />
				</div>
			);
		} else {
			return null;
		}
	}, [hasTableFooter, page, count, pageChange, randerTooterContent]);

	return (
		<ThemeProvider theme={theme}>
			{!fixedHead && (
				<>
					<TableContainer component={Paper}>
						<Table>
							{randerTableHead}
							{randerTableBody}
						</Table>
					</TableContainer>
					{randerTableFooter}
				</>
			)}
			{fixedHead && (
				<div
					style={{ height: "100%", display: "flex", flexDirection: "column" }}
				>
					<TableContainer component={Paper}>
						<Table>{randerTableHead}</Table>
					</TableContainer>
					<TableContainer component={Paper} sx={{ flex: 1 }}>
						<Table>{randerTableBody}</Table>
					</TableContainer>
					{randerTableFooter}
				</div>
			)}
		</ThemeProvider>
	);
};

export default MyTable;
