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, Typography } from "@material-ui/core";
import Checkbox from '@material-ui/core/Checkbox';
import ArrowDropDownIcon from '@material-ui/icons/ArrowDropDown';
import Tooltip from '@material-ui/core/Tooltip';
const COIN_IAMGE_TIPS = require("../../../console/cloudelastic/assets/img/templates/icon_about_grey.png");

const useStyles = makeStyles({
    MuiOutlinedInputInputLarge: { padding: "13.5px 15px" },
    MuiOutlinedInputInput: { padding: "12px 15px", "&::placeholder": { fontSize: "14px" } },
    MuiOutlinedInputInputSmall: { padding: "10px 15px", "&::placeholder": { fontSize: "13px" } },
    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%",
        fontSize: "14px",
        "&: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", transition: "all 1s", position: "fixed", zIndex: 9, width: "552px",
        backgroundColor: "#FFFFFF", boxShadow: "0px 2px 3px 0px rgba(0, 0, 0, 0.16)", borderRadius: "4px",
        overflowY: "overlay",
        maxHeight: "398px",
        // position: "fixed",
        // width: "552px"
    },
    contentWrapOpenPosition: { top: "-400px" },
    contentWrapOpen: { height: "auto", padding: "0px" },
    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" },
    ListItemTextStyle: {
        fontSize: "14px"
    },
    ListItemRoot: { flex: "inherit" },
    rootListItem: { paddingTop: "0px", paddingBottom: "0px" },
    rootListItemDisable: { paddingTop: "0px", paddingBottom: "0px", opacity: "0.4" }
})
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 || ""}
                    value={inputValue || ""}
                    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}
                    autoComplete="off"
                    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 || "",
                        autoComplete: "off"
                    }}
                    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 && (
                    <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: item.disable ? classes.rootListItemDisable : classes.rootListItem }} key={key} button
                                                onClick={(event) => !item.disable && selectClick(event, item)}
                                            >
                                                <Checkbox
                                                    checked={values.filter(k => k.value === item.value).length > 0}
                                                    size={'small'}
                                                    classes={{
                                                        checked: classes.checked
                                                    }}
                                                />
                                                <ListItemText primary={item.label} classes={{ root: classes.ListItemRoot, primary: classes.ListItemTextStyle }} />
                                                {
                                                    item.tooltip && <Tooltip
                                                        arrow
                                                        placement={'top'}
                                                        classes={{
                                                            tooltip: classes.popper2,
                                                        }}
                                                        title={item.tooltip} >
                                                        <img src={COIN_IAMGE_TIPS} style={{ width: "16px", marginLeft: "8px" }} alt="" />
                                                    </Tooltip>
                                                }

                                            </ListItem>
                                        )
                                    })
                                }
                            </List>
                        </Grid>
                    </Grid>
                )
            }
        </Grid >
    )
}