import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Modal } from 'amos-antd';
import { AmosFetch } from 'UTILS/processor';
import { OltSerUrl } from 'CONSTS/urlConsts';
import { message } from 'amos-framework';
import CapacityPropertyCell from './CapacityPropertyCell';
import AddCapacityProperty from './../deviceAddEdit/AddCapacityProperty';
import './../device-detail.scss';

/**
 *
 * 采集指标
 * @class CapacityProperty
 * @extends {Component}
 */
class CapacityProperty extends Component {
  constructor(props) {
    super(props);
    this.state = {

    };
  }

  componentDidMount(){

  }

  /**
   * 取能力属性
   *
   * @memberof PrivateDeviceDetail
   */
  fetchCapacityProperty = (e) => {
    let { propertyInfo,deviceId,getDeviceInfoById,visibility } = this.props;
    let list = [];
    if (propertyInfo !== undefined) {
      for (var index = 0; index < propertyInfo.length; index++) {
        let value = propertyInfo[index];
        list.push(<CapacityPropertyCell key={index} propertyInfo={value} deleteCapacityProperty={this.deleteCapacityProperty} deviceId={deviceId} visibility={visibility} getDeviceInfoById={getDeviceInfoById} />);
      }
    }
    return list;
  }

  /**
   * 删除采集指标
   *
   * @memberof PrivateDeviceDetail
   */
  deleteCapacityProperty = (propertyId) => {
    let delfunc = this.delProperty;
    Modal.confirm({
      title: '删除',
      content: '是否删除所选属性？',
      okText: '确定',
      cancelText: '取消',
      onOk() { delfunc(propertyId); },
      onCancel() { }
    });
  }

  delProperty = (propertyId) => {
    let { deviceId } = this.props;
    //删除数据库
    let url = `${OltSerUrl.deleteCapacityProperty}/${propertyId}`;
    AmosFetch.del(url).then(res => {
      if (res.ok) {
        return res.text();
      }
      else
      {
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data)=>{
    //重新刷新数据
      message.success('删除成功！');
      this.props.getDeviceInfoById(deviceId);
    });
  }

  render() {
    let { deviceId,getDeviceInfoById,capacityId,visibility, addCapacityProperty } = this.props;
    return (
      <div className='capacity-property'>
        <div className='capacity-detail-property'>
          <label>采集指标</label>
          {visibility===1? <AddCapacityProperty addCapacityProperty={addCapacityProperty} capacityId={capacityId} getDeviceInfoById={getDeviceInfoById} deviceId={deviceId} />:null}
        </div>
        <div className='capacity-detail-property-content'>
          {this.fetchCapacityProperty()}
        </div>
      </div>
    );
  }
}

CapacityProperty.propTypes = {
  propertyInfo: PropTypes.array,
  deviceId: PropTypes.number,
  capacityId: PropTypes.number,
  addCapacityProperty: PropTypes.func,
  getDeviceInfoById: PropTypes.func
};

export default CapacityProperty;
