import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { browserHistory } from 'amos-react-router';
import { AmosAlert, Modal, Button } from 'amos-framework';
import AmosGridTable from './../../../common/tableComponent/table/AmosGridTable';
import {
  getMatchesCamerasDataAction,
  deleteBindCamerasAction,
  bindCamerasAction
} from './../../../../../services/bizService';
import EquipCameraAddView from './EquipCameraAddView';
import BizIcon from './../../../../common/icon/BizIcon';

const matchEquipmentTableColumns = self => {
  return [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`
    },
    {
      title: '摄像机编号',
      dataIndex: 'code',
      key: 'code',
      width: '15%'
    },
    {
      title: '摄像机名称',
      dataIndex: 'name',
      key: 'name',
      width: '15%'
    },
    {
      title: '摄像机类型',
      dataIndex: 'type',
      key: 'type',
      width: '10%'
    },
    {
      title: '摄像机IP',
      dataIndex: 'ip',
      key: 'ip',
      width: '10%'
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: '10%'
    },
    {
      title: '密码',
      dataIndex: 'password',
      key: 'password',
      width: '10%'
    },
    {
      title: '端口号',
      dataIndex: 'port',
      key: 'port',
      width: '10%'
    },
    {
      title: '通道',
      dataIndex: 'channel',
      key: 'channel',
      width: '10%'
    }
  ];
};

const defaultHeight = 580;

const monitorHeaderResult = equipment => {
  let equipName;
  let equipTagNum;

  if (equipment) {
    equipName = equipment.name;
    equipTagNum = equipment.code;
    return `${equipTagNum}(${equipName})`;
  } else {
    return '设备位号(设备名称)';
  }
};

/**
 * 设备设施绑定摄像机
 */
class EquipCamera extends Component {
  constructor(props) {
    super(props);

    this.pageConfig = {
      pageNumber: 0,
      pageSize: 10
    },
    this.state = {
      key: 1,
      showQuery: false,
      pagination: false,
      selectedRows: [],
      selectedRowKeys: [],
      dataList: [], //表格数据集合
      size: 'small', //表格大小
      searchParam: [],
      totals: 0, //所有数据总和
      requestParam: [],
      equipmentId: 0,
      pictureMap: new Map(),  //设备相关图片
      enableCarousel: false, //是否打开轮播图页面
      enableAddOp: false  //是否打开绑定装备页面
    };
  }

  componentWillMount() {
    if (this.props.location.state) {
      let { equipment, key } = this.props.location.state;
      this.setState({
        equipmentId: equipment.id,
        equipment,
        key
      });
    }
  }

  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
    });
  }

  getMatchesCamerasData = (param) => {
    let { equipmentId } = this.state;
    getMatchesCamerasDataAction(equipmentId).then(data => {
      this.setState({
        dataList: data,
        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 highlight = this.highlight;
    if (highlight && record.id === highlight) {
      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({
      enableAddOp: true
    });
  }

  clearSelectedRows = () => {
    this.setState({ selectedRows: [], selectedRowKeys: [], enableAddOp: false });
  };

  reloadPage = () => {
    this.clearSelectedRows();
    this.state.reload();
  };

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

  goBack() {
    browserHistory.goBack();
  }

  getBindContext = () => {
    const { equipmentId } = this.state;
    return (<EquipCameraAddView equipmentId={equipmentId} ref={component => this.bindView = component} />);
  }

  changeStatus = (open) => {
    this.setState({ showQuery: open });
  }

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

  filter = (searchParam) => {
    // this.getEquipmentListData(searchParam);
    this.setState({ showQuery: true });
  }

  bind = () => {
    let { selectedRowKeys } = this.bindView.state;
    let { equipmentId } = this.state;
    if (selectedRowKeys.length <= 0 ){
      AmosAlert.warning('提示', '请先选择要绑定的摄像头');
      return;
    }
    bindCamerasAction(equipmentId,selectedRowKeys).then(
      data => {
        AmosAlert.success('提示', '绑定成功');
        this.reloadPage();
      },
      err => {
        AmosAlert.error('错误', err);
      }
    );
  }

  render() {
    let { dataList,selectedRowKeys, enableAddOp, equipment } = this.state;
    let _true_ = true;
    return (
      <div className="fire-station-matches" style={{ background: '#33333', height: '100%' }}>
        <Modal
          className='match-equipment-bind'
          header="添加摄像机"
          width='45%'
          visible={enableAddOp}
          destroyContent
          onCancel={() => this.cancel('bind')}
          content={this.getBindContext()}
          onOk={(e) => this.bind(e)}
          outterClosable={!_true_}
        />
        <div className='match-equipment-toolbar'>
          <div className='match-equipment-toolbar-goback'>
            <Button icon={<BizIcon icon="fanhui" />} transparent onClick={() => this.goBack()}  />
          </div>
          <div className='match-equipment-toolbar-title'>{monitorHeaderResult(equipment)}</div>
          <div className='match-equipment-toolbar-oper'>
            <Button icon={<BizIcon icon="tianjia" />} transparent onClick={() => this.add()}  />
            <Button icon={<BizIcon icon="shanchu" />} transparent onClick={() => this.delete()}  />
          </div>
        </div>
        <div className='match-equipment-content'>
          <div className='match-equipment-table'>
            <div className='match-equipment-item-title'>绑定摄像机</div>
            <AmosGridTable
              rowKey="id"
              columns={matchEquipmentTableColumns(this)}
              callBack={this.reload}
              dataList={dataList}
              isPageable={false}
              getTableDataAction={this.getMatchesCamerasData}
              getSelectedRows={this.getSelectedRows}
              rowClassName={this.getRowClassName}
              setPageConfig={this.setPageConfig}
              getPanelHeight={this.getPanelHeight}
              defaultPageConlHeight={this.getPanelHeight}
              isChecked={_true_}
              selectedRowKeys={selectedRowKeys}
              onRowClick={this.onRowClick}
            />
          </div>
        </div>
      </div>
    );
  }
}

EquipCamera.propTypes = {
  equipment: PropTypes.object
};
export default EquipCamera;
