import React, { useState, useEffect, useRef } from "react";
import TextField from '@material-ui/core/TextField';
import cx from "classnames"
import { makeStyles } from '@material-ui/core/styles';
import { Grid, List, ListItem, ListItemText, Chip } from "@material-ui/core";
import Checkbox from '@material-ui/core/Checkbox';
import ArrowDropDownIcon from '@material-ui/icons/ArrowDropDown';
const useStyles = makeStyles({
    MuiOutlinedInputInputLarge: { padding: "13.5px 15px" },
    MuiOutlinedInputInput: { padding: "12px 15px" },
    MuiOutlinedInputInputSmall: { padding: "10px 15px" },
    outlinedLarge: { transform: "translate(14px, 15.5px) scale(1)", fontSize: '14px', fontWeight: '400', color: '#707070' },
    outlined: { transform: "translate(14px, 14px) scale(1)", fontSize: '14px', fontWeight: '400', color: '#707070' },
    outlinedSmall: { transform: "translate(14px, 11px) scale(1)", fontSize: '14px', fontWeight: '400', color: '#707070' },
    notchedOutline: { borderColor: "rgba(216, 216, 216, 1)" },
    root: {
        width: "100%",
        "&:hover": {
            "& .MuiOutlinedInput-notchedOutline": { borderColor: "rgba(19, 110, 250, 0.9)" }
        },
    },
    error: {
        "& .MuiOutlinedInput-notchedOutline": {
            borderColor: "#D62C1F !important"
        },
    },
    disabled: {
        color: "#E3E3E3 !important",
        "& .MuiOutlinedInput-notchedOutline": { borderColor: "#E3E3E3 !important" },
        "&:hover": {
            "& .MuiOutlinedInput-notchedOutline": { borderColor: "#E3E3E3 !important" }
        },
    },

    errorLabel: { color: "#D62C1F !important" },
    errorFormHelperTextProps: { color: "#D62C1F !important", fontSize: "12px" },
    wrap: { width: "100%", position: "relative" },
    contentWrap: {
        padding: "8px 0", height: 0, transition: "all 1s", position: "absolute", zIndex: 9, width: "100%",
        backgroundColor: "#FFFFFF", boxShadow: "0px 2px 3px 0px rgba(0, 0, 0, 0.16)", borderRadius: "4px",
        overflowY: "overlay",
        maxHeight: "398px"
    },
    contentWrapOpenPosition:{top:"-400px"},
    contentWrapOpen: { height: "auto" },
    ArrowDropDownIconRoot: { transition: "all 0.2s", transform: "rotate(0)", position: "absolute", right: "15px", top: "6px" },
    ArrowDropDownIconRootOpen: { transform: "rotate(180deg)" },
    inputWrap: { position: "relative" },
    checked: { color: "#136EFA !important" }
})
let time = null;
export default props => {
    const classes = useStyles();
    const { label, type, variant, disabled, onChange, placeholder, autoFocus, defaultValue, error, fullWidth, margin, multiline, required, rows, startAdornment, endAdornment, helperText, size, option, callback, values = [], inputValue } = props;
    const [open, setOpen] = useState(false)
    const [curDomBottom, setCurDomBottom] = useState('')
    
    const onChangeDefault = (e) => {
        onChange && throttle(e.target.value)
    }

    const handleMouseUp = (event) => {
        setOpen(false)
        event && event.stopPropagation()
    }

    //节流
    const throttle = (e) => {
        if (!time) {
            time = setTimeout(() => {
                onChange(e)
                time = null
            }, 400);
        }
    }
    const inputEl = useRef(null);

    useEffect(() => {
        window.addEventListener('click', handleMouseUp, false)
        return () => window.removeEventListener('click', handleMouseUp, false)
    }, [])

    const resizeBys = (sty) => {
        switch (size) {
            case "large":
                return sty + "Large";
            case "small":
                return sty + "Small";
            default:
                return sty;
        }
    }

    // 获取当前 元素距离底部位置 
    const scrollFun = (sty) => {
        let dom = inputEl.current;
        const height = window.innerHeight  //可视区窗口高度
        const curDomHeight = dom.offsetHeight
        // const curDomHeight = dom.getBoundingClientRect().height
        const curDomY = dom.getBoundingClientRect().y
        const curDomBottom = height - curDomHeight - curDomY
        if( curDomBottom<400 ){
            setCurDomBottom("top")
        }else setCurDomBottom("")
    }

    const selectClick = (e, item) => {
        callback && callback(item)
    }

    return (
        <Grid ref={inputEl} className={cx({ [classes.wrap]: true, })} onClick={(e) => e.stopPropagation()}>
            <Grid className={cx({ [classes.inputWrap]: true, })}>
                <TextField
                    onFocus={() => {
                       scrollFun()
                        setOpen(true);
                    }}
                    label={label || ""}
                    style={{ width: "100%" }}
                    autoFocus={autoFocus || false}
                    defaultValue={defaultValue || ""}
                    type={type || "text"}
                    placeholder={placeholder || ""}
                    variant={variant || "outlined"}
                    disabled={disabled || false}
                    onChange={onChangeDefault}
                    error={error || false}
                    helperText={helperText || ""}
                    fullWidth={fullWidth || false}
                    rows={rows || 1}
                    multiline={multiline || false}
                    required={required || false}
                    InputProps={{
                        margin: margin || "none",
                        classes: {
                            root: classes.root,
                            input: classes[resizeBys("MuiOutlinedInputInput")],
                            notchedOutline: classes.notchedOutline,
                            error: classes.error,
                            disabled: classes.disabled
                        },
                        startAdornment: startAdornment || "",
                        endAdornment: endAdornment || "",
                    }}
                    InputLabelProps={{
                        classes: {
                            outlined: classes[resizeBys("outlined")],
                            error: classes.errorLabel
                        }
                    }}
                    FormHelperTextProps={{
                        classes: {
                            root: classes.rootFormHelperTextProps,
                            error: classes.errorFormHelperTextProps
                        }
                    }}
                />
                <ArrowDropDownIcon classes={{
                    root: cx({
                        [classes.ArrowDropDownIconRoot]: true,
                        [classes.ArrowDropDownIconRootOpen]: open
                    })
                }} />
            </Grid>
            {
                open && inputValue !== "" && (
                    <Grid onClick={(e) => e.stopPropagation()} className={cx({
                        [classes.contentWrap]: true,
                        [classes.contentWrapOpen]: open,
                        [classes.contentWrapOpenPosition]: curDomBottom==="top",
                    })
                    } id="select-wrap-content">
                        <Grid className={classes.gridScroll}>
                            <List component="nav" className={classes.root} aria-label="contacts">
                                {
                                    option && option.map((item, key) => {
                                        return (
                                            <ListItem
                                                selected={values.filter(k => k.value === item.value).length > 0}
                                                classes={{ root: classes.rootListItem }} key={key} button
                                                onClick={(event) => selectClick(event, item)}
                                            >
                                                <ListItemText primary={item.label} />
                                                <Checkbox
                                                    checked={values.filter(k => k.value === item.value).length > 0}
                                                    onChange={(event) => selectClick(event, item)}
                                                    classes={{
                                                        checked: classes.checked
                                                    }}
                                                />
                                            </ListItem>
                                        )
                                    })
                                }
                            </List>
                        </Grid>
                    </Grid>
                )
            }
        </Grid >
    )
}