import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Input, AmosAlert, Modal, Button } from 'amos-framework';
import AmosGridTable from './../../common/tableComponent/table/AmosGridTable';
import { getFireEquipmentListAction, deleteFireEquipmentAction, addFireEquipmentAction } from './../../../../services/ledgerService';
import MonitorModel from './MonitorModel';
import BizIcon from './../../../common/icon/BizIcon';


const monitorTableColumns = self => {
  return [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`
    },
    {
      title: '编号',
      dataIndex: 'code',
      key: 'code',
      width: '10%'
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: '20%'
    },
    {
      title: '构/建筑物',
      dataIndex: 'production_area',
      key: 'production_area',
      width: '20%'
    },
    {
      title: '楼层',
      dataIndex: 'floor3d',
      key: 'floor3d',
      width: '10%'
    },
    {
      title: '房间',
      dataIndex: 'room',
      key: 'room',
      width: '10%'
    },
    {
      title: '厂商',
      dataIndex: 'manufacturer',
      key: 'manufacturer',
      width: '20%'
    }
  ];
};

const defaultHeight = 580;

/**
 * 重点设备
 */
class Monitor extends Component {
  constructor(props) {
    super(props);

    this.pageConfig = {
      pageNumber: 0,
      pageSize: 10
    },
    this.state = {
      name: '',
      code: '',
      pagination: true,
      selectedRows: [],
      selectedRowKeys: [],
      dataList: [], //表格数据集合
      size: 'small', //表格大小
      searchParam: [], //分类为2表示为视频监控
      totals: 1, //所有数据总和
      requestParam: [],
      enableEditOp: false,   //是否打开维护页面
      fireEquipmentId: 0  //视频设备ID
    };
  }

  onChange(type, value) {
    let { searchParam } = this.state;
    if (type === 'code') {
      this.setState({ code: value });
      searchParam.code = value;
    } else {
      this.setState({ name: value });
      searchParam.name = value;
    }
    this.getFireEquipmentListData(searchParam);
  }

  onRowClick = record => {
    let { selectedRowKeys, selectedRows } = this.state;
    let exist = false;
    selectedRows.find(item => {
      if (item.id === record.id) {
        exist = true;
      }
    });
    if (exist) {
      selectedRows.splice(selectedRows.findIndex(item => item.id === record.id), 1);
      selectedRowKeys.splice(selectedRowKeys.findIndex(item => item === record.id), 1);
    } else {
      selectedRows.push(record);
      selectedRowKeys.push(record.id);
    }
    this.setState({
      selectedRows,
      selectedRowKeys
    });
  }

  getFireEquipmentListData = (param) => {
    let { searchParam } = this.state;
    if (param.current != null) {
      //前端的current 即后端的pageNumber
      param.pageNumber = param.current;
    }
    Object.assign(searchParam, { ...param });
    searchParam.equipClassify = 2;
    getFireEquipmentListAction(searchParam, searchParam.pageNumber, searchParam.pageSize).then(data => {
      this.setState({
        dataList: data.content,
        totalCount: data.totalElements,
        selectedRowKeys: [],
        selectedRows: []
      });
    });
  };

  getPanelHeight = () => {
    return defaultHeight;
  };

  setPageConfig = ({ pageSize, current }) => {
    if (pageSize !== undefined) {
      this.pageConfig.pageSize = pageSize;
    }
    if (current !== undefined) {
      this.pageConfig.current = current;
    }
  };

  getRowClassName = (record, index) => {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys.findIndex(item => item === record.id) >= 0) {
      return 'highlight-row';
    } else {
      return 'normal-row';
    }
  };

  getSelectedRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

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

  add() {
    this.setState({
      enableEditOp: true,
      operateFlag: 0
    });
  }

  edit() {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请先选择需要编辑的设备');
      return;
    }

    let equipId = selectedRowKeys;
    if (selectedRowKeys.length > 1) {
      equipId = selectedRowKeys[selectedRowKeys.length - 1];
    }

    this.setState({
      enableEditOp: true,
      operateFlag: 1,
      fireEquipmentId: equipId
    });
  }

  delete() {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请先选择需要删除的设备');
      return;
    }
    AmosAlert.confirm('提示', '确定删除指定设备?', {
      callback: flag => {
        if (flag) {
          // 确定删除
          let ids = selectedRowKeys.join(',');
          deleteFireEquipmentAction(ids).then(
            data => {
              AmosAlert.success('提示', '删除成功');
              this.state.reload();
            },
            err => {
              AmosAlert.error('错误', err);
            }
          );
        }
      }
    });
  }

  cancel = (key) => {
    const { enableEditOp } = this.state;
    if (enableEditOp && 'add' === key) {
      this.setState({ enableEditOp: false });
    }
  }

  getFireEquipmentFormContext = () => {
    const { fireEquipmentId, operateFlag } = this.state;
    return (<MonitorModel fireEquipmentId={fireEquipmentId} operateFlag={operateFlag} ref={component => this.model = component} />);
  }

  submit = (e) => {
    let { form } = this.model;
    form.validate((valid, dataValues) => {
      if (valid) {
        console.log(this.model.state.form.id);
        let fireEquipment = dataValues;
        addFireEquipmentAction(fireEquipment).then(
          data => {
            AmosAlert.success('提示', '保存成功');
            this.state.reload();
          },
          error => {
            AmosAlert.error('错误', '保存失败');
          }
        );
        this.setState({
          enableEditOp: false
        });
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  }

  render() {
    let { name, code, dataList, totalCount, selectedRowKeys, enableEditOp } = this.state;
    let _true_ = true;
    return (
      <div className="monitor-video" style={{ background: '#33333', height: '100%' }}>
        <div className="important-equipment-toolbar">
          <div className='important-equipment-title'>
            <span>视频监控</span>
          </div>
          <div className='important-equipment-tools'>
            <span>编号：</span>
            <Input value={code} onChange={e => this.onChange('code', e.target.value)} />
            <span>名称：</span>
            <Input value={name} onChange={e => this.onChange('name', e.target.value)} />
            <Button icon={<BizIcon icon="tianjia" />} transparent onClick={() => this.add()} />
            <Button icon={<BizIcon icon="xiugai" />} transparent onClick={() => this.edit()} />
            <Button icon={<BizIcon icon="shanchu" />} transparent onClick={() => this.delete()} />
          </div>
        </div>
        <Modal
          className='match-equipment-bind'
          header="添加视频监控"
          width='50%'
          visible={enableEditOp}
          destroyContent
          onCancel={() => this.cancel('add')}
          content={this.getFireEquipmentFormContext()}
          onOk={(e) => this.submit(e)}
          outterClosable={!_true_}
        />
        <AmosGridTable
          rowKey="id"
          columns={monitorTableColumns(this)}
          callBack={this.reload}
          dataList={dataList}
          totals={totalCount}
          getTableDataAction={this.getFireEquipmentListData}
          getSelectedRows={this.getSelectedRows}
          rowClassName={this.getRowClassName}
          setPageConfig={this.setPageConfig}
          getPanelHeight={this.getPanelHeight}
          defaultPageConlHeight={this.getPanelHeight}
          isChecked={_true_}
          selectedRowKeys={selectedRowKeys}
          onRowClick={this.onRowClick}
        />
      </div>
    );
  }
}

Monitor.propTypes = {
};
export default Monitor;
