/**
 * Created by baoyinghai on 5/26/17.
 */
import React from 'react';
import './css/index.less';
import { fetch, popAlert } from './util';
import { initApi, updateApi } from './constant/link';

import DashBoard from './components/DashBoard';

export default class MetaBase extends React.Component {

  state = {
    cards: []
  };

  updateCards = (cards = []) => {
    this.setState({
      cards
    }, () => {
      // 更新
      fetch(updateApi, cards.map((c, index) => {
        c.chartSetting = JSON.stringify(c.chartSetting);
        c.index = index;
        return c;
      }), response => {
        console.log(response);
        this.state.cards = response;
      }, error=> {
        console.log(error);
      })
    });
  };

  componentWillMount() {
    fetch(initApi, {}, response => {
      this.setState({
        cards: (response || []).map((c, index) => {
          c.chartSetting = JSON.parse(c.chartSetting);
          c.index = index;
          return c;
        })
      });
    }, error => {
      popAlert('初始化dashboard异常！请联系管理员！');
      console.log(error);
    });
  }

  render() {
    return (
      <div className="metabase">
         <div className="dashboard-container">
           <DashBoard cards={this.state.cards} updateCards={this.updateCards} switchNavBar={this.props.switchNavBar} />
          </div>
      </div>
    );
  }
}
