import React, { useCallback, useState} 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 { TablePagination } from '@mui/material';
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import Checkbox from "@mui/material/Checkbox";
import { useEffect } from "react";
import { useImperativeHandle } from "react";
// import Spin from "./Spin";

import EnhancedTableHeadComponent from "./components/EnhancedTableHead"
import { getComparator, stableSort, useStyles } from "./utils";
import ActionsComponent from "./components/ActionsComponent";
import {ITableProps} from './interface'

export default function EnhancedTable(props: ITableProps) {
  const classes: any = useStyles;
  const [order, setOrder] = useState("asc");
  const [orderBy, setOrderBy] = useState("");
  const { headCells, rows, footer = true, elevation1, tableStyle, tableCellStyle, tableContainerStyle, stickyHeader, onRowClick, defaultRow, minHeight = '', borderBottom = '', onDoubleClick,
    load, size, checkboxData, rowsPerPage = 10, initSelected, page = 0, changePage = function () { }, toolbar, count, param, disabledParam = "id", headTableCellCheckbox, RowHeight = '', CellWidth = '', rowHover, TableNodataPadding = '', TableNodataLineHeight = '', tableBodySx, radioClick} = props;
  const [selected, setSelected] = useState(initSelected || []);
  const [rowsPerPageOptions] = useState(initSelected || [5, 10, 20, 50, { value: -1, label: 'All' }]);
  const [onRow, setOnRow] = useState('')

  // 重置复选框选中选项
  const initSelectedFunc = (e: any) => {
    setSelected(e)
  }

  useImperativeHandle(props.onRef, () => {
    return {
      initSelectedFunc: initSelectedFunc,
    };
  });

  useEffect(() => {
    setOnRow(defaultRow)
  }, [defaultRow])

  const onRowClickDefault = (value: any) => {
    setOnRow(value)
    onRowClick && onRowClick(value)
  }

  const handleRequestSort = (event: any, property: any) => {
    const isAsc = orderBy === property && order === "asc";
    setOrder(isAsc ? "desc" : "asc");
    setOrderBy(property);
  };

  const handleSelectAllClick = (event: any) => {
    if (event.target.checked) {
      const newSelecteds = rows.map((n: any) => n[param || 'id']);
      setSelected(newSelecteds);
      checkboxData(newSelecteds);
      return;
    }
    setSelected([]);
    checkboxData([]);
  };
  const handleClick = (event: any, name: any) => {
    const selectedIndex = selected.indexOf(name);
    let newSelected: any[] = [];

    if (selectedIndex === -1) {
      newSelected = newSelected.concat(selected, name);
    } else if (selectedIndex === 0) {
      newSelected = newSelected.concat(selected.slice(1));
    } else if (selectedIndex === selected.length - 1) {
      newSelected = newSelected.concat(selected.slice(0, -1));
    } else if (selectedIndex > 0) {
      newSelected = newSelected.concat(
        selected.slice(0, selectedIndex),
        selected.slice(selectedIndex + 1)
      );
    }
    checkboxData(newSelected)
    setSelected(newSelected);
  };

  const handleRadioClick = (id: string) => {
    setSelected(id)
  }

  const handleOnPageChange = (event: any, newPage: number) => {
    changePage(newPage, Number(rowsPerPage));
  };

  const handleChangeRowsPerPage = (event: any) => {
    changePage(0, parseInt(event.target.value, 10));
  };

  const isSelected = (name: any) => selected.indexOf(name) !== -1;

  // const emptyRows = rowsPerPage - Math.min(rowsPerPage, rows.length - page * rowsPerPage);

  const renderTableCellValue = useCallback(((item: any, row: any, index: number)=>{
    if(
      item.render
    ) {
      return <>{item.render(row[item.id], row, index)}</>
    } else if(row[item.id]) {
      return row[item.id] || '-'
    } else {
      return '-'
    }
  }),[])

  return (
    <div className={classes.root}>
      <Paper sx={{
        boxShadow: 'none'
      }} className={classes.paper} classes={{ elevation1: elevation1 || classes.elevation1 }} >
        {/* <Spin spin={spin} /> */}
        {toolbar && toolbar}
        <TableContainer style={{ ...tableContainerStyle }}>
          <Table stickyHeader={stickyHeader || false} className={classes.table} style={{ ...tableStyle }} aria-labelledby="tableTitle" size={size || "medium"} aria-label="cloudam table header" >
            <EnhancedTableHeadComponent
              classes={classes()}
              {...props}
              numSelected={selected.length}
              headTableCellCheckbox={headTableCellCheckbox}
              order={order}
              orderBy={orderBy}
              onSelectAllClick={handleSelectAllClick}
              onRequestSort={handleRequestSort}
              rowCount={rows.length}
              headCells={headCells || []}
            />
            <TableBody sx={{
              ...tableBodySx
            }}>
              {
                (rows.length === 0 && !load) && <TableRow>
                  <TableCell
                    sx={{
                      borderBottom: '1px solid #F0F2F5'
                    }}
                    colSpan={headCells?.filter((k: any) => k.id === "checkbox")?.length === 0 ? headCells?.length : headCells?.length + 1}
                    className={classes.TypographyStyle}
                    style={{ minHeight: minHeight, height: minHeight, borderBottom: borderBottom, padding: TableNodataPadding, lineHeight: TableNodataLineHeight }}
                  >
                    No Data
                  </TableCell>
                </TableRow>
              }
              {stableSort(rows, getComparator(order, orderBy)).slice(page * Number(rowsPerPage), page * Number(rowsPerPage) + Number(rowsPerPage)).map((row: any, index: number) => {
                const isItemSelected = isSelected(row[param || "id"]);
                const labelId = `enhanced-table-checkbox-${index}`;
                return (
                  <TableRow
                    hover={rowHover ? false : (row[disabledParam || "enabled"] ? true : false)}
                    onDoubleClick={() => {
                      onDoubleClick && onDoubleClick(row)
                    }}
                    style={{
                      height: RowHeight,
                      border: onRow === row[param || "id"] ? !row[disabledParam] ? "" : '1px solid #136EFA' : "",
                      backgroundColor: onRow === row[param || "id"] ? !row[disabledParam] ? "rgba(255, 255, 255, 0.4)" : "rgba(19, 110, 250, 0.1)" : "",
                      cursor: props.cursor ? (row[props.cursor] ? "pointer" : "auto") : (onRowClick ? !row[disabledParam] ? "no-drop" : "pointer" : "auto"),
                    }}
                    role="checkbox"
                    aria-checked={isItemSelected}
                    tabIndex={-1}
                    key={row[param || "id"] || index}
                    selected={isItemSelected}
                    onClick={() => {
                      radioClick && radioClick(row)
                      radioClick && handleRadioClick(row[param || "id"])
                    }}
                  >
                    {
                      headCells.filter((k: any) => k.id === "checkbox").length > 0 && <TableCell
                        sx={{
                          borderBottom: '1px solid #F0F2F5'
                        }}
                        onClick={(event) => {
                          // if (!row[disabledParam]) return;
                          onRowClick && onRowClickDefault(row[param || "id"])
                          headCells.filter((k: any) => k.id === "checkbox").length > 0 && handleClick(event, row[param || "id"])
                        }}
                        padding="checkbox">
                        <Checkbox sx={{ color: '#D1D6DE' }} color={"primary"} checked={isItemSelected} inputProps={{ "aria-labelledby": labelId }} />
                      </TableCell>
                    }
                    {
                      headCells.filter((item: any) => item.id !== 'checkbox').map((item: any, k: any) => {
                        return (
                          <TableCell key={k} component="th" id={labelId + k}
                            sx={{
                              borderBottom: '1px solid #F0F2F5'
                            }}
                            // align={}
                            style={{ width: CellWidth, textAlign: item.numeric ? "right" : "left", paddingRight: item.sort && item.numeric ? "40px" : "", border: tableCellStyle }}
                            scope="row"
                            padding={item.disablePadding ? "none" : "normal"}
                            classes={{
                              body: classes.bodyTableCell
                            }}
                          > {
                            renderTableCellValue(item, row, index)
                            }
                          </TableCell>
                        )
                      })
                    }
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </TableContainer>
        {
          footer ? <TablePagination
            rowsPerPageOptions={rowsPerPageOptions}
            component="div"
            count={count || rows.length}
            rowsPerPage={Number(rowsPerPage)}
            page={page}
            ActionsComponent={ActionsComponent}
            onPageChange={handleOnPageChange}
            onRowsPerPageChange={handleChangeRowsPerPage}
          /> : null
        }

      </Paper>
    </div>
  );
}
