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

const  timestampToTime = (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;
};

const alarmColumns = (actions) => {
  return [{
    title: '告警级别',
    dataIndex: 'level',
    key: 'level',
    width: '8%',
    query: true,
    required: true,//是否是默认显示的
    primary: true,//是否出现在模糊搜索文本框中
    st: 'list',//搜索的类型
    list: [{ name: '一级',value: 1 },{ name: '二级',value: 2 },{ name: '三级',value: 3 }],//如果 st 的值为列表，则这里需要提供列表内容数组，否则可为 null
    render: (text) => text === 1 ? '一级' :  text === 2 ? '二级' : '三级'
  },{
    title: '告警类型',
    dataIndex: 'type',
    key: 'type',
    width: '8%',
    query: true,
    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',
    query: true,
    required: true,//是否是默认显示的
    primary: true,//是否出现在模糊搜索文本框中
    st: 'text',//搜索的类型
    width: '20%'
  },{
    title: '描述',
    dataIndex: 'descr',
    key: 'descr',
    width: '22%'
  },{
    title: '发生时间',
    dataIndex: 'raiseTime',
    key: 'raiseTime',
    width: '12%',
    render: (text) => timestampToTime(text)
  },{
    title: '清除时间',
    dataIndex: 'clearTime',
    key: 'clearTime',
    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.oneClearAlarm(record.id)} />
        <label className='delete-alarm-label' onClick={()=>actions.oneClearAlarm(record.id)} >删除</label>
      </span>
    )
  }];
};
const headHeight = 278;//表格上部分内容高度

//偏移110px
const offsetHeight = 160;
const defaultHeight = 450;
/**
 *
 *
 * @class HistoryAlarmTable
 * @extends {Component}
 */
class HistoryAlarmTable extends Component {
  constructor(props) {
    super(props);
    this.filter = {
      current: 0,
      pageSize: 10
    };
    this.state = {
      dataList: [],
      selectedRows: [],
      selectedRowKeys: [],
      total: 1,
      reload(){},
      maxHeight: 450,
      searchCondition: {}
    };
  }

  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) => {
  }

  oneClearAlarm = (id) => {
    Modal.confirm({
      content: '确定删除吗？',
      onCancel: () => {},
      onOk: () => {
        this.clearAlarm([id]);
      }
    });
  }

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

  /**
   * 添加表格操作按钮
   */
  addButtons = () => {
    let btns = [];
    btns.push(<Button type='primary' onClick={() => this.batchClearAlarm()} >批量删除</Button>);
    return btns;
  }

  alarmDetail= (alarmId) => {

  }

  clearAlarm= (alarmIds) => {
    let param = {
      alarmIds,
      status: 3
    };
    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) => {
    if (filter){
      this.filter = filter;
    } else {
      filter = this.filter || {};
    }
    if (searchCondition){
      if('{}' === searchCondition){
        if(this.searchCondition){
          searchCondition = this.searchCondition;
        }
      }else{
        this.searchCondition = searchCondition;
      }
    } else {
      searchCondition = this.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 });
    }
    list.push({ name: 'status',type: 'EQUAL',value: 2 });
    list.push({ name: 'clearTime',type: 'ORDER BY',value: 'DESC' });
    // searchCondition.push(param);
    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)=>{
      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 = () => {
    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(ids);
      }
    });
  }

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

  refreshData = (filter,searchCondition) => {
    //let filter = this.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 } = this.state;
    const actions = { alarmDetail: this.alarmDetail,oneClearAlarm: this.oneClearAlarm };
    return (
      <div className="history-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>
    );
  }
}

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

export default HistoryAlarmTable;
