/**
 * Created by baoyinghai on 11/17/16.
 */
import React from 'react';
import moment from 'moment';
import { VIEW, EDIT } from '../../constant';
import { DatePicker, Input } from '../../../../../components/mxa';

// moment.locale('zh-cn');

class MyDatePicker extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      value: this.props.value,
    };
  }

  componentWillReceiveProps(next) {
    if (next.value !== this.state.value) {
      this.state.value = next.value;
    }
  }

  _changeTime2Moment = value => {
    return value ? moment(new Date(value)).locale('zh') : null;
  };

  _formatTime2Moment = value => {
    if (value) {
      const date = new Date(value);
      const year = date.getFullYear();
      let month = date.getMonth() + 1;
      let strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = '0' + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate;
      }
      return year + '-' + month + '-' + strDate;
    }
    return null;
  };

  _changeMoment2Time = value => {
    return value.toDate().getTime();
  };

  _onChange = target => {
    const times = this._changeMoment2Time(target);
    this.setState({ value: moment(times).locale('zh') });
    this.props.onChange && this.props.onChange(times);
  };

  render() {
    if (this.props.disabled) {
      return (
        <Input disabled={true} value={this._formatTime2Moment(this.state.value)} />
      );
    }
    const format = this.props.showTime ? 'YYYY-MM-DD HH:mm:ss' : '';
    if (this.props.showTime) {
      return (
        <DatePicker showTime={this.props.showTime} format={format} disabled={this.props.disabled} value={this._changeTime2Moment(this.state.value)} onChange={this._onChange} />
      );
    }
    return (
      <DatePicker disabled={this.props.disabled} value={this._changeTime2Moment(this.state.value)} onChange={this._onChange} />
    );
  }
}

const compRender = config => {
  const { record, props = {} } = config;
  return (
    <MyDatePicker showTime={record.displayComponent.isSelectTime} disabled={record.isReadonly || (props && props.isModalInputMappingItem && props.isLeadInto && props.modalInputIsReadonly)} />
  );
};

/* eslint-disable */
class StaticDisplay extends React.Component {
  render() {
    const value = this.props.value ? moment(new Date(this.props.value)) : null;
    return (
      <span>{value && value.format('YYYY-MM-DD')}</span>
    );
  }
}

export default {
  [VIEW]: () => (<StaticDisplay />),
  [EDIT]: compRender
};
