import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button,Modal } from 'amos-antd';
import { utils } from 'amos-tool';
import { AmosFetch } from 'UTILS/processor';
import OltSerUrl from 'CONSTS/urlConsts';
import dt2react from 'dt2react';
import AmosGridTable from './../../common/tableComponent/table/AmosGridTable';
import SingleClearAlarm from './SingleClearAlarm';
import AlarmDetail from './AlarmDetail';
import './../alarm.scss';

const  timestampToTime = (timestamp) => {
  if (null !== timestamp) {
    let date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = `${date.getFullYear()}-`;
    let M = `${date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1}-`;
    let D = `${date.getDate()} `;
    let h = `${date.getHours()}:`;
    let m = `${date.getMinutes()}:`;
    let s = date.getSeconds();
    return Y + M + D + h + m + s;
  } else {
    return "";
  }
};

const alarmColumns = (actions) => {
  return [{
    title: '告警级别',
    dataIndex: 'level',
    key: 'level',
    width: '8%',
    query: false,
    required: true,//是否是默认显示的
    primary: true,//是否出现在模糊搜索文本框中
    st: 'list',//搜索的类型
    list: [{ name: '一级',value: '1' },{ name: '二级',value: '2' },{ name: '三级',value: '3' }],//如果 st 的值为列表，则这里需要提供列表内容数组，否则可为 null
    defaultValue: actions.level,
    render: (text) => text === 1 ? '一级' :  text === 2 ? '二级' : '三级'
  },{
    title: '告警类型',
    dataIndex: 'type',
    key: 'type',
    width: '8%',
    query: false,
    required: true,//是否是默认显示的
    primary: true,//是否出现在模糊搜索文本框中
    st: 'list',//搜索的类型
    list: [{ name: '指标越界',value: 1 },{ name: '采集异常',value: 2 },{ name: '设备掉线',value: 3 }],
    render: (text) => text === 1 ? '指标越界' :  text === 2 ? '采集异常' : '设备掉线'
  },{
    title: '告警源',
    dataIndex: 'name',
    key: 'name',
    width: '20%',
    query: false,
    required: true,//是否是默认显示的
    primary: true,//是否出现在模糊搜索文本框中
    st: 'text',//搜索的类型
    defaultValue: actions.eqpName
  },{
    title: '描述',
    dataIndex: 'descr',
    key: 'descr',
    width: '22%'
  },{
    title: '发生时间',
    dataIndex: 'raiseTime',
    key: 'raiseTime',
    width: '12%',
    render: (text) => timestampToTime(text)
  },{
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    width: '12%',
    render: (text) => timestampToTime(text)
  },{
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: '6%',
    render: (text) => text === 1 ? '未处理' :  text === 2 ? '历史告警' : '已删除'
  }, {
    title: '操作',
    key: 'action',
    width: '10%',
    render: (text, record) => (
      <span>
        <AlarmDetail alarmInfo={record} clearAlarm={actions.clearAlarm} />
        <SingleClearAlarm title='清除' alarmId={record.id}  clearAlarm={actions.clearAlarm} />
      </span>
    )
  }];
};
const headHeight = 278;//表格上部分内容高度

//偏移110px
const offsetHeight = 160;
const defaultHeight = 450;
/**
 *
 *
 * @class RecentAlarmTable
 * @extends {Component}
 */
class RecentAlarmTable extends Component {
  constructor(props) {
    super(props);
    let equipmentId = '';
    let level = '';
    if (this.props.equipmentId){
      equipmentId = this.props.equipmentId;
    }
    if (this.props.level){
      level = this.props.level;
    }
    this.filter = {
      current: 0,
      pageSize: 10
    };
    this.state = {
      dataList: [],
      selectedRows: [],
      selectedRowKeys: [],
      equipmentId,
      level,
      eqpName: '',
      total: 1,
      reload(){},
      maxHeight: 450,
      searchCondition: {}
    };
  }
  componentWillMount(){
    let equipmentId = this.props.equipmentId;
    if (equipmentId){
      let url = `${OltSerUrl.findEquipmentById}/${equipmentId}`;
      //获取接口通讯方式
      AmosFetch.get(url).then(res => {
        if (res.ok) {
          return res.json();
        }
        else
        {
          throw new Error('从服务端获取数据失败！');
        }
      }).then((data)=>{
        if (data.result === 'SUCCESS'){
          this.setState({ eqpName: data.dataList.name });
        }
      });
    }
  }

  componentDidMount(){
    window.addEventListener('resize', this.onWindowResize);
    this.props.updateStatus();
  }

  componentWillReceiveProps(nextProps) {
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.onWindowResize);
  }

  onChange = ({ nodes, connections }) => {
    this.setState({ nodes, connections });
  }

  onWindowResize = (e) => {

  }

  /**
   * 获取表格所选则的行数据
   */
  getSelectedRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  }

  getSelectedRowKeys = () => {
    return this.state.selectedRowKeys;
  }

  alarmDetail= (alarmId) => {

  }

  clearAlarm= (remark,alarmIds) => {
    let param = {
      alarmIds,
      status: 2,
      remark
    };
    AmosFetch.post(OltSerUrl.deleteAlarm,{ data: param }).then(res => {
      if (res.ok) {
        return res.json();
      } else
      {
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data)=>{
      if (data.result === 'SUCCESS'){
        this.refreshData(this.filter);
        const modal = Modal.warning({
          title: '系统提示',
          content: '清除成功！',
          okText: '确定'
        });
        setTimeout(() => modal.destroy(), 2000);
      } else {
        const modal = Modal.warning({
          title: '系统提示',
          content: '清除失败！',
          okText: '确定'
        });
        setTimeout(() => modal.destroy(), 2000);
      }
    });
  }

  fetchCurrentAlarm = (filter = {}, searchCondition = {}) => {
    // searchCondition = JSON.parse(searchCondition);
    let list = [];
    if (searchCondition.level && searchCondition.level !== '-1'){
      list.push({ name: 'level',type: 'EQUAL',value: searchCondition.level });
    }
    if (searchCondition.type && searchCondition.type !== '-1'){
      list.push({ name: 'type',type: 'EQUAL',value: searchCondition.type });
    }
    if (searchCondition.name){
      list.push({ name: 'name',type: 'LIKE',value: searchCondition.name });
    }
    // if (searchCondition.raiseTime){
    //   // let raiseTime = searchCondition.raiseTime.format('yyyy-MM-dd HH:mm:ss');
    //   console.log(searchCondition.raiseTime);
    //   list.push({ name: 'raiseTime',type: 'EQUAL',value: searchCondition.raiseTime });
    // }
    let equipmentId = this.state.equipmentId;
    if (equipmentId !== ''){
      list.push({ name: 'eqpId',type: 'EQUAL',value: equipmentId });
    }
    let level = this.state.level;
    if (level !== ''){
      list.push({ name: 'level',type: 'EQUAL',value: level });
    }
    list.push({ name: 'status',type: 'EQUAL',value: 1 });
    list.push({ name: 'raiseTime',type: 'ORDER BY',value: 'DESC' });
    let url = `${OltSerUrl.getHistoryAlarm}?pageNumber=${filter.current}&pageSize=${filter.pageSize}`;
    AmosFetch.post(url,{ data: list }).then(res => {
      if (res.ok) {
        return res.json();
      } else
      {
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data)=>{
      this.setState({ equipmentId: '' });
      let myDate = new Date();
      let hours = myDate.getHours();
      let minutes = myDate.getMinutes();
      if (minutes < 10){
        minutes = `0${minutes}`;
      }
      let refreshTime = `${hours}时${minutes}分`;
      if (data.result === 'SUCCESS'){
        let total = data.dataList.totalElements;
        if (data.content !== null){
          this.setState({ dataList: data.dataList.content,refreshTime,total,filter });
        }
      } else {
        this.setState({ dataList: [],refreshTime,total: 0,filter });
      }
    });
  }


  batchClearAlarm = (remark,ids) => {
    // let ids = this.state.selectedRowKeys;
    if (ids.length === 0){
      const modal = Modal.warning({
        title: '系统提示',
        content: '请选择数据！',
        okText: '确定'
      });
      setTimeout(() => modal.destroy(), 2000);
      return;
    }
    Modal.confirm({
      content: '确定清除吗？',
      onCancel: () => {},
      onOk: () => {
        let ids = this.state.selectedRowKeys;
        this.clearAlarm(remark,ids);
      }
    });
  }

  /**
   * 获取表格刷新方法
   */
  reload = (r) => {
    this.setState({ reload: ()=>{r();this.setState({ selectedRows: [],selectedRowKeys: [] });} },r());
  }

  refreshData = (filter,searchCondition) => {
    this.filter = filter;
    this.fetchCurrentAlarm(filter, searchCondition);
  }

  getRefreshTime = () => {
    let { refreshTime } = this.state;
    if (refreshTime) {
      return this.state.refreshTime;
    } else {
      let myDate = new Date();
      let hours = myDate.getHours();
      let minutes = myDate.getMinutes();
      if (minutes < 10){
        minutes = `0${minutes}`;
      }
      let refreshTime = `${hours}时${minutes}分`;
      return refreshTime;
    }
  }

  refreshTime = () => {
    this.refreshData(this.filter);
  }

  getPanelHeight = () => {
    let alarmTablePanel = this.alarmRoot;
    let tableLocation = dt2react.getOffset(alarmTablePanel) || {};
    return tableLocation !== undefined ? tableLocation.height - offsetHeight : defaultHeight;
  }

  render() {
    let { dataList,total,refreshTime,maxHeight,eqpName,level } = this.state;

    const actions = { alarmDetail: this.alarmDetail,clearAlarm: this.clearAlarm,eqpName,level };
    return (
      <div className="curent-alarm-root" ref={node => this.alarmRoot = node}>
        {/*<div className='rule-view-header'>
          <div className='rule-view-header-title'>
            <span>当前告警最新刷新时刻：{refreshTime}</span>
            <Button type='primary' onClick={this.refreshData} >数据刷新</Button>
          </div>
    </div>*/}
        <div className='recent-alarm-table'>
          <AmosGridTable
            columns={alarmColumns(actions)}
            callBack={this.reload}
            dataList={dataList}
            totals={total}
            getTableDataAction={this.fetchCurrentAlarm}
            getSelectedRows={this.getSelectedRows}
            maxHeight={maxHeight}
            getPanelHeight={this.getPanelHeight}
          />
        </div>
      </div>
    );
  }
}

RecentAlarmTable.propTypes = {
  updateStatus: PropTypes.func
};

export default RecentAlarmTable;
