/*
* @Author: zhouningyi
* @Date: 2016-12-26 11:55:57
*/

import React, { Component, PropTypes } from 'react';
import Utils        from './../../lib/utils';
import UiBase       from './../uiBase';
import OpenIcon     from 'material-ui/svg-icons/navigation/expand-more';
import DropDownMenu from 'material-ui/DropDownMenu';
import IconButton   from 'material-ui/IconButton';
import Popover      from 'material-ui/Popover';
import MenuItem     from 'material-ui/MenuItem';
import Menu         from 'material-ui/Menu';
import InputBase    from './../Input/Base';
import './../MultiSelect/index.css';
import {fade, emphasize} from 'material-ui/utils/colorManipulator';

function getName (v, options) {
  if(!Array.isArray(options)){
    let vv;
    for(let k in options){
      vv = options[k];

      if(_.isEqual(v, vv)) return k
    }
  }
  if (v === null) return 'null';
  return (typeof(v) === 'object') ? v.name : v;
}

function replaceValue(validation){
  const {options} = validation.validate;
  const {value} = validation;
  if(options){
    _.forEach(options, v => {
      if(_.isEqual(v, value)) validation.value = v;
    })
  }
}

function getStyles(props, context, state){
  const { palette } = context.muiTheme;
  let {textColor, borderColor, primary1Color} = palette;
  borderColor = state.isActive ? primary1Color : borderColor;
  return {
    root: {
      borderWidth: 1,
      borderColor,
      borderStyle: 'solid',
      boxSizing: 'border-box',
      width: '100%',
      height: '100%'
    },
    input: {
      color: textColor,
      border: 0,
      outline: 0,
      height: '100%',
      background: 'transparent',
      margin: '5px 8px',
      flexGrow: 1
    },
    menuItem:{
      backgroundColor: emphasize(context.muiTheme.menuItem.hoverColor, 0.3),
    },
    rightIcon: {
      color: textColor
    }
  };
}


const empty = () => null;


const getValue = d => {
  if(typeof(d) === 'object') return d.value;
  return d;
}

export default class Select extends UiBase {
  static propTypes = {
    data:           PropTypes.any.isRequired,
    onChange:       PropTypes.func.isRequired,
    onFinishChange: PropTypes.func
  }
  static defaultProps = {
    onChange: () => null,
    onFinishChange: () => null,
    listN: 6
  }
  constructor(props: any) {
    super(props);
    this.state = {
      isInputActive: false
    };
  }
  onInputChange = (v) => {
    this.onChange(v);
  }
  onMenuItemClick(e, v){
    this.onChange(v);
    this._shrink();
  }
  onInputClick = (v) => {
    this.setState({
      isInputActive: !this.state.isInputActive
    });
  }
  onBgClick = () => {
    this._shrink();
  }
  _shrink(){
    this.setState({
      isInputActive: false
    });
  }
  _genMenus(){
    const {value, validate} = this.state.data;
    const {options} = validate;
    const style = getStyles(this.props, this.context, this.state);
    const inputWrapper = this.refs.inputWrapper;
    let minWidth, width, menuStyle = {};
    if(inputWrapper){
      width = minWidth = inputWrapper.clientWidth + style.root.borderWidth * 2;
      menuStyle = {minWidth};
    }
    const isarray = Array.isArray(options);
    return (
      <Popover
        open={this.state.isInputActive}
        anchorEl={this.refs.inputWrapper}
        anchorOrigin={{horizontal: 'left', vertical: 'bottom'}}
        targetOrigin={{horizontal: 'left', vertical: 'top'}}
        onRequestClose={this.onBgClick}
        useLayerForClickAway={true}
        style={menuStyle}
      >
        <Menu maxHeight={400} style={{overflowY:null}}>
          {_.map(options, (d, k) => {
            const styleM = _.isEqual(d, value) ? style.menuItem : {};
            let name, v;
            if (isarray){
              if(d === null) {
                name = 'null';
                v = null;
              } else {
                name  = typeof(d) === 'object' ? d.name  : d ;
                v     = typeof(d) === 'object' ? d.value : d;
              }
            } else {
              name = k;
              v = d;
            }
            return (
              <MenuItem
                 key={name}
                 value={v} 
                 primaryText={name}
                 style={styleM}
                 onTouchTap={e => this.onMenuItemClick(e, d, k)}
              >
              </MenuItem>
            );
          })}
        </Menu>
      </Popover>
    );
  }
  _genUI(){
    const {onChange, onFinishChange, listN, heightPhi} = this.props;
    const height = this._getDefaultHeight() * heightPhi + 'px';
    const {id, value} = this.state.data;
    const styles = getStyles(this.props, this.context, this.state);
    const style = Object.assign({height}, this._getSelectorStyle());
    return (
      <div className="z_select-container" style={style}>
        <div 
          className="z_input-container"
          style={styles.root}
          ref="inputWrapper"
          onClick={this.onInputClick}
        >
          <div className="z_select-text">
           {getName(value, this.state.data.validate.options)}
          </div>
          <div className="z_spliter"/>
          <OpenIcon
            style={styles.rightIcon}
          />
        </div>
        {this._genMenus()}
      </div>
    );
  }

  // _genUI(){
  //   let {onChange, onFinishChange, listN} = this.props;
  //   replaceValue(this.props.data);
  //   const height = this._getDefaultHeight();
  //   const maxHeight = listN * height;
  //   //
  //   const {data} = this.state;
  //   let {validate, value} = data;
  //   if(!validate.options) validate.options = [value];

  //   const lineHeight = `${height}px`;
  //   const style = this._getSelectorStyle();
  //   Object.assign({}, style, {height});
    
  //   return (
  //     <div className="z_select-container" style={style}>
  //       <DropDownMenu
  //         key={data.key}
  //         autoWidth={false}
  //         maxHeight={maxHeight}
  //         style={{width: '100%', height, margin: 0}}
  //         value={data.value}
  //         onChange={this.onChange}
  //         labelStyle={{lineHeight}}
  //         underlineStyle={{bottom: height / 6}}
  //         iconStyle={{right: 5, top: height / 16}}
  //         menuItemStyle={{width: '100%'}}
  //         menuStyle={{width: '100%'}}
  //       >
  //         {this._genMenus(validate.options)}
  //       </DropDownMenu>
  //    </div>
  //   )
  // }
}
