import React, { Component } from 'react';
import { Button,Modal } from 'amos-antd';
import { Switch,message } from 'amos-framework';
import { AmosFetch } from '../../utils/processor';
import OltSerUrl from '../../consts/urlConsts';
import AmosGridTable from './common/table/AmosGridTable';
import AddRule from './addRule';
import EditRule from './editRule';
import MonitorObjList from './monitorObjList';
import './../common/style/commonTabs.scss';
import './../common/style/commonStyle.scss';
import './common/index.scss';


const monitorColumns = (param) => {
  return [{
    title: '任务名称',
    dataIndex: 'name',
    key: 'name',
    width: '20%'
  }, {
    title: '对象数量',
    dataIndex: 'objNum',
    key: 'objNum',
    width: '10%',
    render: (text,record) => (
      <span>
        <MonitorObjList text={text} monitorRuleInfo={record} />
      </span>
    )
  }, {
    title: '任务类型',
    dataIndex: 'monitorType',
    key: 'monitorType',
    width: '10%',
    render: (text,record) => text === 1 ? '采集' : '监听'
  }, {
    title: '采集周期（秒/次）',
    dataIndex: 'period',
    key: 'period',
    width: '20%',
    render: (text) => text === 0 ? '--' : text
  }, {
    title: '最后修改时间',
    dataIndex: 'updateTime',
    key: 'startTime',
    width: '20%'
  }, {
    title: '操作',
    key: 'action',
    width: '20%',
    render: (text, record) => (
      <span>
        <EditRule reload={param.reload} text='编辑' monitorRuleInfo={record} />
        <Button size='small' style={{ marginLeft: '10px' }} onClick={()=>param.delConfirm(record.id)} >删除</Button>
        <Switch onLabel='启' offLabel='停' onOff={record.isEnabled} style={{ marginLeft: '10px' }} onChange={(checked)=>param.oneOpenOrClose(checked,record.id)} />
      </span>
    )
  }];
};
/**
 * 设备接口
 */
class RuleMgmt extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataList: [],
      selectedRows: [],
      selectedRowKeys: [],
      total: 0,
      reload(){}
    };
  }

  componentWillMount(){
  }

  onRefresh = () => {
    let filter = {
      current: 0,
      pageSize: 10
    };
    this.selectDataList(filter);
  }

  //单个任务启用或者关闭
  oneOpenOrClose =(statusFlag,id) =>{
    let ruleIds = [];
    ruleIds.push(id);

    let param = {
      ruleIds,
      statusFlag
    };
    this.openOrClose(param);
  }

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

  //批量任务启用或者关闭
  batchOpenOrClose = (statusFlag) =>{
    let ruleIds = this.state.selectedRowKeys;
    let param = {
      ruleIds,
      statusFlag
    };
    this.openOrClose(param);
  }

  /**
   * 添加表格操作按钮
   */
  addButtons = () => {
    let btns = [];
    let { reload } = this.state;
    btns.push(<AddRule reload={reload} text='新增' {...this.props} />);
    btns.push(<Button type='primary' style={{ float: 'left',marginLeft: '10px' }} onClick={() => this.batchOpenOrClose(true)} >批量启用</Button>);
    btns.push(<Button type='primary' style={{ marginLeft: '10px' }} onClick={()=>this.batchOpenOrClose(false)} >批量停用</Button>);
    return btns;
  }

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

  //查询列表数据
  selectDataList = (filter) =>{
    if (!filter){
      filter = this.state.filter;
    }
    let url = `${OltSerUrl.monitorRuleDataList}?pageNumber=${filter.current}&pageSize=${filter.pageSize}`;
    // 获取接口通讯方式
    AmosFetch.post(url).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.state === 'SUCCESS'){
        let total = data.totalElements;
        if (data.content !== null){
          this.setState({ dataList: data.content,refreshTime,total,filter });
        }
      } else {
        this.setState({ dataList: [],refreshTime,total: 0,filter });
      }
    });
  }

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

    });
  }

  delMonitorRule = (id) =>{
    let url = `${OltSerUrl.monitorRuleDel}/${id}`;
    AmosFetch.del(url).then(res => {
      if (res.ok) {
        return res.json();
      }
      else
      {
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data)=>{
      if (data.result === 'SUCCESS'){
        this.selectDataList();
        message.success('删除成功！');
      } else {
        message.danger('删除失败！');
      }

    });
  }

  //启用或者关闭
  openOrClose = (param) =>{
    let url = OltSerUrl.monitorIsenable;
    AmosFetch.post(url,{ data: param }).then(res => {
      if (res.ok) {
        return res.json();
      } else {
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data)=>{
      this.selectDataList();
    });
  }

  render() {
    let { dataList,refreshTime,total,reload } = this.state;
    let param = {
      delConfirm: this.delConfirm,
      oneOpenOrClose: this.oneOpenOrClose,
      reload
    };
    return (
      <div className='rule-view-content giot-content-card'>
        <div className='rule-view-header'>
          <div className='rule-view-header-title'>
            <span>最新刷新时刻：{refreshTime}</span>
            <Button type='primary' onClick={this.onRefresh} style={{ marginLeft: '30px' }} >数据刷新</Button>
          </div>
        </div>
        <div className='rule-view-body'>
          <div style={{ marginTop: '10px' }} >
            <AmosGridTable
              columns={monitorColumns(param)}
              callBack={this.reload}
              dataList={dataList}
              totals={total}
              getTableDataAction={this.selectDataList}
              operBtns={this.addButtons()}
              getSelectedRows={this.getSelectedRows}
            />
          </div>

        </div>
      </div>
    );
  }
}

RuleMgmt.propTypes = {
};

export default RuleMgmt;
