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

/**
 *
 *能力接口面板
 * @class CapacityInterfacePanel
 * @extends {Component}
 */
class CapacityInterfacePanel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      propertyList: [],
      editProperty: false
    };
  }

  componentDidMount(){
    let { interfaceBasicInfo } = this.props;
    this.getInterfaceData(interfaceBasicInfo.intfcId);
  }

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

   //设备属性编辑
  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;
        }
      });
    }
  }


  //获取接口数据
  getInterfaceData = (id) => {
    if (id !== undefined) {
      let url = `${OltSerUrl.deviceInterfaceByid}/${id}`;
      AmosFetch.post(url).then(res => {
        if (res.ok) {
          return res.json();
        } else {
          throw new Error('从服务端获取数据失败！');
        }
      }).then((data)=>{
        this.setState({
          propertyList: data.dataList.content
        });
      });
    }
  }

  //获取能力接口
  getCapacityInterfaceContent = ()=> {
    let content = [];
    let { propertyList } = this.state;
    let { getCurrentEquipment,capacityBasicInfo } = this.props;
    content.push(
      <Row>
        <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }}>
          {'设备ID'}：
        </Col>
        <Col span={18} offset={1} style={{ 'text-align': 'left', height: '30px', 'line-height': '30px' }} >
          <Input style={{ width: '60%' }}
            defaultValue={''}
          />
        </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%' }}
            defaultValue={'1'}
          />
        </Col>
      </Row>);
    // if (getCurrentEquipment === undefined) {
    //   return;
    // }
    // let equipment = getCurrentEquipment();
    // if (propertyList !== undefined && equipment.cfgParamMap !== undefined) {
    //   propertyList.map((item)=> {
    //     let displayValue = equipment.cfgParamMap[`cpbl_intfc_${capacityBasicInfo.id}_${item.id}`];
    //     displayValue = displayValue === undefined ? item.valueStr : displayValue;
    //     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' }} >
    //           {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;
  }

  //获取能力接口
  getCapacityInterfaceEditContent = ()=> {
    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_intfc_${capacityBasicInfo.id}_${item.id}`];
        displayValue = displayValue === undefined ? item.valueStr : displayValue;
        item.valueStr = displayValue;
        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' }} >
              <Input style={{ width: '60%' }}
                onChange={(e) => this.onAttributeChange(e, item.id)}
                defaultValue={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' }} >
              <Input style={{ width: '60%' }}
                onChange={(e) => this.onAttributeChange(e, item.id)}
                defaultValue={item.valueStr}
              />
            </Col>
          </Row>);
      });
    }
    return content;
  }

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

  //保存设备属性信息
  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_intfc_${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_intfc_${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 { interfaceBasicInfo } = this.props;
    let { editProperty } = this.state;
    return (
      <div className='capacity-interface-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='capacity-interface-basic' >
          <div className='capacity-interface-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={interfaceBasicInfo}
                />
              </Col>
            </Row>
          </div>
        </div>
        <div className='capacity-interface-property' >
          <div className='capacity-interface-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.getCapacityInterfaceEditContent() : this.getCapacityInterfaceContent()}
        </div>
      </div>
    );
  }
}

CapacityInterfacePanel.propTypes = {
  closeCapacityInterfacePanel: PropTypes.func,
  interfaceBasicInfo: PropTypes.object,
  capacityBasicInfo: PropTypes.object,
  getCurrentEquipment: PropTypes.func,
  updateNodeConfig: PropTypes.func,
  cfgParamJson: PropTypes.object,
  nodeId: PropTypes.string
};

CapacityInterfacePanel.defaultProps = {
  interfaceBasicInfo: {},
  capacityBasicInfo: {}
};

export default CapacityInterfacePanel;
