import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Connect, Modal, AmosAlert } from 'amos-framework';
import AmosWebSocket from 'amos-websocket';
import * as endConf from 'amos-processor/lib/config/endconf';
import PilotController from 'amos-viz/lib/board/PilotController';
import SysWsURL, { completeToken } from 'CONSTS/wsUrlConsts';
// import AmosGridTable from './../../../bizview/common/tableComponent/table/AmosGridTable';
import { Table } from 'amos-antd';
import BottomTable from './rightChartChild/bottomTable';
import moment from 'moment';
import { BarCharts } from 'amos-core';
import { setPieOption,setLineOption } from './chartData';
import ReactEcharts from 'amos-viz/lib/echarts';
import { getLeftMetricDataAction, getLeftDangerDataAction } from './../../../../services/2dService';
import { browserHistory } from 'amos-react-router';
import { utils } from 'amos-tool';


// import Three3dView from './View3D';
// import { eventTopics } from './consts';
// import IndexChart from './indexChart';
const chartStyle = {
  width: '100%', height: '100%'
};
const chartDatas = {
  dangerNums:{
    total: 0,
    data: [
      {
        name:'一级风险',
        value:'0/0'
      },{
        name:'二级风险',
        value:'0/0'
      },{
        name:'三级风险',
        value:'0/0'
      },{
        name:'四级风险',
        value:'0/0'
      }
    ]
  },
  alarmNums:{
    total: 223,
    data: [
      {
        name:'紧急',
        value:'0/0'
      },{
        name:'重要',
        value:'0/0'
      },{
        name:'次要',
        value:'0/0'
      },{
        name:'警告',
        value:'0/0'
      }
    ]
  },
  equipmentData:[
    {
      name: '网络设备',
      num: 0,
      unit: '个',
      damageNum: 0,
      damageRate: '0%'
    },{
      name: '服务器',
      num: 0,
      unit: '个',
      damageNum: 0,
      damageRate: '0%'
    },{
      name: 'NPC节点',
      num: 0,
      unit: '个',
      damageNum: 0,
      damageRate: '0%'
    }
  ],
  rangeData:[
    {
      name:'中心机房',
      data:[
        {
          name: '供配电',
          normalNum: 11,
          damageNum: 4
        },
        {
          name: 'UPS',
          normalNum: 15,
          damageNum: 6
        },{
          name: '精密空调',
          normalNum: 21,
          damageNum: 5
        },{
          name: '其他',
          normalNum: 19,
          damageNum: 8
        }
      ]
    },{
      name:'通信转接机房',
      data:[
        {
          name: '供配电',
          normalNum: 13,
          damageNum: 4
        },
        {
          name: 'UPS',
          normalNum: 17,
          damageNum: 5
        },{
          name: '精密空调',
          normalNum: 15,
          damageNum: 7
        },{
          name: '其他',
          normalNum: 19,
          damageNum: 8
        }
      ]
    }
  ]
}
const eventConnect = Connect.eventConnect;
const AmosConfig = endConf.AmosConfig;
const enableScreenSaver = AmosConfig.screenSaverConf.enable;
const delayTime = AmosConfig.screenSaverConf.delayTime;


@eventConnect
class LeftCharts extends Component {
  constructor(props) {
    super(props);

    this.state = {
      currentCode: this.props.currentCode || '1*2',
      dangerNumData: [],
      gjdate:[],
      gjznum:0,
      equipmentData: [],
      dangerAllNum: [0,0]
    };

  }

  componentDidMount() {
    // getLeftMetricDataAction({code:this.state.currentCode}).then(data => {
    //   console.log('hhhhh',data);
    //   this.setState({
    //     dangerNumData: data
    //   });
    // });
    this.initData();
  }



  handleData = (data) => {
    console.log(data);

    this.initData();
}

  componentWillReceiveProps = nextProps => {
    if (nextProps.currentCode && this.state.currentCode !== nextProps.currentCode) {
      const { currentCode } = nextProps || {};
      this.state.currentCode = currentCode;
      this.setState({ currentCode });
      this.initData();
    }
  };
  initData = () => {

    getLeftMetricDataAction({ code: this.state.currentCode }).then(data => {
      //console.log('hhhhh',data);

      let dataList = data.data || [];
      let num=0;
      dataList.forEach(v=>{
        num=num+Number(v.value.split('/')[1]);
      });
      this.state.dangerAllNum[0] = num || 0;
      this.props.dotTipNumChange(this.state.dangerAllNum[0]+this.state.dangerAllNum[1]);
      this.setState({
        dangerNumData: data,
        dangerAllNum: this.state.dangerAllNum
      });
      if (data.result === 'FAILURE' && data.message) { AmosAlert.error('警告', data.message);}
    });

    let  dates = {
      collectionName: 'alarm',
      conditions: [
        {
          name: 'orgCode',
          queryType: 'is',
          value: this.state.currentCode
        }
      ],
      groupBy: 'alarmLevel',
      statisticType: 'count'
    };

    getLeftDangerDataAction({ code: this.state.currentCode }).then(data => {


      if (data&&data.length>0){
        let num=0;
        data.forEach(v=>{
          num=num+v.value;
        });
        this.state.dangerAllNum[1] = num || 0;
        this.props.dotTipNumChange(this.state.dangerAllNum[0]+this.state.dangerAllNum[1]);
        this.setState({
          gjznum: num,
          dangerAllNum: this.state.dangerAllNum
        });
      }

      this.setState({
        gjdate: data
      });
    });
    // 设备图
    // getLeftMetricDataAction2(this.state.currentCode).then(data => {
    //   // console.log('llllll',data);
    //   this.setState({
    //     equipmentData: data
    //   });
    // });
  }


  gofx(){

    browserHistory.push('/biz/riskModel');
  }







  componentWillUnmount() {

  }
  renderDangerNum = () => {
    let { dangerNumData } = this.state;
     return (dangerNumData.data || chartDatas.dangerNums.data || []).map((item,index) => {
      return (
        <div className='item' key={index} onClick={ () => {this.gofx()} }>
          <div className='itemContent'   >
            <span className='itemValue'>{item.value}</span>
            <span className='itemLable'>{item.name}</span>
          </div>

        </div>
      )
    })
  }
  renderAlarmNum = () => {
    // let alarmNumData = chartDatas.alarmNums.data || [];
    // return alarmNumData.map(item => {
    //   return (
    //     <div className='item'>
    //       <span className='itemValue'>{item.value}</span>
    //       <span className='itemLable'>{item.name}</span>
    //     </div>
    //   )
    // })
    let { gjdate } = this.state;
    // gjdate = gjdate.filter( e => { return e._id != null })

    if(!utils.isEmpty(gjdate) && utils.isArray(gjdate)){
      return (gjdate||[]).map((item, index) => {
        return (
          <div className='item' key={index}>
            <div className='itemContent'>
              <span className='itemValue'>{item.value}</span>
              <span className='itemLable'>{item.name}</span>
            </div>

          </div>
        )
      })
    }else{
      let alarmNumData = chartDatas.alarmNums.data || [];
      return alarmNumData.map((item,index) => {
        return (
          <div className='item' key={index}>
            <div className='itemContent'>
              <span className='itemValue'>{item.value}</span>
              <span className='itemLable'>{item.name}</span>
            </div>

          </div>
        )
      })
    }
  }
  renderEquipmentData = () => {
    let { equipmentData } = this.state;
    if (equipmentData.length < 3) {
      equipmentData = chartDatas.equipmentData;
    }
    // let equipmentData = chartDatas.equipmentData || [];
    return (equipmentData || []).map((item, index) => {
      return (
        <div className='item' key={index}>
          <div className='chartBox'>
            <BarCharts barOps={setPieOption(item)} />
          </div>
          <div className='chartDesc'>

            <span className='itemName'>
              {
                item.name === '网络设备'?
                  <span className='itemIcon' style={{ background: 'url("/src/assets/indexChart/net.png") no-repeat center center/100% 100%' }}></span>:
                  item.name === '服务器'?
                  <span className='itemIcon' style={{ background: 'url("/src/assets/indexChart/service.png") no-repeat center center/100% 100%' }}></span>:
                  item.name === 'NPC节点'?
                  <span className='itemIcon' style={{ background: 'url("/src/assets/indexChart/NPC.png") no-repeat center center/100% 100%' }}></span>:''
              }
              {item.templateAlias || item.name}
            </span>
            {
              item.alarmTotal&&item.alarmTotal!=0?<span className='itemValue'>{`${Math.round(((item.alarmTotal / item.total)*100))}%   ${item.alarmTotal || 0}个`}</span>:
              <span className='itemValue'>{`0%   0个`}</span>
            }

          </div>
        </div>
      )
    })
  }
  renderRangeData = () => {
    let rangeData = chartDatas.rangeData || [];

    return rangeData.map((item, index) => {
      return (
        <div className='item' key={index}>
          <div className='chartDesc'>
            <span className='itemName'>{item.name}</span>
          </div>
          <div className='chartBox'>
            {/*<LineCharts barOps={setLineOption(item)} chartStyle={chartStyle} />*/}
            <ReactEcharts  option={setLineOption(item)} style={chartStyle} className="react_for_echarts" />
          </div>
        </div>
      )
    })
  }
  renderWorkList = () => {
    // let workMsg = chartDatas.workMsg || [];

  }
  reload = r => {
    this.setState(
      {
        reload: () => {
          r();
          this.setState({ selectedRows: [], selectedRowKeys: [] });
        }
      },
      r()
    );
  };


  render() {
    let now = moment().locale('zh-cn').format('YYYY-MM-DD');
    const { dangerNumData,gjdate,gjznum } = this.state;
    const wsURL = completeToken(SysWsURL.view3dws);
    return (
      <div className="chart-content">
         <AmosWebSocket ref={node => this.aws = node} url={wsURL} onMessage={this.handleData} reconnect  />

        <div className='dangerNums'>
          <div className='tieleBox'>
            <div className='title'>
              <span className='titleLeft'>
                <span className='titleIcon' style={{ background: 'url("/src/assets/indexChart/point.png") no-repeat center center/100% 100%' }}></span>
              风险总数</span>
              <span className='titleRight'>{dangerNumData.total || 0}</span>
            </div>
          </div>
          <div className='chartBody'>
            {this.renderDangerNum()}
          </div>
        </div>
        <div className='alarmNums'>
          <div className='tieleBox'>
            <div className='title'>
              <span className='titleLeft'>
                <span className='titleIcon' style={{ background: 'url("/src/assets/indexChart/point.png") no-repeat center center/100% 100%' }}></span>
              告警统计</span>
              <span className='titleRight'>{gjznum|| 0}</span>
            </div>
          </div>
          <div className='chartBody'>
            {this.renderAlarmNum()}
          </div>
        </div>
        {/**<div className='equipmentdata'>
          <div className='tieleBox'>
            <div className='title'>
              <span className='titleLeft'>
                <span className='titleIcon' style={{ background: 'url("/src/assets/indexChart/point.png") no-repeat center center/100% 100%' }}></span>
              设备</span>
            </div>
          </div>
          <div className='chartBody'>
            {this.renderEquipmentData()}
          </div>
        </div>
        <div className='rangeData'>
          <div className='tieleBox'>
            <div className='title'>
              <span className='titleLeft'>
                <span className='titleIcon' style={{ background: 'url("/src/assets/indexChart/point.png") no-repeat center center/100% 100%' }}></span>
              动环数据</span>
            </div>
          </div>
          <div className='chartBody'>
            {this.renderRangeData()}
          </div>
    </div>*/}
          <div className='business'>
            <div className='title'>
              <span className='titleLeft'>
              <span className='titleIcon' style={{ background: 'url("/src/assets/indexChart/point.png") no-repeat center center/100% 100%' }}></span>
                支付业务累计数据</span>
              <span className='titleRight'>{ now }</span>
            </div>
            <div className='chartBody'>
              <BottomTable />
            </div>
          </div>
      </div>
    );
  }
}

LeftCharts.propTypes = {
  subscribe: PropTypes.func,
  trigger: PropTypes.func
};

export default LeftCharts;
