import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Spin } from 'amos-antd';
import { message } from 'amos-framework';
import { AmosFetch } from 'UTILS/processor';
import OltSerUrl from 'CONSTS/urlConsts';
import { dataAnaysisUrl } from 'CONSTS/outterUrlConsts';
import QueryPanel from './QueryPanel';
import HistoryChartView from './HistoryChartView';
import { dateToNoYSWeek } from './../common/date/DateUtil';
import './history.scss';

const ONEDAY_HOUR = 24;//1天24小时
const ONEHOUR_MINUTE = 60;//1小时60分钟
const ONEMINUTE_SECOND = 60;//1分钟60秒
const ONESECOND_MILL = 1000;//1秒1000毫秒
const ONE_DAY = 24 * ONEHOUR_MINUTE * ONEMINUTE_SECOND * ONESECOND_MILL;//1天
// const selectLegends = [
//   {
//     label: '设备资源', value: '设备资源', unit: '%', data: [
//       { name: 'CPU', icon: 'circle', color: 'green', fetchDateName: 'exeTime', valueVarName: 'cpuData' },
//       { name: '内存', icon: 'circle', color: 'red', fetchDateName: 'exeTime', valueVarName: 'memoryData' }
//     ]
//   }
// ];
// const netHistoryData = { cpuData: [{ exeTime: 1521475200000,value: 1 },{ exeTime: 1521485200000,value: 1 },{ exeTime: 1521495200000,value: 1 }] };
/**
 *
 *历史数据
 * @class HistoryPanel
 * @extends {Component}
 */
class HistoryPanel extends Component {
  constructor(props) {
    super(props);
    this.searchParam = {};
    this.state = {
      historyData: { cpuData: [] },
      loading: false
    };
  }

  componentDidMount = () => {
    // this.getHistoryData();
  }

  //设置
  setDayHistoryChartViewProps = (netHistoryData,legend,unit) => {
    let searchParam = this.searchParam;
    let yesterdayDate = new Date();
    yesterdayDate.setTime(yesterdayDate.getTime() - (ONEDAY_HOUR * ONEHOUR_MINUTE * ONEMINUTE_SECOND * ONESECOND_MILL));
    yesterdayDate = yesterdayDate.getTime();
    return {
      unit,
      interval: 2 * ONEHOUR_MINUTE * ONEMINUTE_SECOND * ONESECOND_MILL,//间隔：两小时
      min: searchParam.startTimeStr === undefined ? new Date().getTime() - ONE_DAY : new Date(searchParam.startTimeStr).getTime(),
      max: searchParam.endTimeStr === undefined ? new Date().getTime() : new Date(searchParam.endTimeStr).getTime(),
      axisLabelFormatter: dateToNoYSWeek,
      data: netHistoryData,
      legend
    };
  }

  //获取图表区内容
  getChartContent = () => {
    let { historyData } = this.state;
    let content = [];
    Object.keys(historyData).map((key) => {
      let capacity = key.split('-')[1];
      let name = key.split('-')[2];
      let unit = key.split('-')[3];
      let netHistoryData = { [name]: historyData[key] };
      let legend = [
        { name , icon: 'circle', color: '#345FA6', fetchDateName: 'exeTime', valueVarName: name }
      ];
      content.push(<div key={key} className='history-single-chart'>
        <div className='history-single-chart-title'>
          <label>{capacity}：{name}</label>
        </div>
        <HistoryChartView {...this.setDayHistoryChartViewProps(netHistoryData,legend,unit)} {...this.props} />
      </div>);
    });
    return content;
  }

  //根据条件查询历史数据
  getHistoryData = () => {
    if (this.searchParam.eqpId === undefined) {
      message.danger('请选择要查询的设备');
      return;
    }
    //时间空间赋默认值
    if (this.searchParam.startTimeStr === undefined) {
      let yesterdayDate = new Date();
      yesterdayDate.setTime(yesterdayDate.getTime() - (ONEDAY_HOUR * ONEHOUR_MINUTE * ONEMINUTE_SECOND * ONESECOND_MILL));
      let yesterdayTime = yesterdayDate.format('yyyy-MM-dd hh:mm:ss');
      this.searchParam.startTimeStr = yesterdayTime;
    }
    if (this.searchParam.endTimeStr === undefined) {
      let nowDate = new Date();
      let nowTime = nowDate.format('yyyy-MM-dd hh:mm:ss');
      this.searchParam.endTimeStr = nowTime;
    }
    this.setState({ loading: true });
    AmosFetch.post(OltSerUrl.getHistoryData,{ data: this.searchParam }).then(res => {
      if (res.ok) {
        return res.json();
      }
      else
      {
        this.setState({ loading: false });
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data)=>{
      this.setState({ loading: false });
      if (data.result === 'SUCCESS'){
        this.setState({ historyData: data.dataList === null ? {} : data.dataList });
      }
    });
  }


  //设置设备ID
  setSearchDeviceParam = (eqpId) => {
    let param = this.searchParam;
    if (parseInt(eqpId) === 0) {
      param.eqpId = undefined;
    } else {
      param.eqpId = eqpId;
    }
    this.searchParam = param;
  }

  //设置能力ID
  setSearchCapacityParam = (cpblId) => {
    let param = this.searchParam;
    if (parseInt(cpblId) === 0) {
      param.cpblId = undefined;
    } else {
      param.cpblId = cpblId;
    }
    this.searchParam = param;
  }

  //设置
  setStartTimeParam = (startTimeStr) => {
    let param = this.searchParam;
    param.startTimeStr = startTimeStr;
    this.searchParam = param;
  }

  //设置
  setEndTimeParam = (endTimeStr) => {
    let param = this.searchParam;
    param.endTimeStr = endTimeStr;
    this.searchParam = param;
  }

  //设置
  setEmptyParam = () => {
    let param = this.searchParam;
    param.cpblId = undefined;
    param.eqpId = undefined;
    this.searchParam = param;
    this.setState({ historyData: {} });
  }

  handleDataAnaysisClick = () => {
    window.open(dataAnaysisUrl(), 'dataAnalysis');
  }


  render() {
    let { historyData } = this.state;
    return (
      <div className='history-root' style={{ height: '100%' }}>
        <Spin spinning={this.state.loading} delay={500} >
          <div className='history-select-area'>
            <div className='history-select-title' />
            <QueryPanel
              setSearchDeviceParam={this.setSearchDeviceParam}
              setSearchCapacityParam={this.setSearchCapacityParam}
              setEndTimeParam={this.setEndTimeParam}
              setStartTimeParam={this.setStartTimeParam}
              setEmptyParam={this.setEmptyParam}
              getHistoryData={this.getHistoryData}
            />
            {/* <a
              style={{
                float: 'right',
                fontSize: '16px',
                lineHeight: '50px'
              }}
              onClick={this.handleDataAnaysisClick}
            >
              数据分析
            </a> */}
          </div>
        </Spin>
        <div className='history-chart-area'>
          {Object.keys(historyData).length === 0 ? <img src={require('./../../../assets/tip/empty.png')} style={{ margin: '18% 43%' }} alt="empty" /> : this.getChartContent()}
        </div>
      </div>
    );
  }
}

HistoryPanel.propTypes = {

};

export default HistoryPanel;
