import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Icon,Input,Modal } from 'amos-antd';
import { Row,Col } from 'amos-framework';
import { AmosFetch } from '../../../../../utils/processor';
import { OltSerUrl } from '../../../../../consts/urlConsts';
import { capacatyclassifyEnum } from  './../../../../deviceManage/common/DeviceEnum';

/**
 * 设备能力面板
 *
 * @class DeviceCapacityPanel
 * @extends {Component}
 */
class DeviceCapacityPanel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      interfaceList: [],
      protocolName: '',
      propertyList: [],
      editProperty: false
    };
  }

  componentDidMount(){
    let { capacityBasicInfo } = this.props;
    this.getCapacityData(capacityBasicInfo.id);
  }

  componentWillReceiveProps(nextProps) {
    let { capacityBasicInfo,nodeId } = this.props;
    if (nextProps.capacityBasicInfo.id !== capacityBasicInfo.id || nodeId !== nextProps.nodeId) {
      this.getCapacityData(nextProps.capacityBasicInfo.id);
    }
  }

  //能力接口编辑
  onClickInterface = (e,item) => {
    let { showCapacityInterfacePanel,getCurrentEquipment } = this.props;
    showCapacityInterfacePanel(item,getCurrentEquipment);
  }

  //设备属性编辑
  onClickProperty = (e,flag) => {
    if (!flag) {
      this.savePropertyToEquipment();
    }
    this.setState({ editProperty: flag });
  }

  //属性编辑
  onAttributeChange = (e,propertyId) => {
    let { propertyList } = this.state;
    if (propertyList !== undefined) {
      propertyList.map((item)=>{
        if (item.id === propertyId) {
          item.valueStr = e.target.value;
        }
      });
    }
  }

  //获取能力数据
  getCapacityData = (id) => {
    if (id !== undefined) {
      let url = `${OltSerUrl.fetchCapacityListInfoById}/${id}`;
      AmosFetch.get(url).then(res => {
        if (res.ok) {
          return res.json();
        }
        else {
          throw new Error('从服务端获取数据失败！');
        }
      }).then((data) => {
        if (data.result === 'SUCCESS') {
          let dataList = data.dataList;
          if (dataList !== undefined) {
            let interfaceList = dataList.interface;
            let protocolName = dataList.protocolName;
            let propertyList = dataList.property;
            let noOutputProperty = [];
            propertyList.map((item)=>{
              if (item.type !== capacatyclassifyEnum.get('output').value) {
                noOutputProperty.push(item);
              }
            });
            this.setState({ interfaceList, protocolName,propertyList: noOutputProperty });
          }
        }
      });
    }
  }

  //构建信息界面
  getCapacityInterfaceContent = () => {
    let content = [];
    let { interfaceList } = this.state;
    let { capacityBasicInfo } = this.props;
    if (capacityBasicInfo === '压力') {
      content.push(<Row>
        <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }}>
          {'采集压力'}
        </Col>
        <Col span={18} offset={1} style={{ 'text-align': 'left', height: '30px', 'line-height': '30px' }} >
          <div onClick={(e) => this.onClickInterface(e, '压力')} className='edit-interface-img'>
            <img src={require('./../../../../../assets/iot/img/list_nlsx.png')} alt='' style={{ paddingTop: '3px' }} />
          </div>
        </Col>
      </Row>);
    } else {
      content.push(<Row>
        <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }}>
          {'采集GPS'}
        </Col>
        <Col span={18} offset={1} style={{ 'text-align': 'left', height: '30px', 'line-height': '30px' }} >
          <div onClick={(e) => this.onClickInterface(e, '采集GPS')} className='edit-interface-img'>
            <img src={require('./../../../../../assets/iot/img/list_nlsx.png')} alt='' style={{ paddingTop: '3px' }} />
          </div>
        </Col>
      </Row>);
    }
    return content;
  }

  //构建信息界面
  getCapacityPropertyContent = () => {
    let content = [];
    let { capacityBasicInfo } = this.props;
    if (capacityBasicInfo === '压力') {
      content.push(
        <Row>
          <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }}>
            {'压力'}：
          </Col>
          <Col span={18} offset={1} style={{ 'text-align': 'left', height: '30px', 'line-height': '30px' }} >
            <Input style={{ width: '60%' }}
              value={'2.6mPa'}
            />
          </Col>
        </Row>);
    } else {
      content.push(
        <Row>
          <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }}>
            {'经度'}：
          </Col>
          <Col span={18} offset={1} style={{ 'text-align': 'left', height: '30px', 'line-height': '30px' }} >
            <Input style={{ width: '60%' }}
              value={'113:42E'}
            />
          </Col>
        </Row>);
      content.push(
        <Row>
          <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }}>
            {'纬度'}：
          </Col>
          <Col span={18} offset={1} style={{ 'text-align': 'left', height: '30px', 'line-height': '30px' }} >
            <Input style={{ width: '60%' }}
              value={'34:44N'}
            />
          </Col>
        </Row>);
    }
    // let { propertyList } = this.state;
    // let { getCurrentEquipment,capacityBasicInfo } = this.props;
    // if (getCurrentEquipment === undefined) {
    //   return;
    // }
    // let equipment = getCurrentEquipment();
    // if (propertyList !== undefined && equipment.cfgParamMap !== undefined) {
    //   propertyList.map((item)=> {
    //     let displayValue = equipment.cfgParamMap[`cpbl_${capacityBasicInfo.id}_${item.id}`];
    //     displayValue = displayValue === undefined ? item.valueStr : displayValue;
    //     content.push(
    //       <Row>
    //         <Col span={5} style={{ height: '30px', 'line-height': '30px' }}>
    //           {item.displayName}：
    //         </Col>
    //         <Col span={18} offset={1} style={{ 'text-align': 'left', height: '30px', 'line-height': '30px' }} >
    //           {displayValue}
    //         </Col>
    //       </Row>
    //       );
    //   });
    // } else if (propertyList !== undefined && equipment.cfgParamMap === undefined) {
    //   propertyList.map((item)=> {
    //     content.push(
    //       <Row>
    //         <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }}>
    //           {item.displayName}：
    //         </Col>
    //         <Col span={18} offset={1} style={{ 'text-align': 'left', height: '30px', 'line-height': '30px' }} >
    //           {item.valueStr}
    //         </Col>
    //       </Row>);
    //   });
    // }
    return content;
  }

  //构建信息界面
  getCapacityPropertyEditContent = () => {
    let content = [];
    let { propertyList } = this.state;
    let { getCurrentEquipment,capacityBasicInfo } = this.props;
    if (getCurrentEquipment === undefined) {
      return;
    }
    let equipment = getCurrentEquipment();
    if (propertyList !== undefined && equipment.cfgParamMap !== undefined) {
      propertyList.map((item)=> {
        let displayValue = equipment.cfgParamMap[`cpbl_${capacityBasicInfo.id}_${item.id}`];
        displayValue = displayValue === undefined ? item.valueStr : displayValue;
        //更新数据
        item.valueStr = displayValue;
        content.push(<div className='device-capacity-text'>
          <label>
            {item.displayName}：
          </label>
          <Input style={{ width: '60%' }}
            onChange={(e) => this.onAttributeChange(e,item.id)}
            defaultValue={displayValue}
          />
        </div>);
      });
    } else if (propertyList !== undefined && equipment.cfgParamMap === undefined)
    {
      propertyList.map((item)=> {
        content.push(<div className='device-capacity-text'>
          <label>
            {item.displayName}：
          </label>
          <Input style={{ width: '60%' }}
            onChange={(e) => this.onAttributeChange(e,item.id)}
            defaultValue={item.valueStr}
          />
        </div>);
      });
    }
    return content;
  }

  //关闭界面
  closedPanel = () => {
    let { closeDeviceCapacityPanel } = this.props;
    closeDeviceCapacityPanel();
  }

  //保存设备属性信息
  savePropertyToEquipment = () => {
    let { getCurrentEquipment,capacityBasicInfo } = this.props;
    if (getCurrentEquipment === undefined) {
      return;
    }
    let equipment = getCurrentEquipment();
    let { propertyList } = this.state;
    if (equipment.id === undefined) {
      let { updateNodeConfig, nodeId,cfgParamJson } = this.props;
      if (propertyList !== undefined) {
        propertyList.map((item)=>{
          let key = `cpbl_${capacityBasicInfo.id}_${item.id}`;
          let value = item.valueStr;
          //有属性：覆盖，没数据：添加
          if (cfgParamJson.hasOwnProperty(key))
          {
            cfgParamJson[key] = value;
          } else {
            Object.assign(cfgParamJson,{ [key]: value });
          }
        });
        //保存到缓存
        updateNodeConfig(nodeId, cfgParamJson);
      }
    } else {
      let equipmentAttributes = equipment.cfgParamMap;
      if (propertyList !== undefined) {
        propertyList.map((item)=>{
          let key = `cpbl_${capacityBasicInfo.id}_${item.id}`;
          let value = item.valueStr;
          //有属性：覆盖，没数据：添加
          if (equipmentAttributes.hasOwnProperty(key))
          {
            equipmentAttributes[key] = value;
          } else {
            Object.assign(equipmentAttributes,{ [key]: value });
          }
        });
        equipment.cfgParamJson = JSON.stringify(equipmentAttributes);
        //保存到后台
        AmosFetch.post(OltSerUrl.addEquipmentAttribute, { data: equipment }).then(res => {
          if (res.ok) {
            return res.json();
          }
          else {
            throw new Error('从服务端获取数据失败！');
          }
        }).then((data) => {
          if (data.result === 'SUCCESS') {
            Modal.warning({
              title: '系统提示',
              content: '编辑成功！',
              okText: '确定'
            });
          } else {
            Modal.error({
              title: '系统提示',
              content: '编辑失败！',
              okText: '确定'
            });
          }
        });
      }
    }
  }

  render() {
    let { capacityBasicInfo } = this.props;
    let { protocolName,editProperty } = this.state;
    return (
      <div className='device-capacity-panel-content'>
        <div className='head-one'>数据采集</div><Icon type="close" onClick={this.closedPanel} style={{ position: 'absolute',top: '8px',right: '5px' }} />
        <div className='head-two'>
          <div className='head-two-one'>

          </div>
          <div className='head-two-two'>
            删除
          </div>
          <div className='head-two-three'>
            取消
          </div>
          <div className='head-two-four'>
            完成
          </div>
        </div>
        <div className='device-capacity-basic' >
          <div className='device-capacity-basic-label'>
            <label>设备接口</label>
            <img src={require('./../../../../../assets/iot/topo/u2074.png')} alt='' className='img-line' />
            <img src={require('./../../../../../assets/iot/topo/expand.png')} alt='' className='img-last-temp' />
          </div>
          <div>
            <Row>
              <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }}>
                名称：
              </Col>
              <Col span={18} offset={1} style={{ 'text-align': 'left', height: '30px', 'line-height': '30px' }} >
                <Input style={{ width: '60%' }}
                  value={capacityBasicInfo}
                />
              </Col>
            </Row>
            <Row>
              <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }}>
                协议：
              </Col>
              <Col span={18} offset={1} style={{ 'text-align': 'left', height: '30px', 'line-height': '30px' }} >
                <Input style={{ width: '60%' }}
                  value={capacityBasicInfo === '压力' ? '压力数据' : 'GPS数据'}
                />
              </Col>
            </Row>
            <Row>
              <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }}>
                类型：
              </Col>
              <Col span={18} offset={1} style={{ 'text-align': 'left', height: '30px', 'line-height': '30px' }} >
                <Input style={{ width: '60%' }}
                  defaultValue={'采集'}
                />
              </Col>
            </Row>
          </div>
        </div>
        <div className='device-capacity-property' >
          <div className='device-capacity-property-label'>
            <label>采集指标</label>
            <img src={require('./../../../../../assets/iot/topo/u2074.png')} alt='' className='img-line' />
            <img src={require('./../../../../../assets/iot/topo/expand.png')} alt='' className='img-last-temp' />
          </div>
          {editProperty ? this.getCapacityPropertyEditContent() : this.getCapacityPropertyContent()}
        </div>
        <div className='device-capacity-interface' >
          <div className='device-capacity-interface-label'>
            <label>设备接口</label>
            <img src={require('./../../../../../assets/iot/topo/u2074.png')} alt='' className='img-line' />
            <img src={require('./../../../../../assets/iot/topo/expand.png')} alt='' className='img-last-temp' />
          </div>
          {this.getCapacityInterfaceContent()}
        </div>
      </div>
    );
  }
}

DeviceCapacityPanel.propTypes = {
  closeDeviceCapacityPanel: PropTypes.func,
  capacityBasicInfo: PropTypes.object,
  showCapacityInterfacePanel: PropTypes.func,
  getCurrentEquipment: PropTypes.func,
  updateNodeConfig: PropTypes.func,
  cfgParamJson: PropTypes.object,
  nodeId: PropTypes.string
};

DeviceCapacityPanel.defaultProps = {
  capacityBasicInfo: {}
};

export default DeviceCapacityPanel;
