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 {
  getMatchesFireEquipmentListAction,
  deleteFireStationMatchesAction,
  bindFireStationMatchesAction
} from './../../../../../services/ledgerService';
import FireStationMatchesAddView from './FireStationMatchesAddView';
import BizIcon from './../../../../common/icon/BizIcon';
import { pathMapping } from './../../../../../routes/customRoutes';

const EquipClassifyEnum = { 0: '设备类', 1: '耗材类', 2: '视频监控', 3: '灭火器材' };
// const stationMatchesPath = pathMapping.stationMatches;

const matchEquipmentTableColumns = self => {
  return [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`
    },
    {
      title: '编号',
      dataIndex: 'code',
      key: 'code',
      width: '10%'
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: '15%'
    },
    {
      title: '厂商',
      dataIndex: 'manufacturer',
      key: 'manufacturer',
      width: '20%'
    },
    {
      title: '分类',
      dataIndex: 'equip_classify',
      key: 'equip_classify',
      width: '15%',
      render: (text) => EquipClassifyEnum[text]
    },
    {
      title: '类型',
      dataIndex: 'equip_type',
      key: 'equip_type',
      width: '15%'
    },
    {
      title: '数量',
      dataIndex: 'numberInStation',
      key: 'numberInStation',
      width: '10%'
    },
    {
      title: '单位',
      dataIndex: 'unit',
      key: 'unit',
      width: '6%'
    }
  ];
};

const defaultHeight = 580;

const equipmentHeaderResult = fireStation => {
  let fireStationName;
  let fireStationCode;

  if (fireStation) {
    fireStationName = fireStation.name;
    fireStationCode = fireStation.code;
    return `${fireStationName}(${fireStationCode})`;
  } else {
    return '房间名称(编号)';
  }
};

/**
 * 重点设备配套装备
 */
class FireStationMatches extends Component {
  constructor(props) {
    super(props);

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

  componentWillMount() {
    if (this.props.location.state) {
      let { fireStation, key } = this.props.location.state;
      this.setState({
        fireStationId: fireStation.id,
        fireStationName: fireStation.name,
        fireStationCode: fireStation.code,
        fireStation,
        key
      });
    }
    let { searchParam } = this.state;
    searchParam.pageNumber = 0;
    searchParam.pageSize = 10;
    this.getMatchesFireEquipmentListData(searchParam);
  }

  onImgClick = () => {
    this.setState({
      enableCarousel: true
    });
  }

  getMatchesFireEquipmentListData = (param) => {
    let { searchParam, fireStationId } = this.state;

    if (param.current != null) {
      //前端的current 即后端的pageNumber
      param.pageNumber = param.current;
    }
    Object.assign(searchParam, { ...param });
    getMatchesFireEquipmentListAction(searchParam, fireStationId, searchParam.pageNumber, searchParam.pageSize).then(data => {
      this.setState({
        dataList: data.content,
        totalCount: data.totalElements
      });
    });
  };

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

  delete() {
    let { selectedRowKeys, fireStationId } = this.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请先选择需要删除的装备');
      return;
    }
    AmosAlert.confirm('提示', '确定删除指定装备?', {
      callback: flag => {
        if (flag) {
          // 确定删除
          let deleteObj = [];
          for (let i = 0; i < selectedRowKeys.length; i++) {
            let obj = {};
            obj.fireStationId = fireStationId;
            obj.fireEquipmentId = selectedRowKeys[i];
            deleteObj.push(obj);
          }
          deleteFireStationMatchesAction(deleteObj).then(
            data => {
              AmosAlert.success('提示', '删除成功');
              this.state.reload();
            },
            err => {
              AmosAlert.error('错误', err);
            }
          );
        }
      }
    });
  }

  goBack() {
    let { key } = this.state;
    let path = {
      pathname: '/biz/fireresource',
      state: { activeKey: key }
    };
    browserHistory.push(path);
  }

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

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

  bind = () => {
    let { selectedRowKeys, numberInStation, unitInStation } = this.bindView.state;
    let { fireStationId } = this.state;
    let bindObj = [];
    for (let i = 0; i < selectedRowKeys.length; i++) {
      let obj = {};
      obj.fireStationId = fireStationId;
      obj.fireEquipmentId = selectedRowKeys[i];
      obj.number = numberInStation[obj.fireEquipmentId] ? numberInStation[obj.fireEquipmentId] : 1;
      obj.unit = unitInStation[obj.fireEquipmentId];
      bindObj.push(obj);
    }
    if (bindObj.length > 0) {
      bindFireStationMatchesAction(bindObj).then(
        data => {
          AmosAlert.success('提示', '添加装备成功');
          this.state.reload();
        },
        err => {
          AmosAlert.error('错误', err || '添加装备失败');
        }
      );
    }
    this.setState({
      enableAddOp: false
    });
  }

  render() {
    let { dataList, totalCount, selectedRowKeys, enableAddOp, fireStation } = this.state;
    let _true_ = true;
    return (
      <div className="fire-station-matches" style={{ background: '#33333', height: '100%' }}>
        <Modal
          className='match-equipment-bind'
          header="添加配套设备"
          width='65%'
          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'>{equipmentHeaderResult(fireStation)}</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}
              totals={totalCount}
              getTableDataAction={this.getMatchesFireEquipmentListData}
              getSelectedRows={this.getSelectedRows}
              rowClassName={this.getRowClassName}
              setPageConfig={this.setPageConfig}
              getPanelHeight={this.getPanelHeight}
              defaultPageConlHeight={this.getPanelHeight}
              isChecked={_true_}
              selectedRowKeys={selectedRowKeys}
            />
          </div>
        </div>
      </div>
    );
  }
}

FireStationMatches.propTypes = {
  fireStation: PropTypes.object
};
export default FireStationMatches;
