import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { PubSub } from 'ray-eventpool';
import classnames from 'classnames';
import Icon from 'amos-icon';
import { UUID } from 'amos-tool';
import { Scrollbars, Modal } from 'amos-framework';
import panelDataFactory from './../../../../utils/panelDataFactory';
import { ON_CARDFRAME_ADD, ON_CARDFRAME_REMOVE } from './../../../../consts/topicConsts';
import CreateDesk from './CreateDesk';

import CenterGraph from './CenterGraph';


const maxDesk = 5;

const datas = [
  { key: 'test1-1', title: '分类1-1', itemPath: '分类1/分类1-1', funcIcon: '/src/assets/funcicon/search.png' },
  { key: 'test1-2', title: '分类1-2', itemPath: '分类1/分类1-2', funcIcon: '/src/assets/funcicon/text.png' },
  { key: 'test1-3', title: '分类1-3', itemPath: '分类1/分类1-3', funcIcon: '/src/assets/funcicon/think.png' },
  { key: 'test2-1', title: '分类2-1', itemPath: '分类2/分类2-1', funcIcon: '/src/assets/funcicon/print.png' },
  { key: 'test2-2', title: '分类2-2', itemPath: '分类2/分类2-2', funcIcon: '/src/assets/funcicon/calender.png' },
  { key: 'test3-1', title: '分类3-1', itemPath: '分类3/分类3-1', funcIcon: '/src/assets/funcicon/calc.png' }
];

/**
 * middle
 *
 * @class MiddleContent
 * @extends {Component}
 */
class MiddleContent extends Component {

  static propTypes = {
    personCenters: PropTypes.array,
    style: PropTypes.object
  };

  constructor(props) {
    super(props);
    this.state = {
      activeDesk: 'defaultDesk',
      visible: false,
      personCenters: [{ key: 'defaultDesk', text: '默认桌面' }],
      cardPanelDataMap: new Map(),
      cols: { lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 }
    };
  }

  componentWillMount() {
    this.loadDefaultDesk();
  }

  componentDidMount() {
    this.pubsub_panelAdd = PubSub.subscribe(ON_CARDFRAME_ADD, (topic, chartType) => {
      this.onTrigerPanelAdd(chartType);
    });

    this.pubsub_panelRemove = PubSub.subscribe(ON_CARDFRAME_REMOVE, (topic, panelUID) => {
      this.onTrigerPanelRemove(panelUID);
    });
  }

  /**
   *  当组件卸载（unmounted）的时候，在 componentWillUnmount 事件中取消事件的订阅
   */
  componentWillUnmount() {
    PubSub.unsubscribe(this.pubsub_panelAdd);
    PubSub.unsubscribe(this.pubsub_panelRemove);
  }

  onItemClick = (e, deskId) => {

  }

  onSaveNewDesk = (deskname) => {

    const personCenters = this.state.personCenters;
    personCenters.push({
      key: UUID.timeUUID('amos-desk'),
      text: deskname
    });

    this.setState({
      personCenters,
      visible: false
    });
  }

  onCreateCancel = () => {
    this.setState({
      visible: false
    });
  }

  onPanelLayoutChange = (layouts = []) => {

  }

  onTrigerPanelAdd = () => {
    const { cardPanelDataMap } = this.state;
    const opts = { existPanelSize: cardPanelDataMap.size, cardOptions: {
      data: datas
    } };
    const data = panelDataFactory(opts);
    const panelUID = data.uid;
    cardPanelDataMap.set(panelUID, data);
    this.setState({
      cardPanelDataMap
    });
  }

  /**
   * 移除一个cardPanel
   */
  onTrigerPanelRemove = (panelUID) => {
    const { cardPanelDataMap: newDatas } = this.state;
    newDatas.delete(panelUID);
    this.setState({ cardPanelDataMap: newDatas });
  }

  /**
   * 加载默认桌面
   */
  loadDefaultDesk = () => {
    const { cardPanelDataMap } = this.state;
    const opts = { existPanelSize: cardPanelDataMap.size, cardOptions: {
      title: '推荐&最新应用',
      closable: false,
      data: datas
    } };
    const data = panelDataFactory(opts);
    const panelUID = data.uid;
    cardPanelDataMap.set(panelUID, data);

    const addOpts = { panelUID: 'panel-add', existPanelSize: cardPanelDataMap.size, cardOptions: {
      isAddFrame: true
    } };
    const add = panelDataFactory(addOpts);
    cardPanelDataMap.set(add.uid, add);
    this.setState({
      cardPanelDataMap
    });
  }

  addDesktop = () => {
    const { personCenters } = this.state;

    if (personCenters.length === maxDesk) {
      Modal.warning({
        title: '警告',
        content: '最多添加5个自定义桌面！'
      });
    } else {
      this.setState({
        visible: true
      });
    }
  }

  addCradFrame = () => {
    this.onTrigerPanelAdd();
  }

  renderHeaderDesk = () => {
    const { activeDesk, personCenters } = this.state;
    return (
      personCenters.map(pc => {
        const isActive = activeDesk === pc.key;
        const cls = classnames({
          'desktop-tab': true,
          'center-tab-item': true,
          'active-tab': isActive
        });
        return (
          <div className={cls} key={pc.key} title={pc.text} onClick={(e) => this.onItemClick(e, pc.key)}>{pc.text}</div>
        );
      })
    );
  }

  render() {
    const { cardPanelDataMap, visible, cols } = this.state;
    const { style } = this.props;

    return (
      <div className="personal-center" style={style}>
        <div className="center-header">
          {this.renderHeaderDesk()}
          <div className="center-tab center-tab-item" title="新增桌面" onClick={this.addDesktop}><Icon icon="add" /></div>
          <div className="center-tab center-tab-item" title="设置" onClick={this.addCradFrame}><Icon icon="setting" /></div>
          <Modal
            header="新增桌面"
            visible={visible}
            noDefaultFoote
            onCancel={this.onCreateCancel}
            content={<CreateDesk onSaveNewDesk={this.onSaveNewDesk} onCancel={this.onCreateCancel} />}
          />
        </div>
        <div className="center-body amos-clearfix">
          <Scrollbars>
            <CenterGraph
              cardPanelDataMap={cardPanelDataMap}
              onPanelLayoutChange={this.onPanelLayoutChange}
              cols={cols}
            />
          </Scrollbars>
        </div>
      </div>
    );
  }
}

export default MiddleContent;
