import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { PubSub } from 'ray-eventpool';
import QuotaCommonCell from './commoncell/QuotaCommonCell';
import { fetchTemplatOrEqpQuotaAction } from './../../../services/deviceService';
import { SELECT_STATUS_CHANGE_TOPIC } from './../common/ActionConf';

/**
 *
 *
 * @class DeviceQuotaInfo
 * @extends {Component}
 */
class DeviceQuotaInfo extends Component {
  constructor(props) {
    super(props);
    this.autoSelectedCpbId = undefined;
    this.state = {
      quotaList: [],
      refreshFlag: true
    };
  }

  componentDidMount() {
    let { device, equipment, updateQuotaCellStatus } = this.props;
    this.getTemplatQuotas(device.id, equipment ? equipment.id : 0);
    this.pubsub_change = PubSub.subscribe(SELECT_STATUS_CHANGE_TOPIC.selectStatusChange, (e, { cpbId, status }) => {
      if (cpbId !== undefined) {
        updateQuotaCellStatus(cpbId, status);
      }
      this.autoSelectedCpbId = cpbId;
      this.setState({ refreshFlag: true });
    });
  }

  componentWillUnmount() {
    PubSub.unsubscribe(this.pubsub_change);
  }

  getTemplatQuotas = (devId, eqpId) => {
    fetchTemplatOrEqpQuotaAction(devId, eqpId).then(data => {
      this.setState({ quotaList: data });
      let { updateQuotaTaskCell } = this.props;
      data &&
        data.map(item => {
          let taskParam = {
            monitorType: item.monitorType,
            monitorPeriod: item.monitorPeriod
          };
          updateQuotaTaskCell(item.id, taskParam);
        });
      this.props.getQuotaInfo(data);
    });
  };

  getQuotaList = () => {
    let { quotaList } = this.state;
    let autoSelectedCpbId = this.autoSelectedCpbId;
    let { refreshCellStatus } = this.props;
    if (refreshCellStatus) {
      autoSelectedCpbId = undefined;
      this.autoSelectedCpbId = autoSelectedCpbId;
    }
    let content = [];
    quotaList.map(item => {
      let autoSelected;
      if (autoSelectedCpbId && autoSelectedCpbId === item.id) {
        autoSelected = true;
      }
      content.push(<QuotaCommonCell key={item.id} updateStatus={this.updateStatus} autoSelected={autoSelected} content={item} {...this.props} />);
    });
    return content;
  };

  updateStatus = status => {
    this.autoSelectedCpbId = status;
    this.setState({ refreshFlag: true });
  };

  render() {
    return (
      <div className="add-device-left-quota">
        <div className="template-quota-info-title">数据采集</div>
        <div className="template-quota-info-body">{this.getQuotaList()}</div>
      </div>
    );
  }
}

DeviceQuotaInfo.propTypes = {
  device: PropTypes.object,
  equipment: PropTypes.object,
  getQuotaInfo: PropTypes.func,
  updateQuotaCellStatus: PropTypes.func,
  enable: PropTypes.bool,
  refreshCellStatus: PropTypes.bool,
  updateQuotaTaskCell: PropTypes.func
};

DeviceQuotaInfo.defaultProps = {
  enable: true
};

export default DeviceQuotaInfo;
