import React, { useRef, useState } from "react"

import './global.less';
import { Button, Space, Tag, Tooltip, Typography } from "antd";
import { HOUR_LIST, Props, formatData, getInitalFormatList, initTimerPicker } from "./const";
const INIT_START_POINT = { rowNum: -1, colNum: -1, deselect: false };
const INIT_END_POINT = { rowNum: -1, colNum: -1 };
function getRealStartEndPoint(startPoint: { colNum: number, rowNum: number }, endPoint: { colNum: number, rowNum: number }) {
    let startRowNum = startPoint.rowNum,
        startColNum = startPoint.colNum,
        endRowNum = endPoint.rowNum,
        endColNum = endPoint.colNum;
    if (startPoint.colNum > endPoint.colNum) {
        startColNum = endPoint.colNum;
        endColNum = startPoint.colNum;
    }
    if (startPoint.rowNum > endPoint.rowNum) {
        startRowNum = endPoint.rowNum;
        endRowNum = startPoint.rowNum;
    }
    return {
        startRowNum,
        startColNum,
        endRowNum,
        endColNum,
    };
}
const getActiveStatus = (data: { each: any, startPoint: any, endPoint: any }) => {
    const { each, startPoint, endPoint } = data;
    if (startPoint.rowNum === -1 || endPoint.rowNum === -1) {
        return each.selected;
    }
    const { startRowNum, startColNum, endRowNum, endColNum } = getRealStartEndPoint(startPoint, endPoint);
    if (each.rowNum >= startRowNum && each.colNum >= startColNum && each.rowNum <= endRowNum && each.colNum <= endColNum) {
        return !startPoint.deselect;
    }
    return each.selected;
};

const Thead: React.FC<Props> = ({ value, onChange }) => {
    // console.log('33333', value)
    const [timerPickered, setTimerPickered] = useState(initTimerPicker(value ? value.split('') : []));
    const [startPoint, setStartPoint] = useState({ ...INIT_START_POINT });
    const [endPoint, setEndPoint] = useState({ ...INIT_END_POINT });
    const endPointRef = useRef(endPoint);

    // console.log('timerPickered--->', timerPickered)

    const updateEndPoint = (point: any) => {
        endPointRef.current = { ...point };
        setEndPoint(endPointRef.current);
    };

    const handleClear = () => {
        const initData = getInitalFormatList();
        setTimerPickered(initTimerPicker(initData));
        setStartPoint({ ...INIT_START_POINT });
        setEndPoint({ ...INIT_END_POINT });
        onChange?.();
    };

    const updateDataList = ({ startPoint, endPoint }: any) => {
        const dataList = getInitalFormatList();
        timerPickered.forEach((rows) => {
            rows.forEach((each: any) => {
                each.selected = getActiveStatus({
                    each,
                    startPoint,
                    endPoint,
                });
                formatData(dataList, each);
            });
        });
        setTimerPickered([...timerPickered]);
        setStartPoint({ ...INIT_START_POINT });
        updateEndPoint({ ...INIT_END_POINT });
        return dataList;
    };

    const triggerChange = () => {
        const data = updateDataList({ startPoint, endPoint });
        onChange?.(data.join(''));
    };

    const onMouseDown = ({ target: { dataset } }: any) => {
        const { type, rowNum, colNum, selected } = dataset;
        if ('time-boxzone' !== type) return;
        setStartPoint({
            rowNum: +rowNum,
            colNum: +colNum,
            deselect: selected === '1',
        });
        updateEndPoint({ rowNum: +rowNum, colNum: +colNum });
    };

    const onMouseUp = ({ target: { dataset } }: any) => {
        const { type, rowNum, colNum } = dataset;
        if (type !== 'time-boxzone') return;
        if (+rowNum !== endPointRef.current.rowNum || +colNum !== endPointRef.current.colNum) {
            updateEndPoint({ rowNum: +rowNum, colNum: +colNum });
        }
        requestAnimationFrame(() => {
            triggerChange();
        });
    };

    const onMouseOver = ({ target: { dataset } }: any) => {
        const { type, rowNum, colNum } = dataset;
        if ('time-boxzone' !== type) return;
        if (startPoint.colNum === -1) return;
        endPointRef.current = { rowNum: +rowNum, colNum: +colNum };
        requestAnimationFrame(() => {
            updateEndPoint(endPointRef.current);
        });
    };

    const onMouseLeave = () => {
        if (startPoint.rowNum === -1) return;
        // setTimeout(() => {
        if (endPointRef.current.colNum === -1) {
            updateEndPoint({
                colNum: startPoint.colNum,
                rowNum: startPoint.rowNum,
            });
        }
        requestAnimationFrame(() => {
            triggerChange();
        });
        // });
    };

    const Footer = (
        <div className="footer_wrapper">
            <Space>
                <Tag color="#1DA57A">已选</Tag>
                <Tag>未选</Tag>
                <Typography.Text type="secondary">可拖动鼠标选择时间段</Typography.Text>
            </Space>
            <Button type="link" onClick={handleClear} style={{ paddingLeft: 0, paddingRight: 0 }}>
                清空
            </Button>
        </div>
    );

    return <div className="thead_wrapper">
        <div className="thead_wrapper_content">
            <div className="week_series" draggable={false}>
                {HOUR_LIST.map(hour => (
                    <div className="week_series__item" key={hour}>
                        {hour}点
                    </div>
                ))}
            </div>
            <div
                className="time_series"
                data-type="right-boxzones"
                onMouseDown={onMouseDown}
                onMouseUp={onMouseUp}
                onMouseOver={onMouseOver}
                onMouseLeave={onMouseLeave}
            >
                {timerPickered.map((row, index) => (
                    <div className="time_series__row" key={index}>
                        {row.map((each: any, i: number) => (
                            <Tooltip
                                destroyTooltipOnHide
                                mouseEnterDelay={1}
                                key={`${index}_${i}`}
                                title={each?.name}
                                placement="bottom"
                            >
                                <div
                                    key={each?.key}
                                    draggable={false}
                                    data-row-num={each?.rowNum}
                                    data-col-num={each?.colNum}
                                    data-selected={each?.selected ? '1' : '0'}
                                    data-type="time-boxzone"
                                    className={`row_item ${getActiveStatus({
                                        each,
                                        startPoint,
                                        endPoint: endPointRef.current
                                    }) ? 'isActive' : ''}`}
                                />
                            </Tooltip>
                        ))}
                    </div>
                ))}
            </div>
        </div>
        {Footer}
    </div>
}


export default React.memo(Thead)