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

const Panel = Collapse.Panel;
const collapseHeadHeight = 95;
/**
 *
 *能力接口面板
 * @class CapacityInterfacePanel
 * @extends {Component}
 */
class CapacityInterfacePanel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      propertyList: [],
      collapseKey: [ '1','2' ],
      tempEdit: {}
    };
  }

  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);
      this.setState({ tempEdit: {} });
    }
  }

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

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


  //获取接口数据
  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;
    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.intfcId}_${item.id}`];
        displayValue = displayValue === undefined ? item.valueStr : displayValue;
        content.push(
          <Row>
            <Col span={4} offset={1} style={{ height: '30px', lineHeight: '30px',textOverflow: 'ellipsis',whiteSpace: 'nowrap','overflow': 'hidden' }}>
              {item.displayName}：
            </Col>
            <Col span={18} offset={1} style={{ textAlign: 'left', height: '30px', lineHeight: '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', lineHeight: '30px',textOverflow: 'ellipsis',whiteSpace: 'nowrap','overflow': 'hidden' }}>
              {item.displayName}：
            </Col>
            <Col span={18} offset={1} style={{ textAlign: 'left', height: '30px', lineHeight: '30px' }} >
              {item.valueStr}
            </Col>
          </Row>);
      });
    }
    return content;
  }

  //获取能力接口
  getCapacityInterfaceEditContent = ()=> {
    let content = [];
    let { propertyList,tempEdit } = 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.intfcId}_${item.id}`];
        displayValue = displayValue === undefined ? item.valueStr : displayValue;
        item.valueStr = tempEdit[item.id] ? tempEdit[item.id] : displayValue;
        content.push(
          <Row>
            <Col title={item.displayName} span={8} offset={1} style={{ textAlign: 'right',height: '30px', lineHeight: '30px',textOverflow: 'ellipsis',whiteSpace: 'nowrap','overflow': 'hidden' }}>
              {item.displayName}：
            </Col>
            <Col span={14} offset={1} style={{ textAlign: 'left', height: '30px', lineHeight: '30px' }} >
              <Input style={{ width: '90%' }}
                onChange={(e) => this.onAttributeChange(e, item.id)}
                value={item.valueStr}
              />
            </Col>
          </Row>);
      });
    } else if (propertyList !== undefined && equipment.cfgParamMap === undefined)
    {
      propertyList.map((item)=> {
        content.push(
          <Row>
            <Col title={item.displayName} span={8} offset={1} style={{ textAlign: 'right',height: '30px', lineHeight: '30px',textOverflow: 'ellipsis',whiteSpace: 'nowrap','overflow': 'hidden' }}>
              {item.displayName}：
            </Col>
            <Col span={14} offset={1} style={{ textAlign: 'left', height: '30px', lineHeight: '30px' }} >
              <Input style={{ width: '90%' }}
                onChange={(e) => this.onAttributeChange(e, item.id)}
                value={item.valueStr}
              />
            </Col>
          </Row>);
      });
    }
    return content;
  }

  //折叠面板折叠操作区内容
  getCollapseHead = (name,index) => {
    let imgPath = this.getImgPath(index);
    let content = [];
    let lineClass = name.length > 4 ? 'img-line' : 'img-short-line';
    content.push(<div className='img-line-root'>
      <label>{name}</label>
      <img src={require('./../../../assets/iot/topo/u2074.png')} alt='' className={lineClass} />
      {imgPath}
    </div>);
    return content;
  }

  getImgPath = (index) => {
    let { collapseKey } = this.state;
    let imgPath;
    if (collapseKey.includes(index))
    {
      imgPath = (<img src={require('./../../../assets/iot/topo/expand.png')} alt='' className='img-last' />);
    } else {
      imgPath = (<img src={require('./../../../assets/iot/topo/shrink.png')} alt='' className='img-last' />);
    }
    return imgPath;
  }

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

  //保存设备属性信息
  savePropertyToEquipment = () => {
    let { getCurrentEquipment,capacityBasicInfo } = this.props;
    if (getCurrentEquipment === undefined) {
      return;
    }
    let equipment = getCurrentEquipment();
    let { propertyList } = this.state;
    let equipmentAttributes = equipment.cfgParamMap;
    if (propertyList !== undefined) {
      propertyList.map((item)=>{
        let key = `cpbl_intfc_${capacityBasicInfo.id}_${item.intfcId}_${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') {
          message.success('编辑成功！');
        } else {
          message.danger('编辑失败！');
        }
      });
    }
  }

  //折叠面板区滑动条控制
  changeCollapseSize = (key) =>{
    let collapsepanel = this.collapsepanel;
    let style = dt2react.getOffsetParent(collapsepanel);
    let height = style.clientHeight - collapseHeadHeight;
    dt2react.addStyle(collapsepanel,'height',`${height}px`);
    if (key !== undefined && key.length !== undefined) {
      this.setState({ collapseKey: key });
    }
  }

  render() {
    let { interfaceBasicInfo } = this.props;
    let { collapseKey } = this.state;
    return (
      <div className='capacity-interface-panel-content'>
        <div className='head-one'>设备接口</div>
        <Icon type='close' onClick={this.closedPanel} style={{ position: 'relative',top: '-26px',left: '14rem' }} />
        <div className='head-two' style={{ position: 'relative',top: '21px' }}>
          <div className='head-two-five' style={{ position: 'relative',top: '-42px' }} />
          <div className='head-two-six' style={{ position: 'relative',top: '-72px' }} onClick={(e)=>this.onClickProperty(e)}>
            完成
          </div>
        </div>
        <div className='amos-collapse-panel' style={{ position: 'relative',top: '-21px' }} ref={node => this.collapsepanel = node} >
          <Collapse activeKey={collapseKey}  onChange={key => this.changeCollapseSize(key)}  >
            <Panel showArrow={false} header={this.getCollapseHead('基本信息','1')} key="1">
              <div className='capacity-interface-basic' >
                <div>
                  <Row>
                    <Col span={4} offset={1} style={{ height: '30px', lineHeight: '30px' }}>
                      名称：
                    </Col>
                    <Col span={18} offset={1} style={{ textAlign: 'left', height: '30px', lineHeight: '30px' }} >
                      {interfaceBasicInfo.intfcName}
                    </Col>
                  </Row>
                </div>
              </div>
            </Panel>
            <Panel showArrow={false} header={this.getCollapseHead('通讯参数','2')} key="2" >
              <div className='capacity-interface-property' >
                {this.getCapacityInterfaceEditContent()}
              </div>
            </Panel>
          </Collapse>
        </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;
