/**
 * Created by baoyinghai on 5/31/17.
 */
import React from 'react';
import SaveButton from '../Button/SaveButton';
import CancelButton from '../Button/CancelButton';
import { Visualizations, setting } from '../../visualizations';
import SettingButton from '../Button/SettingButton';
import Arrow from '../Icon/Arrow';
import { fetch, popModal, closeWhileClickSpace, popAlert } from '../../util';
import { sqlApi } from '../../constant/link';
import SQLEditor from '../SQLEditor';
import Setting from '../Setting';
import "./CardSetting.less";

const DropDown = props => {
  const { items, value, show } = props;
  if (!show) return null;
  return (
    <div className="drop-down-wrapper">
      <div className="arrow-up"/>
      {items.map(v => {
        return (
          <div className={v === value ? 'item is-focus' : 'item'} onClick={() => {
            const { onHandleChange, switchHandler } = props;
            switchHandler && switchHandler();
            onHandleChange && onHandleChange(v);
          }}>{v.toLocaleUpperCase()}</div>
        );
      })}
    </div>
  );
};

export default class CardSetting extends React.Component {

  state = {
    visualizationName: 'table',
    buttonDesc: '刷新数据',
    dataSource: [],
    chartSetting: {},
    showDropDown: false,
    containerHeight: 400,
  };

  constructor(props) {
    super(props);
    this.querySql = this.props.querySql;
    this.sqlModify = false;
  }

  handleChange = value => {
    this.setState({
      visualizationName: value,
    });
  };

  fetchData = isInit => {
    const self = this;
    const sqlStr = self.querySql;
    const builtInType = self.props.builtInType;
    if (sqlStr) {
      fetch(sqlApi, {requestParamsBean: {sql: sqlStr, builtInType}}, response => {
        console.log(response);
        let data = response;
        if ('Process' === builtInType) {
          data = (response && response.contentList) || [];
        }
        self.sqlModify = false;
        this.setState({
          dataSource: data || [],
          chartSetting: {}
        });
      }, error => {
        popAlert(error);
      });
    } else {
      !isInit && popAlert('请输入sql语句查询数据');
    }
  };

  updateSetting = (key, setting, title) => {
    this.setState({
      chartSetting: setting,
      title
    });
  };

  popSettingModel = () => {
    if (!this.state.dataSource || this.state.dataSource.length === 0) {
      popAlert('请选择数据源！');
    } else {
      const settingProps = setting[this.state.visualizationName];
      const body = props => {
        return (
          <Setting {...settingProps} title={this.props.title} chartSetting={this.state.chartSetting} index={-1} updateSetting={this.updateSetting} onClick={props.callback} createBottomButtons={props.createBottomButtons} dataSource={this.state.dataSource} />
        );
      };
      popModal(this.state.visualizationName, body);
    }
  };

  componentDidMount() {
    this.fetchData(true);
    this.setState({containerHeight: window.innerHeight - 250});
  }

  showDropDown = () => {
    this.setState({
      showDropDown: !this.state.showDropDown
    });
  };

  renderVisualization = () => {
    return (
      <a className="visualization-label" onClick={this.showDropDown}>{this.state.visualizationName.toLocaleUpperCase()}</a>
    );
  };

  calculatePosition = (width, height) => {
    const { calculatePosition } = this.props;
    return calculatePosition(width, height);
  };

  save = () => {
    // TODO: 是否可以保存
    if (this.sqlModify) {
      popAlert('sql语句变更，请刷新数据！');
      return;
    }
    if (this.querySql) {
      this.props.addCards({
        title: this.state.title || this.state.visualizationName,
        layout: {
          ...this.calculatePosition(8, 5),
          width: 8, height: 5
        },
        chartType: this.state.visualizationName,
        querySql: this.querySql,
        chartSetting: this.state.chartSetting,
        panelDefinitionId: this.props.panelDefinitionId,
        builtInType: this.props.builtInType
      });
    } else {
      this.props.cancel();
    }
  };

  _renderButtons = () => {
    const ret = [];
    ret.push(<SaveButton onClick={this.save} />);
    ret.push(<CancelButton onClick={this.props.cancel} />);
    return ret;
  };

  setSqlStr = value => {
    this.querySql = value;
    this.sqlModify = true;
  };

  render() {
    const Comp = Visualizations[this.state.visualizationName];
    const DropDownMenu = closeWhileClickSpace(DropDown, {
      defaultShow: this.state.showDropDown,
      querySelector: 'select-group'
    });
    const width = window.innerWidth - 70;
    const height = this.state.containerHeight - 30;
    return (
    <div>
      <div className="button-bar">
        {this._renderButtons()}
      </div>
      <SQLEditor setSqlStr={this.setSqlStr} sqlStr={this.querySql} />
      <div className="card-setting-wrapper">
        <div className="select-group">
          {this.renderVisualization()}
          <div onClick={this.showDropDown} className="arrow-wrapper"><Arrow /></div>
          <DropDownMenu value={this.state.visualizationName} switchHandler={this.showDropDown} items={Object.keys(Visualizations)} onHandleChange={this.handleChange} />
        </div>
        {setting[this.state.visualizationName] && <SettingButton style={{float: 'left', marginTop: '-4px'}} onClick={this.popSettingModel} />}
        <a className="run-button" onClick={e => this.fetchData()}>{this.state.buttonDesc}</a>
        <div className="chart-create-container" style={{height: this.state.containerHeight + 'px'}}>
          {this.state.dataSource.length > 0 && Comp
            ? <Comp chartSetting={this.state.chartSetting} dataSource={this.state.dataSource} width={width} height={height} />
            : <div style={{width, height, lineHeight: height + 'px'}}>没有数据</div>}
        </div>
      </div>
    </div>
    );
  }
}