import React from "react";
import ReactDOM from 'react-dom'
import PropTypes from "prop-types";
import { Radio, Input, Checkbox, Select, Modal, Table, Icon,DatePicker, message, Tabs, Row, Col, Button, Menu, Dropdown, Alert, Spin } from 'antd';
import moment from 'moment';
const { RangePicker } = DatePicker;

import {
    getYear,
    addYears,
    subYears,
  } from "./date_utils";
import './yearPicker.css'

export default class Year extends React.Component {
  static propTypes = {
    // date: PropTypes.string,
    // onDayClick: PropTypes.func
  };

  constructor(props) {
    super(props);
    this.state={
        selectDate:new Date(),   //选中的值
        inputDate:'',   //文本框的值
        inputValue:'',  //动态文本框值
        date:new Date(), 
        yearsToShow:11,//每页轮回显示 年数
        focused:false,
        mousePos:false,
        open:false,
        testComponent:null,
        maxY:9999,  //上线年份
        minY:1000,  //下线年份
        dateFormat:'YYYY',  //年份格式 
        disabled:false,
    }
  }
  componentDidMount() {
    let dateFormat="YYYY"
    if(this.props.dateFormat){
        if(this.props.dateFormat.toLocaleUpperCase()==="YYYY年"){
            dateFormat="YYYY年"
            this.setState({ dateFormat:"YYYY年" });
        }else if(this.props.dateFormat.toLocaleUpperCase()==="YYYY"){
            this.setState({ dateFormat:"YYYY" });
        }
    }
    if (this.props.selectDate) {
        this.setState({ 
            selectDate: this.props.selectDate._i,
            date: this.props.selectDate._i,
            inputDate: getYear(this.props.selectDate._i ),
            // inputDate: getYear(this.props.selectDate._i ),
         });
         this.dateFormatYear(getYear(this.props.selectDate._i ),dateFormat)
    }else{
        this.setState({ selectDate:new Date() });
    }
    document.addEventListener('click', this.handleClick)
  }
  componentWillReceiveProps(nextProps){
        if(nextProps.dateFormat){
            if(nextProps.dateFormat.toLocaleUpperCase()==="YYYY年"){
                this.setState({ dateFormat:"YYYY年" });
            }else if(nextProps.dateFormat.toLocaleUpperCase()==="YYYY"){
                this.setState({ dateFormat:"YYYY" });
            }
        }
        if(nextProps.selectDate==="" || nextProps.selectDate===null){
            this.setState({ 
                inputDate:'',   //文本框的值
                inputValue:''
            });           
        }
        if(!nextProps.disabled){
          this.setState({ disabled:false });
        }else{
          this.setState({ disabled:true });
        }
    }
  dateFormatYear(y,format){
    if(y===null || y===""){
        this.setState({ inputDate:y });
        return y
    }else{
        let year=getYear(moment().set('year',y)) 
        if(format){
            if(format==="YYYY年"){
                year+="年"
            }
        }else{
            if(this.state.dateFormat==="YYYY年"){
                year+="年"
            }
        }
          
        this.setState({ inputDate:year });
        return year
    }
    
  }
  componentWillUnmount() {
    document.removeEventListener('click', this.handleClick)
  }
  handleClick = e => {
        // if(this.testComponent.contains(e.target)) {
            // if(this.containerComponent&&this.containerComponent.contains(e.target) || this.inputComponent&&this.inputComponent.contains(e.target) ) {
            // } else {
            //     this.cultureValue()

            //     this.setState({
            //         focused:false
            //     })
            //     this.removeModal()
            // }
        // }
            // return;
        let child=e.target
        let parent=document.getElementById('yeatPickerModal')
        if( parent&&parent.contains(e.target) || (e.target.parentElement&&e.target.parentElement.classList&&e.target.parentElement.classList[0]==="yearPicerInput") ) {
        } else {
            this.cultureValue()

            this.setState({
                focused:false
            })
            this.removeModal()
        }
    
  }
  handleYearClick = (day, event) => {
    if (this.props.onYearClick) {
      this.props.onYearClick(day, event);
    }
  };

  onYearClick = (e, y) => {
    e.stopPropagation()
    this.setState({
        selectDate:moment().set('year',y),
        inputDate:getYear(moment().set('year',y)) ,
        // inputDate:year,
        focused:false
    })
    this.removeModal()
    let year= this.dateFormatYear(getYear(moment().set('year',y)))
    this.handleYearClick(moment().set('year',y),year);
  }
  cultureValue(){
    let { 
        inputValue,  //原有的数值
        inputDate,    //实时变动 有可能不正确的值
        minY,
        maxY
     } = this.state;
    let value='';
    function isIntNum(val) {
        var reg = /^\d{1,}$/
        var pattern = new RegExp(reg);
        return pattern.test(val);
    }
    if(inputDate&&inputDate[inputDate.length-1]==="年"){
        inputDate=inputDate.slice(0,inputDate.length-1)
    }
    if(inputDate&&(inputDate>=minY&&inputDate<=maxY)){
        if(isIntNum( inputDate)){
            value=inputDate
        }
        
    }else if(inputDate===null ||inputDate===''){
        value=null
    }else if(inputValue!=="0000"){
        value=inputValue
    }
   
    this.setState({
        // inputDate: value,
        selectDate:value===null ||value===''? moment().set('year',getYear(new Date())):moment().set('year',value),
        date: value===null ||value===''? moment().set('year',getYear(new Date())):moment().set('year',value),
    })
    this.dateFormatYear(value)

  }
  handleBlur = event => {
    const { open } = this.state;
    if(open){
        return;
    }
    this.cultureValue()
    this.setState({ focused: false });
    this.removeModal()
  };
  handleFocus = event => {
    event.stopPropagation();
    event.nativeEvent.stopImmediatePropagation()
    let { inputDate } = this.state;
    if(inputDate===null ||inputDate===''){
        inputDate= getYear(new Date())
    }
    this.setState({ 
        focused: true,
        open:true,
        inputValue: inputDate,
     });
     this.renderYearContainer(event)
  };
  handleChange = (...allArgs) => {
    const { inputDate } = this.state;

    let event = allArgs[0];
    if (this.props.onChangeRaw) {
      this.props.onChangeRaw.apply(this, allArgs);
      if (
        typeof event.isDefaultPrevented !== "function" ||
        event.isDefaultPrevented()
      ) {
        return;
      }
    }
    this.setState({
        inputDate:event.target.value
    });
    
    
    // const date = parseDate(
    //   event.target.value,
    //   this.props.dateFormat,
    //   this.props.locale,
    //   this.props.strictParsing
    // );
    // if (date || !event.target.value) {
    //   this.setSelected(date, event, true);
    // }
  };
  handleMouseOver=event=>{
    this.setState({ mousePos: true });

  }
  handleMouseOut=event=>{
    this.setState({ mousePos: false });

  }
  clearValue=event=>{
    this.setState({
        inputDate:null,
        selectDate:null,
        focused:false
    })
    this.removeModal()
  }
  renderDateInput = () => {
   
    const { inputDate,mousePos,disabled } = this.state;
    const { dateFormat,style } = this.props;
    let selectedDate=''
    if(inputDate){
        selectedDate=inputDate
    }
    let eleIcon=<Icon type="calendar"  />

        if(mousePos&&selectedDate&&!disabled){
            eleIcon=<Icon type="close-circle" onMouseEnter={this.handleMouseOver}  onClick={this.clearValue} />
        }
        const customInput =<Input style={ style } suffix={eleIcon}  />;
    return React.cloneElement(customInput, {
        className:"yearPicerInput",
        value: selectedDate,
        onBlur: this.handleBlur,
        onChange: this.handleChange,
        //   onClick: this.onInputClick,
        onFocus: this.handleFocus,
        onMouseEnter:this.handleMouseOver,
        onMouseLeave:this.handleMouseOut,
        onKeyDown: this.onInputKeyDown,
        id: this.props.el,
        name: this.props.name,
        autoFocus: this.props.autoFocus,
        placeholder: this.props.placeholderText ? this.props.placeholderText :"请选择年份"  ,
        disabled: this.props.disabled,
        autoComplete: this.props.autoComplete,
        title: this.props.title,
        readOnly: this.props.readOnly,
        required: this.props.required,
        tabIndex: this.props.tabIndex,
        "aria-labelledby": this.props.ariaLabelledBy
        });
  };

  
  increaseYear = () => {
    const { date ,yearsToShow,maxY} = this.state;
    if(getYear(date)>=maxY){
        return;
    }
    this.setState(
      ({ date }) => ({
        date: addYears(date, yearsToShow )
      }),
      () => this.handleYearChange(this.state.date)
    );
  };
  decreaseYear = () => {
      
    const { date,yearsToShow,minY } = this.state;
    if(getYear(date)<=minY){
        return;
    }

    this.setState(
      ({ date }) => ({
        date: subYears(date, yearsToShow)
      }),
      () => this.handleYearChange(this.state.date)
    );

  };
  handleYearChange = date => {
    if (this.props.onYearChange) {
      this.props.onYearChange(date);
    }
    this.renderYearContainer()

  };
  renderYearContainer=(event)=>{
    const yearsList = [];
    const { selected,dateFormat,style } = this.props;
    const { date,selectDate,yearsToShow ,focused,maxY,minY} = this.state;
    let maxYear=getYear(date)
    let currYear=getYear(selectDate)
    
    for (
      let y = maxYear - yearsToShow, i = 0;
      y <= maxYear;
      y++, i++
    ) {
        let classNa="react-datepicker__year-container-text";
        if(y===currYear){
            classNa+=" activeYear"
        }
        if(y<minY || y>maxY){
            classNa+=" disableYear"
        }
      yearsList.push(
        <div
          onClick={ev => {
            this.onYearClick(ev, y);
          }}
          className={classNa}
          key={y}
        >
          {y}
        </div>
      );
    }
    
    let yearContainer=(
        <div id=""  ref = {containerComponent => this.containerComponent = containerComponent} >
            <div className="panel-container" onClick={event=> event.preventDefault()} onMouseEnter={event=>this.setState({open:true})} >
            <div className="picker-header">
                <button type="button"  className="prev-btn"  onClick={ev => {
                    this.decreaseYear(ev);
                }} >
                    <Icon type="double-left" />
                </button>
                <span  className="decade-btn">
                {getYear(date) - 11} - {getYear(date)}
                </span>
                <button type="button" className="next-btn" onClick={ev => {
                    this.increaseYear(ev);
                }}>
                    <Icon type="double-right" />
                </button>
            </div>
            <div className="react-datepicker__year-container">{yearsList}</div>
        </div>
       
    </div>
    );
    let div=document.createElement('div')
    if(document.getElementById("yeatPickerModal")){
        div = document.getElementById("yeatPickerModal");    

    }else{
        div.style.position="absolute"
        div.setAttribute('id', 'yeatPickerModal');
        if (event&&event.target.getBoundingClientRect) {
            let left = event.target.getBoundingClientRect().left + event.target.scrollLeft;
            let top = event.target.getBoundingClientRect().top + event.target.scrollTop;
            div.style.top=top+"px"
            div.style.left=left+"px"
            event.stopPropagation();
        }  
        document.body.appendChild(div);
    }
    
    ReactDOM.render(yearContainer, div);
  }

    /**
     * 删除弹框
     */
    removeModal = function() {
        if(document.getElementById("yeatPickerModal")) {
            $("#yeatPickerModal").remove();
            // document.getElementById('yeatPickerModal').remove();
        }
    }

  render(){
    const yearsList = [];
    const { selected,dateFormat,style } = this.props;
    const { date,selectDate,yearsToShow ,focused,maxY,minY} = this.state;
    let maxYear=getYear(date)
    let currYear=getYear(selectDate)
    
    for (
      let y = maxYear - yearsToShow, i = 0;
      y <= maxYear;
      y++, i++
    ) {
        let classNa="react-datepicker__year-container-text";
        if(y===currYear){
            classNa+=" activeYear"
        }
        if(y<minY || y>maxY){
            classNa+=" disableYear"
        }
      yearsList.push(
        <div
          onClick={ev => {
            this.onYearClick(ev, y);
          }}
          className={classNa}
          key={y}
        >
          {y}
        </div>
      );
    }
    return (
        <div  className="react-datepicker" ref = {inputComponent => this.inputComponent = inputComponent} >
            <div className="react-datepicker__input-container" >
                {this.renderDateInput()}
            </div>
            {/* {
                focused?
                <div className="panel-container" onClick={event=> event.preventDefault()} onMouseEnter={event=>this.setState({open:true})} >
                    <div className="picker-header">
                        <button type="button"  className="prev-btn"  onClick={ev => {
                            this.decreaseYear(ev);
                        }} >
                            <Icon type="double-left" />
                        </button>
                        <span  className="decade-btn">
                        {getYear(date) - 11} - {getYear(date)}
                        </span>
                        <button type="button" className="next-btn" onClick={ev => {
                            this.increaseYear(ev);
                        }}>
                            <Icon type="double-right" />
                        </button>
                    </div>
                    <div className="react-datepicker__year-container">{yearsList}</div>
                </div>
                :null
            } */}
        </div>
    )
    
  }

}
