import React from "react";

import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableContainer from "@material-ui/core/TableContainer";
import TablePagination from "@material-ui/core/TablePagination";
import TableRow from "@material-ui/core/TableRow";
import Paper from "@material-ui/core/Paper";
import Checkbox from "@material-ui/core/Checkbox";
import LinearProgress from '@material-ui/core/LinearProgress';
import Spin from "@/commons/components/Material.Ui/Spin";
import { CLOUDE } from '@/commons//utils/constants';
import EnhancedTableHeadComponent from "./Table/EnhancedTableHead"
import { getComparator, stableSort, useStyles } from "./Table/function";
import ActionsComponent from "./Table/ActionsComponent"
import { useEffect } from "react";

export default function EnhancedTable(props) {
    const classes = useStyles();
    const [order, setOrder] = React.useState("asc");
    const [orderBy, setOrderBy] = React.useState("");
    const { headCells, rows, size, checkboxData, rowsPerPage = 10, initSelected, page = 0, changePage = function () { }, toolbar, count, minHeight='',
        load = false, param, expandable, isShowFunction, renderExpandPanel, clickRow, nopadding, headTableCellCheckbox, headTableCell, boder, subBody, renderCheckbox ,
        noDatapadding='' ,RowHeight='',RowHover=true ,minWidth ='',RowStyle={},
    } = props;
    const [selected, setSelected] = React.useState(initSelected || []);
    // const [rowsPerPageOptions, setRowsPerPageOptions] = React.useState(initSelected || [5, 10, 20, 50, { value: -1, label: 'All' }]);
    const [rowsPerPageOptions, setRowsPerPageOptions] = React.useState(initSelected || [5, 10, 20, 50]);
    const [progress, setProgress] = React.useState(0);
    const progressRef = React.useRef(() => { });
    const [spin, setSpin] = React.useState(false)
    const [expanded, setExpanded] = React.useState([])

    useEffect(() => {
        setSelected([])
    }, [rows])

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

    const handleSelectAllClick = (event) => {
        if (event.target.checked) {
            let newSelecteds = []
            if (renderCheckbox) {
                let list = rows.map((n) => renderCheckbox(n) ? "" : n[param || "id"]);
                list.map(item => {
                    if (item) {
                        newSelecteds.push(item)
                    }
                })
            } else {
                newSelecteds = rows.map((n) => n[param || "id"]);
            }
            setSelected(newSelecteds);
            checkboxData && checkboxData(newSelecteds);
            return;
        }
        setSelected([]);
        checkboxData && checkboxData([]);
    };

    const handleClick = (event, name) => {

        // // 阻止合成事件的冒泡
        // event.stopPropagation();
        // // 阻止与原生事件的冒泡
        // event.nativeEvent.stopImmediatePropagation();

        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 && checkboxData(newSelected)
        setSelected(newSelected);
    };

    const handleOnPageChange = (event, newPage) => {
        changePage(newPage, rowsPerPage);
        setSelected([]);
        checkboxData && checkboxData([]);
    };

    const filterCheckbox = (data) => {
        if (renderCheckbox) {
            return renderCheckbox(data)
        } else {
            return false
        }
    }

    /*
    *@分割线=======================================================================================================================================
    *@Description: 线性 进度条
    *@File: 
    *@param: {} [] 
    *@MethodAuthor:  dawei.liu
    *@Date: 2021-07-27 16:12:57
    */
    // React.useEffect(() => {
    //     progressRef.current = () => {
    //         let diff = 0;
    //         if (progress > 90) {
    //             diff = 0;
    //         } else {
    //             if (progress >= 100)
    //                 diff = 0
    //             else
    //                 diff = (100 - progress) / 10
    //         }
    //         setProgress(progress + diff);
    //     };
    // });

    React.useEffect(() => {
        /*
         *@分割线=======================================================================================================================================
         *@Description: 线性 进度条
         *@File: 
         *@param: {} [] 
         *@MethodAuthor:  dawei.liu
         *@Date: 2021-07-27 16:12:57
        */
        // const timer = setInterval(() => {
        //     progressRef.current();
        // }, 500);
        // if (!load) {
        //     timer && clearInterval(timer);
        //     setProgress(100);
        // } else {
        //     setProgress(0)
        // }
        // return () => {
        //     clearInterval(timer);
        // };
        setSpin(load)
    }, [load]);

    const handleChangeRowsPerPage = (event) => {
        setSelected([]);
        checkboxData && checkboxData([]);
        changePage(0, parseInt(event.target.value, 10));
    };

    const handleExpand = (event, id, isShowFunctions) => {
        let tempExpand = expanded;
        if (expanded.includes(id)) {
            tempExpand = tempExpand.filter(item => item !== id);
        } else {
            tempExpand.push(id);
        }
        isShowFunctions && isShowFunctions(tempExpand)
        setExpanded(JSON.parse(JSON.stringify(tempExpand)))
    };
    const isSelected = (name) => selected.indexOf(name) !== -1;

    const noDateRender = (rows) => {
        if (rows.length > 0 || load) return <TableRow></TableRow>
        return <TableRow>
            <TableCell
                colSpan={headCells.filter(k => k.id === "checkbox").length === 0 ? headCells.length : headCells.length + 1}
                className={boder ? classes.TypographyboderStyle : classes.TypographyStyle}
                style={{minHeight: minHeight, height: minHeight , padding:noDatapadding}}
            >
                No Data
            </TableCell>
        </TableRow >
    }

    return (
        <div className={classes.root}>
            <Paper className={classes.paper} classes={nopadding ? { elevation1: classes.elevationNoPadding } : { elevation1: classes.elevation1 }} >
                {/*
                 *@分割线=======================================================================================================================================
                 *@Description: 线性加载进度
                 *@param: {} [] 
                 *@MethodAuthor:  dawei.liu
                 *@Date: 2021-07-27 16:17:12
                */}
                {/* {
                load && <LinearProgress variant="determinate" value={progress} classes={{ root: classes.LinearProgressStyle }} />
            } */}
                <Spin spin={spin} />
                {toolbar && toolbar}
                <TableContainer classes={{ root: boder ? classes.rootTableboderContainer : classes.rootTableContainer }}>
                    <Table className={classes.table} style={{minWidth:minWidth}}  aria-labelledby="tableTitle" size={size || "medium"} aria-label="cloudam table header" >
                        <EnhancedTableHeadComponent
                            classes={classes}
                            headTableCell={headTableCell}
                            numSelected={selected.length}
                            order={order}
                            orderBy={orderBy}
                            headTableCellCheckbox={headTableCellCheckbox}
                            onSelectAllClick={handleSelectAllClick}
                            onRequestSort={handleRequestSort}
                            rowCount={rows.length}
                            headCells={headCells || []}
                            RowStyle={RowStyle || {}}
                        />

                        <TableBody>
                            {noDateRender(rows)}
                            {stableSort(rows, getComparator(order, orderBy)).map((row, index) => {
                                const isItemSelected = isSelected(row[param || "id"]);
                                const labelId = `enhanced-table-checkbox-${index}`;
                                const columns = headCells.length + (headCells.filter(k => k.id === "checkbox").length === 0 ? 0 : 1) + (expandable ? 1 : 0);
                                return (
                                    <React.Fragment key={index}>
                                        <TableRow style={{height:RowHeight,...RowStyle}} hover={RowHover} onClick={(event) => {
                                            if (expandable) {
                                                handleExpand(event, row[param || 'id'], isShowFunction);
                                                event.stopPropagation();
                                            } else if (clickRow && headCells.filter(k => k.id === "checkbox").length > 0) {
                                                if (!filterCheckbox(row)) handleClick(event, row[param || "id"])
                                            }
                                        }} role="checkbox" aria-checked={isItemSelected}
                                            tabIndex={-1} selected={isItemSelected}
                                        >
                                            {
                                                headCells.filter(k => k.id === "checkbox").length > 0 && <TableCell classes={{ root: classes.bodyTableCellRoot }} padding="checkbox">
                                                    <Checkbox color={"primary"} checked={isItemSelected} inputProps={{ "aria-labelledby": labelId }} disabled={filterCheckbox(row)} />
                                                </TableCell>
                                            }
                                            {
                                                headCells.map((item, k) => {
                                                    return (
                                                        <TableCell
                                                            onClick={(event) => {
                                                                if (expandable) {
                                                                    handleExpand(event, row.id, isShowFunction);
                                                                    event.stopPropagation();
                                                                }
                                                            }}
                                                            key={k} component="th" id={labelId + k}
                                                            style={{ width:item.width || '',maxWidth:item.width || '',textAlign: item.numeric ? "right" : "left", paddingRight: item.sort && item.numeric ? "40px" : "", boxSizing: "border-box", display: item.id !== "checkbox" ? "" : "none" }}
                                                            scope="row"
                                                            padding={item.disablePadding ? "none" : "normal"}
                                                            classes={{ body: props.bodyTableCell || classes.bodyTableCell }}
                                                        > {row[item.id]} </TableCell>
                                                    )
                                                })
                                            }
                                        </TableRow>
                                        {
                                            expandable && expanded.includes(row[param || 'id']) && <TableRow tabIndex={-1}>
                                                <TableCell colSpan={columns} style={{ padding: 0, borderBottom: 'none' }} >
                                                    {renderExpandPanel(row[param || 'id'])}
                                                </TableCell>
                                            </TableRow>
                                        }
                                    </React.Fragment>
                                );
                            })}
                        </TableBody>
                    </Table>
                </TableContainer>
                {
                    <div style={{
                        display: "flex", justifyContent: subBody ? "space-between" : "flex-end", alignItems: "center"
                    }}>
                        {
                            subBody ? subBody : ""
                        }
                        <TablePagination
                            rowsPerPageOptions={rowsPerPageOptions}
                            component="div"
                            count={count || rows.length}
                            rowsPerPage={rowsPerPage || 10}
                            page={page}
                            ActionsComponent={ActionsComponent}
                            onChangePage={handleOnPageChange}
                            labelRowsPerPage={CLOUDE.linePage}
                            onChangeRowsPerPage={handleChangeRowsPerPage}
                        />
                    </div>
                }

            </Paper>
        </div>
    );
}
