import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Tree, message, Row, Col } from 'amos-framework';
import RightOne from './rightOne';
import RightFour from './rightFour';
import RightSix from './rightSix';
import RightNine from './rightNine';
import { utils } from 'amos-tool';
import { getMonitorsByPageData, getMonitorsTreeData } from './../../../../services/videoServices';
import './../../../../styles/view/biz/monitor/videoLabel.scss';

const TreeNode = Tree.TreeNode;

/**
 *
 *
 * @class Video
 * @extends {Component}
 * @description 报警监控业务屏
 */
class Video extends Component {

  constructor() {
    var today = new Date(),
      now = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()} ${today.getHours()}:${today.getMinutes()}:${today.getSeconds()}`;

    super();
    this.state = {
      id: '9',
      //默认展示四画面
      arrange: 4,
      time: now,
      //监控集合
      monitorList: [],
      title: '监控中心',
      //分页
      pagination: {
        current: 1,
        pageSize: '',
        total: ''
      },
      //当前页详情
      currentMessage: '0/0',
      hikvideoList: [],
      monitorTree: []
    };
  }

  componentWillMount() {
    this.getMonitorsTree();
  }

  componentDidMount() {
    let { id, pagination } = this.state;
    if (id !== null && id !== '') {
      this.getMonitorListByPageData(pagination);
    }
  }

  /**
   *查询左侧树
   *
   * @memberof Video
   */
  getMonitorsTree = () => {
    getMonitorsTreeData().then((data) => {
      if (data) {
        this.setState({
          monitorTree: data
        });
      }
    });
  }

  onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
    let { pagination } = this.state;
    pagination.parentId = selectedKeys[0];
    this.setState({
      id: selectedKeys[0],
      title: info.node.props.dataRef.name
    });
    var arr = [];
    arr.push(info.node.props.dataRef);
    if (info.node.props.dataRef.isLeaf === '0') {
      this.setState({
        arrange: 1,
        monitorList: arr
      });
    } else {
      this.setState({
        arrange: 4
      });
      pagination.pageSize = 4;
      this.getMonitorListByPageData(pagination);
    }
  };

  // 分页查询
  handleTableChange = (mark) => {
    let { id, pagination, arrange } = this.state;
    pagination.parentId = id;
    pagination.pageSize = arrange;
    var pageNum = Math.ceil(pagination.total / pagination.pageSize);

    this.setState({ pagination });

    if (mark === 'first') {//首页
      if (pagination.current === 1) {
        message.danger('当前页为第一页');
      } else {
        pagination.current = 1;
        this.getMonitorListByPageData(pagination);
      }
    } else if (mark === 'before') {//上一页
      if (pagination.current === 1) {
        message.danger('当前页为第一页');
      } else {
        pagination.current = pagination.current - 1;
        this.getMonitorListByPageData(pagination);
      }
    } else if (mark === 'after') {//下一页
      var currentPage = pagination.current + 1;
      if (currentPage > pageNum) {
        message.danger('当前页为最后一页');
      } else {
        pagination.current = pagination.current + 1;
        this.getMonitorListByPageData(pagination);
      }
    } else if (mark === 'last') {//尾页
      if (pagination.current >= pageNum) {
        message.danger('当前页为最后一页');
      } else {
        pagination.current = pageNum;
        this.getMonitorListByPageData(pagination);
      }
    }
  };

  /**
   * 分页查询（后台请求）
   */
  getMonitorListByPageData = (pagination) => {
    if (!pagination.parentId) {
      let { id } = this.state;
      pagination.parentId = id;
    }
    getMonitorsByPageData(pagination).then((data) => {
      if (data.dataList.length > 0) {
        var pageNum = Math.ceil(data.total / data.pageSize);
        var currentMessage = data.pageSize < data.total && data.currPage <= pageNum ? `${data.currPage}\/${pageNum}` : `${pageNum}\/${pageNum}`;
        this.setState({
          monitorList: data.dataList,
          pagination: {
            current: data.currPage,
            pageSize: data.pageSize,
            total: data.total
          },
          currentMessage
        });
      } else {
        this.setState({
          monitorList: []
        });
      }
    });
  }

  /**
   * 左侧树
   */
  renderTreeNodes = (data) => {
    const branchImg = '/src/assets/monitor/branch.png';
    const leafImg = '/src/assets/monitor/leaf.png';
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode icon={<img src={item.isLeaf === '1' ? branchImg : leafImg} />} title={item.name} key={item.id} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode icon={<img src={item.isLeaf === '1' ? branchImg : leafImg} />} key={item.id} {...item} />;
    });
  }

  /**
   * 加载监控画面
   */
  arrangeShow = (arrange) => {
    let { time, pagination, monitorList } = this.state;
    pagination.pageSize = arrange;
    if (arrange === 1) {
      return <RightOne time={time} monitorList={monitorList} />;
    } else if (arrange === 4) {
      return <RightFour time={time} monitorList={monitorList} />;
    } else if (arrange === 9) {
      return <RightNine time={time} monitorList={monitorList} />;
    } else if (arrange === 6) {
      return <RightSix time={time} monitorList={monitorList} />;
    }
  }

  /**
   * 点击切换画面
   */
  onClick = (key) => {
    let { pagination } = this.state;
    this.setState({
      arrange: key
    });
    pagination.pageSize = key;
    pagination.current = 1;
    pagination.total = '';
    this.getMonitorListByPageData(pagination);
  }

  render() {
    const { className, ...other } = this.props;
    let { arrange, currentMessage, title, monitorTree } = this.state;
    let _this = this;
    return (
      <div className="monitor" >
        <div className="monitor-top">
          <Row>
            <Col className="monitor-title" span={11}>
              <img src="/src/assets/monitor/title.png" /><span>&nbsp;&nbsp;{title}</span>
            </Col>
            <Col className="monitor-btn" span={7}>
              <div className="row-btn">
                <img src="/src/assets/monitor/arrange1.png" onClick={() => _this.onClick(1)} />
              </div>
              <div className="row-btn">
                <img src="/src/assets/monitor/arrange4.png" onClick={() => _this.onClick(4)} />
              </div>
              <div className="row-btn">
                <img src="/src/assets/monitor/arrange9.png" onClick={() => _this.onClick(9)} />
              </div>
              <div className="row-btn">
                <img src="/src/assets/monitor/arrange6.png" onClick={() => _this.onClick(6)} />
              </div>
            </Col>
            <Col className="monitor-pagination" span={5}>
              <div className="row-btn">
                <img src="/src/assets/monitor/first.png" onClick={() => _this.handleTableChange('first')} />
              </div>
              <div className="row-btn">
                <img src="/src/assets/monitor/previous.png" onClick={() => _this.handleTableChange('before')} />
              </div>
              <div className="row-pagination">
                <span className="row-pagination-text">{currentMessage}页</span>
              </div>
              <div className="row-btn">
                <img src="/src/assets/monitor/next.png" onClick={() => _this.handleTableChange('after')} />
              </div>
              <div className="row-btn">
                <img src="/src/assets/monitor/last.png" onClick={() => _this.handleTableChange('last')} />
              </div>
            </Col>
          </Row>
        </div>
        <div className="monitor-down">
          <div className='monitor-left'>
            {!utils.isEmpty(monitorTree) && utils.isArray(monitorTree) &&
              <Tree showIcon
                onSelect={this.onSelect}
                defaultExpandAll
              >
                {this.renderTreeNodes(monitorTree)}
              </Tree>}
          </div>
          <div className='monitor-right'>
            {this.arrangeShow(arrange)}
          </div>
        </div>
      </div>
    );
  }
}

Video.propTypes = {
  className: PropTypes.string,
  arrange: PropTypes.number
};

export default Video;
