import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { browserHistory } from 'amos-react-router';
import { baseURI } from 'CONSTS/urlConsts';
import { AmosAlert, Modal, Button } from 'amos-framework';
import AmosGridTable from './../../common/tableComponent/table/AmosGridTable';
import {
  getMatchEquipmentListAction,
  deleteMatchEquipmentAction,
  bindMatchEquipmentAction,
  getPrePlanPictureAction,
  getEquipmentDataAction
} from './../../../../services/ledgerService';
import EquipmentFireEquipmentAdd from './EquipmentFireEquipmentAdd';
import Picture from './Picture';
import BizIcon from './../../../common/icon/BizIcon';


const prePlanPictureEnum = { 1: '电源负荷图', 2: '电缆沟封堵图', 3: '消防车进战行车路线图', 4: '消防取水图' };

const matchEquipmentTableColumns = self => {
  return [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`
    },
    {
      title: '编号',
      dataIndex: 'code',
      key: 'code',
      width: '20%'
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: '25%'
    },
    {
      title: '厂商',
      dataIndex: 'manufacturer',
      key: 'manufacturer',
      width: '25%'
    },
    {
      title: '类型',
      dataIndex: 'equipType',
      key: 'equipType',
      width: '15%'
    }
  ];
};

const defaultHeight = 580;

const equipmentHeaderResult = equipment => {
  let equipmentName;
  let equipmentCode;

  if (equipment) {
    equipmentName = equipment.name;
    equipmentCode = equipment.code;
    return `${equipmentName}(${equipmentCode})`;
  } else {
    return '设备名称(设备编号)';
  }
};

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

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

  componentDidMount() {
    if (this.props.location.state) {
      let { equipmentId } = this.props.location.state;
      let { searchParam } = this.state;
      searchParam.pageNumber = 0;
      searchParam.pageSize = 10;
      if(equipmentId){
        this.getEquipmentData(equipmentId);
        this.setState({equipmentId},()=>this.getMatchEquipmentListData(searchParam));
        this.setState({equipmentId},()=>this.getPrePlanPictureData());
      }
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps && nextProps.location.state) {
      let { equipmentId } = nextProps.location.state || {};
      let { searchParam } = this.state;
      searchParam.pageNumber = 0;
      searchParam.pageSize = 10;
      if (equipmentId){
        this.getEquipmentData(equipmentId);
        this.setState({ equipmentId }, ()=>this.getMatchEquipmentListData(searchParam));
        this.setState({ equipmentId }, ()=>this.getPrePlanPictureData());
      }
    }
  }

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

  getEquipmentData = (equipmentId) => {
    getEquipmentDataAction(equipmentId).then(data => {
      this.setState({
        equipmentId: data.id,
        equipmentName: data.name,
        equipmentCode: data.code,
        equipment: data
      });
    });
  }

  getPrePlanPictureData() {
    let { equipmentId } = this.state;
    getPrePlanPictureAction(equipmentId, '').then(
      data => {
        let pMap = new Map();
        data.forEach(ele => {
          let type = ele.type;
          if (type >= 1 && type <= 4) {
            pMap.set(type, ele.picture);
          }
        });
        // for (let i = 0; i < data.length; i++) {
        //   let type = data[i].type;
        //   pMap.set(type, data[i].picture);
        // }
        this.setState({
          pictureMap: pMap
        });
      }
    );
  }

  getMatchEquipmentListData = (param) => {
    let { searchParam, equipmentId } = this.state;
    // equipmentId = 2;
    if (param.current != null) {
      //前端的current 即后端的pageNumber
      param.pageNumber = param.current;
    }
    Object.assign(searchParam, { ...param });
    equipmentId && getMatchEquipmentListAction(searchParam, equipmentId, 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() {
    console.log('添加重点设备配套装备');
    this.setState({
      enableAddOp: true
    });
  }

  // edit() {
  //   console.log('编辑重点设备配套装备');
  // }

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

  goBack() {
    let path = '/biz/equipment';
    browserHistory.push(path);
  }

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

  getPictureContext = () => {
    const { pictureMap } = this.state;
    let pictureList = [...pictureMap.values()];
    console.log(pictureList);
    return (<Picture pictureList={pictureList}  />);
  }

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

  bind = () => {
    let { selectedRowKeys } = this.bindView.state;
    let { equipmentId } = this.state;
    console.log(selectedRowKeys);
    let bindObj = [];
    for (let i = 0; i < selectedRowKeys.length; i++) {
      let obj = {};
      obj.equipmentId = equipmentId;
      obj.fireEquipmentId = selectedRowKeys[i];
      bindObj.push(obj);
    }
    if (bindObj.length > 0) {
      bindMatchEquipmentAction(equipmentId, bindObj).then(
        data => {
          AmosAlert.success('提示', '添加设备成功');
          this.state.reload();
        },
        err => {
          AmosAlert.error('错误', '添加设备失败');
        }
      );
    }
    this.setState({
      enableAddOp: false
    });
  }

  getImgServerPath(path) {
    if (path) {
      let realPath = `${baseURI}${path.substr(0, path.length)}`;
      return realPath;
    }
  }

  render() {
    let { dataList, totalCount, selectedRowKeys, enableAddOp, equipment, pictureMap, enableCarousel } = this.state;
    let _true_ = true;
    return (
      <div className="match-equipment" 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_}
        />
        <Modal
          className='match-equipment-carousel'
          header="图片浏览"
          width='65%'
          visible={enableCarousel}
          destroyContent
          onCancel={() => this.cancel('pic')}
          content={this.getPictureContext()}
          noDefaultFooter
        />
        <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(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}
              totals={totalCount}
              getTableDataAction={this.getMatchEquipmentListData}
              getSelectedRows={this.getSelectedRows}
              rowClassName={this.getRowClassName}
              setPageConfig={this.setPageConfig}
              getPanelHeight={this.getPanelHeight}
              defaultPageConlHeight={this.getPanelHeight}
              isChecked={_true_}
              selectedRowKeys={selectedRowKeys}
            />
          </div>
          <div className='match-equipment-photo'>
            <div className='match-equipment-photo-row1'>
              <div className='match-equipment-photo1'>
                <div className='match-equipment-item-title'>电源负荷图</div>
                <img alt='电源负荷图' src={this.getImgServerPath(pictureMap.get(1))} onClick={this.onImgClick} style={{ cursor: 'pointer' }} />
              </div>
              <div className='match-equipment-photo2'>
                <div className='match-equipment-item-title'>电缆沟封堵图</div>
                <img alt='电缆沟封堵图' src={this.getImgServerPath(pictureMap.get(2))} onClick={this.onImgClick} style={{ cursor: 'pointer' }} />
              </div>
            </div>
            <div className='match-equipment-photo-row2'>
              <div className='match-equipment-photo3'>
                <div className='match-equipment-item-title'>消防车进站行车路线图</div>
                <img alt='消防车进站行车路线图' src={this.getImgServerPath(pictureMap.get(3))} onClick={this.onImgClick} style={{ cursor: 'pointer' }} />
              </div>
              <div className='match-equipment-photo4'>
                <div className='match-equipment-item-title'>消防取水图</div>
                <img alt='消防取水图' src={this.getImgServerPath(pictureMap.get(4))} onClick={this.onImgClick} style={{ cursor: 'pointer' }} />
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

MatchEquipment.propTypes = {
  equipmentId: PropTypes.object
};
export default MatchEquipment;
