import React, { PureComponent } from "react";
import ReactDOM from "react-dom";
import { DatePicker } from "antd";
import { DatePickerProps } from 'antd/lib/date-picker/interface'
import moment, { months } from "moment";
import * as Tools from 'jad-tool'


export default class DispersedDatePicker extends PureComponent<DatePickerProps & {
    initValue?: moment.Moment[] | string[],
    onChange?: (date: moment.Moment[] | null, dateString: string[]) => void;
    disabledDate?: (date: moment.Moment[] | null) => void;
}> {
    constructor(props) {
        super(props);
        const { initValue } = this.props
        if (initValue && initValue.length > 0) {
            initValue.forEach(e => this.selectedDateSet.add(Tools.isString(e) ? e : e.format("YYYY-MM-DD")))
            const formatArr = this.sortDateFormat(Array.from(this.selectedDateSet));
            if (formatArr.length > 0) {
                this.state.formatStr = formatArr.join()
            }
        }
    }


    selectedDateSet = new Set();
    state = {
        formatStr: null,
        open: false,
    };


    // componentDidMount(){
    //     const { initValue } = this.props
    //     if( initValue && initValue.length > 0 ){
    //         initValue.forEach( e=>this.selectedDateSet.add(Tools.isString(e)?e:e.format("YYYY-MM-DD")))
    //         const formatArr = this.sortDateFormat(Array.from(this.selectedDateSet));
    //         if (formatArr.length > 0) {
    //             this.setState({ formatStr: formatArr.join() });
    //         }
    //     }
    // }



    // 排序
    sortDateFormat = selectedArr => {
        // 排序数组
        selectedArr.sort((a, b) => moment(a).diff(moment(b)));
        // 遍历数组
        let conti_startStr,
            conti_endStr = "";
        let unPickDateSet = new Set(selectedArr);
        let pickDateSet = new Set();
        for (let i = 0; unPickDateSet.size !== 0; i++) {
            //如果没有到达末尾
            if (selectedArr[i + 1]) {
                // 当前节点与下一节点存在连续的情况
                if (
                    moment(selectedArr[i]).diff(moment(selectedArr[i + 1]), "days") === -1
                ) {
                    // 如果起始字符串为空，将当前节点设为起始日期
                    if (!conti_startStr) {
                        conti_startStr = selectedArr[i];
                        conti_endStr = selectedArr[i + 1];
                    } else {
                        // 当不为空时
                        conti_endStr = selectedArr[i + 1];
                    }
                    unPickDateSet.delete(selectedArr[i]); // 删除当前遍历节点 表示已经加入 （有可能已经被删过但是不影响）
                    unPickDateSet.delete(selectedArr[i + 1]); // 删除下一个节点
                } else {
                    //存在不连续时，执行加入
                    //如果当前已经存在连续节点
                    if (conti_startStr) {
                        pickDateSet.add(conti_startStr + " ~ " + conti_endStr);
                        conti_startStr = "";
                        conti_endStr = "";
                        unPickDateSet.delete(selectedArr[i]);
                        //滞空连续
                    } else {
                        pickDateSet.add(selectedArr[i]);
                        unPickDateSet.delete(selectedArr[i]);
                    }
                }
            } else {
                //如果已经处于末尾
                pickDateSet.add(selectedArr[i]);
                unPickDateSet.delete(selectedArr[i]);
            }
        }
        if (conti_startStr) {
            // 遍历结束如果还存在连续没有被 开始和结束点 补上
            pickDateSet.add(conti_startStr + " ~ " + conti_endStr);
            conti_startStr = "";
            conti_endStr = "";
        }
        return Array.from(pickDateSet);
    };

    handleOpenChange = open => {
        if (open) {
            this.setState({
                open
            });
        }
    };

    dateRender = date => {
        const { disabledDate } = this.props;
        if (disabledDate && disabledDate(date)) {
            return (
                <div className={`ant-calendar-date`}> {date.date()}</div>
            );
        } else {
            const formatDate = date.format("YYYY-MM-DD");
            const isSelected = this.selectedDateSet.has(formatDate)
                ? "muti-selected"
                : "muti-unSelected";
            return (
                <div
                    className={`ant-calendar-date multdate ${isSelected}`}
                    onClick={() => {
                        this.onClickDate(date);
                    }}
                >
                    {date.date()}
                </div>
            );
        }
    };

    onClickDate = date => {
        const formatDate = date.format("YYYY-MM-DD");
        if (this.selectedDateSet.has(formatDate)) {
            this.selectedDateSet.delete(formatDate);
        } else {
            this.selectedDateSet.add(formatDate);
        }
        const formatArr = this.sortDateFormat(Array.from(this.selectedDateSet));

        if (formatArr.length > 0) {
            this.setState({ formatStr: formatArr.join() });
        }
    };

    handleCancel = e => {
        e.preventDefault();
        this.setState({ open: false });
    };

    handleOk = e => {
        e.preventDefault();
        const { onChange } = this.props
        if (onChange) {
            onChange(Array.from(this.selectedDateSet).map(e => moment(e)), (Array.from(this.selectedDateSet) as string[]))
        }
        this.setState({ open: false });
    };

    onHandleChange = e=>{
        const { onChange } = this.props
        if(!e){
            //clearl all
            this.selectedDateSet = new Set();
            this.setState({ formatStr: null })
            if (onChange) {
                onChange([],[])
            }
            return false;
        }
    }

    render() {
        const { formatStr, open } = this.state
        return (
            <DatePicker
                {...this.props}
                onChange={this.onHandleChange.bind(this)}
                defaultValue={moment()}
                className={'dispersed-date-picker'}
                showToday={false}
                format={formatStr}
                open={open}
                onOpenChange={this.handleOpenChange}
                dateRender={this.dateRender}
                renderExtraFooter={() => {
                    return (
                        <div style={{ width: '100%', overflow: 'hidden', backgroundColor: '#fff' }}>
                            <div style={{ float: "right" }}>
                                <a
                                    onClick={this.handleCancel}
                                    style={{ marginRight: "10px", color: "gray" }}
                                >
                                    取消
                                </a>
                                <a href="#" onClick={this.handleOk}>
                                    确定
                                </a>
                            </div>
                        </div>
                    );
                }}
            />
        );
    }


}


