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

import EnhancedTableHeadComponent from "./Table/EnhancedTableHead"
import { getComparator, stableSort, useStyles } from "./Table/function";
import ActionsComponent from "./Table/ActionsComponent"
import { useEffect } from "react";
import { useImperativeHandle } from "react";

export default function EnhancedTable(props) {
  const classes = useStyles;
  const [order, setOrder] = React.useState("asc");
  const [orderBy, setOrderBy] = React.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 = '', tableBoySx, radioClick} = props;
  const [selected, setSelected] = React.useState(initSelected || []);
  const [rowsPerPageOptions] = React.useState(initSelected || [5, 10, 20, 50, { value: -1, label: 'All' }]);
  const [onRow, setOnRow] = React.useState('')

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

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

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

  const onRowClickDefault = (value) => {
    setOnRow(value)
    onRowClick(value)
  }

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

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

    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) => {
    setSelected(id)
  }

  const handleOnPageChange = (event, newPage) => {
    changePage(newPage, rowsPerPage);
  };

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

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

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

  const renderTableCellValue = useCallback(((item, row, index)=>{
    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={{
              ...tableBoySx
            }}>
              {
                (rows.length === 0 && !load) && <TableRow>
                  <TableCell
                    sx={{
                      borderBottom: '1px solid #F0F2F5'
                    }}
                    colSpan={headCells?.filter(k => 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 * rowsPerPage, page * rowsPerPage + rowsPerPage).map((row, index) => {
                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 => 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 => 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 => item.id !== 'checkbox').map((item, k) => {
                        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: props.bodyTableCell || classes.bodyTableCell
                            }}
                          > {
                            renderTableCellValue(item, row, index)
                            }
                          </TableCell>
                        )
                      })
                    }
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </TableContainer>
        {
          footer && <TablePagination
            rowsPerPageOptions={rowsPerPageOptions}
            component="div"
            count={count || rows.length}
            rowsPerPage={rowsPerPage}
            page={page}
            ActionsComponent={ActionsComponent}
            onChangePage={handleOnPageChange}
            onChangeRowsPerPage={handleChangeRowsPerPage}
          />
        }

      </Paper>
    </div>
  );
}
