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 { trim } from 'amos-tool';
import { Scrollbars, Modal, message } from 'amos-framework';

import title from '_MOCK/title';
import { recommends } from '_MOCK/apps';
import { amosRequest } from 'amos-processor';
import { secExtUrl as Url } from 'CONSTS/urlConsts';
import { ON_CARDFRAME_ADD, ON_CARDFRAME_REMOVE } from 'CONSTS/topicConsts';

import panelUid from './../../../../utils/panelUid';
import CreateDesk from './CreateDesk';

import SortGraph from './SortGraph';


const maxDesk = 5;

/**
 * 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: '默认桌面' }],
      cardPanelDataArr: []
    };
  }

  componentWillMount() {
    // this.loadDefaultDesk(1);
    this.loadAllDesk(()=>{
      let { personCenters = [] } = this.state;
      console.log('personCenters', personCenters);
      let activeDesk = (personCenters[0] || {}).key;
      this.setState({ activeDesk });
      setTimeout(()=>{this.loadDefaultDesk(activeDesk);}, 100);
    });
  }

  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);
    });
  }

  componentDidUpdate(prevProps, prevState) {
    let deskItemInput = document.getElementById('deskItemInput');
    deskItemInput && deskItemInput.focus();
  }
  /**
   *  当组件卸载（unmounted）的时候，在 componentWillUnmount 事件中取消事件的订阅
   */
  componentWillUnmount() {
    PubSub.unsubscribe(this.pubsub_panelAdd);
    PubSub.unsubscribe(this.pubsub_panelRemove);
  }

  onItemClick = (e, deskId) => {
    this.setState({
      activeDesk: deskId
    });
    this.loadDefaultDesk(deskId);
  }

  onItemRemoveClick = (e, deskId) => {
    let { personCenters } = this.state;
    let defaultDeskId = (personCenters[0] || {}).key;
    if (deskId === defaultDeskId) {
      message.danger('默认桌面不能删除！');
    } else {
      amosRequest(`${Url.deskRemoveUrl}/${deskId}`,{ method: 'DELETE' }).then(
        (data) => {
          this.loadAllDesk(()=>{
            this.setState({ activeDesk: defaultDeskId });
            this.loadDefaultDesk(defaultDeskId);
          });
        }
      );
    }
  }

  onItemDoubleClick = (e, deskKey) => {
    let personCenters = this.state.personCenters.map((pc, index) => {
      if (pc.key === deskKey) {
        if (index === 0){
          message.danger('默认桌面不能编辑！');
        } else {
          pc.status = 'edit';
        }
      }
      return pc;
    });
    this.setState({ personCenters });
  }

  onItemBlur = (e, desk) => {
    // e.stopPropagation();
    // let personCenters = this.state.personCenters.map(pc => {
    //   if (pc.key === desk.key) {
    //     pc.status = undefined;
    //     pc.text = e.target.value;
    //   }
    //   return pc;
    // });
    // amosRequest(Url.deskEditUrl,
    //   {
    //     method: 'POST',
    //     body: { id: desk.key, name: trim(e.target.value) }
    //   }
    // ).then(
    //   (data) => {
    //     this.loadAllDesk();
    //   }
    // );
    // this.setState({ personCenters });
  }

  onSaveNewDesk = (deskname) => {

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

    // this.setState({
    //   personCenters,
    //   visible: false
    // });
    // amosRequest(Url.deskAddUrl,
    //   {
    //     method: 'PUT',
    //     body: {
    //       name: deskname
    //     }
    //   }
    // ).then(
    //   (data) => {
    //     this.loadAllDesk();
    //     this.setState({ visible: false });
    //   }
    // );
  }

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

  onTrigerPanelAdd = () => {
    const { cardPanelDataArr } = this.state;
    const opts = { uid: panelUid(), cardOptions: {
      title: title(),
      data: recommends().dataList
    } };
    // cardPanelDataArr.push(opts);
    cardPanelDataArr.splice(cardPanelDataArr.length - 1, 0, opts);
    this.setState({
      cardPanelDataArr
    });
  }

  /**
   * 移除一个cardPanel
   */
  onTrigerPanelRemove = (panelUID) => {
    const { cardPanelDataArr: newDatas } = this.state;
    const result = newDatas.filter(nd => nd.uid !== panelUID);
    this.setState({ cardPanelDataArr: result });
  }
  /**
   * 加载所有桌面
   */
  loadAllDesk = (callBack) => {
    callBack = callBack || function(){};
    // amosRequest(Url.deskListUrl,{ method: 'GET' }).then(
    //   (data) => {
    //     let deskList = data.dataList || [];
    //     deskList = deskList.map(e => {
    //       return { key: e.id, text: e.name };
    //     });
    //     this.setState({
    //       personCenters: deskList
    //     }, callBack);
    //   }
    // );
  }
  /**
   * 加载默认桌面
   */
  loadDefaultDesk = (deskId) => {
    const { cardPanelDataArr } = this.state;
    // const opts = { uid: panelUid(), cardOptions: {
    //   title: '推荐&最新应用',
    //   closable: false,
    //   data: recommends().dataList
    // } };
    const add = { uid: 'panel-add', cardOptions: {
      isAddFrame: true
    } };
    this.setState({ cardPanelDataArr: [add] });
    // amosRequest(`${Url.deskPanelDetailsUrl}/${deskId}`,{ method: 'GET' }).then(
    //   (data) => {
    //     let deskList = data.dataList || [];
    //     let list = deskList.map(e => {
    //       let obj = {};
    //       obj.uid = e.id;
    //       obj.cardOptions = {
    //         title: e.name,
    //         data: e.appinfos.map(app => {
    //           let appItem = {};
    //           appItem.key = app.id;
    //           appItem.title = app.appName;
    //           appItem.funcIcon = app.image || '/src/assets/funcicon/search.png';
    //           return appItem;
    //         })
    //       };
    //       return obj;
    //     });
    //     list.push(add);
    //     this.setState({
    //       cardPanelDataArr: list
    //     });
    //   }
    // );
  }

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

    if (personCenters.length === maxDesk) {
      message.info('最多添加5个自定义桌面！');
    } else {
      this.setState({
        visible: true
      });
    }
  }

  setting = () => {


  }

  renderHeaderDesk = () => {
    const { activeDesk, personCenters } = this.state;
    return (
      personCenters.map((pc, index) => {
        const isActive = activeDesk === pc.key;
        const cls = classnames({
          'desktop-tab': true,
          'center-tab-item': true,
          'active-tab': isActive
        });
        let itemProps = pc.status !== 'edit' ? { onDoubleClick: (e) => this.onItemDoubleClick(e, pc.key) } : {};
        return (
          <div className={cls} key={pc.key} title={pc.text} {...itemProps} onClick={(e) => this.onItemClick(e, pc.key)}>
            { pc.status === 'edit' ? <input id="deskItemInput" type="text" onBlur={(e)=>this.onItemBlur(e, pc)} defaultValue={pc.text} /> : pc.text }
          </div>
        );
      })
    );
  }

  render() {
    const { cardPanelDataArr, visible } = 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.setting}><Icon icon="setting" /></div>
          <Modal
            header="新增桌面"
            visible={visible}
            noDefaultFooter
            onCancel={this.onCreateCancel}
            content={<CreateDesk onSaveNewDesk={this.onSaveNewDesk} onCancel={this.onCreateCancel} />}
          />
        </div>
        <div className="center-body amos-clearfix">
          <Scrollbars>
            <SortGraph
              cardPanelDataArr={cardPanelDataArr}
              onCardAdd={this.onTrigerPanelAdd}
            />
          </Scrollbars>
        </div>
      </div>
    );
  }
}

export default MiddleContent;
