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 DevicePropertyCell from './DevicePropertyCell';
import AddDeviceProperty from './../deviceAddEdit/AddDeviceProperty';
import './../device-detail.scss';

/**
 *
 * 设备属性
 * @class DeviceProperty
 * @extends {Component}
 */
class DeviceProperty extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {}

  /**
   * 取设备属性
   *
   * @memberof PrivateDeviceDetail
   */
  fetchDeviceProperty = e => {
    let { device } = this.props;
    let deviceId = device.id;
    let devicePropertyList = device.attributes;
    let visibility = device.visibility;
    let list = [];
    if (devicePropertyList !== undefined) {
      for (var index = 0; index < devicePropertyList.length; index++) {
        let value = devicePropertyList[index];
        list.push(
          <DevicePropertyCell
            key={index}
            propertyInfo={value}
            deleteDeviceProperty={this.deleteDeviceProperty}
            deviceId={deviceId}
            visibility={visibility}
            {...this.props}
          />
        );
      }
    }
    return list;
  };

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

  delProperty = propertyId => {
    let deviceId = this.props.device.id;
    //删除数据库
    let url = `${OltSerUrl.deleteDeviceProperty}/${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 { device, getDeviceInfoById } = this.props;
    return (
      <div className="device-property">
        <div className="device-detail-property">
          <label>基本属性</label>
          {device.visibility === 1 ? <AddDeviceProperty deviceId={device.id} getDeviceInfoById={getDeviceInfoById} {...this.props} /> : null}
        </div>
        <div className="device-detail-property-content">{this.fetchDeviceProperty()}</div>
      </div>
    );
  }
}

DeviceProperty.propTypes = {
  device: PropTypes.object,
  getDeviceInfoById: PropTypes.func
};

export default DeviceProperty;
