import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { OltSerUrl } from '../../../consts/urlConsts';
import { Input,Form } from 'amos-antd';
import { AmosFetch } from '../../../utils/processor';
import { Editable,Row,Col,Collapse,message } from 'amos-framework';
import dt2react from 'dt2react';
import { deviceCategoryEnum } from  './../../deviceManage/common/DeviceEnum';
import { stringUtil } from './../../deviceManage/common/DeviceLang';
import './topo.scss';

const createForm = Form.create();
const Panel = Collapse.Panel;
const collapseHeadHeight = 95;
/**
 * 设备属性
 *
 * @class DeviceProperty
 * @extends {Component}
 */
class DevicePropertyPanel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      attributes: [],
      intfcList: [],
      capabilities: [],
      equipment: {},
      collapseKey: [ '1','2','3' ]
    };
  }

  /**
   * 初始化
   */
  componentDidMount() {
    let { config,equipmentId } = this.props;
    let propertyContent = config.data ? config.data : {};
    this.getPropertyData(propertyContent.id,equipmentId);
    this.getInterfaceData(propertyContent.id);
    this.changeCollapseSize();
  }

  componentWillReceiveProps(nextProps){
    let { nodeId,cfgParamJson } = this.props;
    let nextPropertyContent = nextProps.config.data ? nextProps.config.data : {};
    if (nodeId !== nextProps.nodeId || cfgParamJson !== nextProps.cfgParamJson) {
      this.getPropertyData(nextPropertyContent.id,nextProps.equipmentId);
      this.getInterfaceData(nextPropertyContent.id);
    }
  }

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

  //设备能力编辑
  onClickCapacity = (e,item) => {
    let { showDeviceCapacityPanel,closeCapacityInterfacePanel } = this.props;
    showDeviceCapacityPanel(item,this.getCurrentEquipment);
    closeCapacityInterfacePanel();
  }

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

  //获取设备能力
  getPropertyData = (id,equipmentId) => {
    if (id !== undefined) {
      let { config } = this.props;
      if (config && config.data) {
        let template = config.data.eqpTmplId;
        let url = `${OltSerUrl.fetchDeviceById}/${template}`;
        AmosFetch.get(url).then(res => {
          if (res.ok) {
            return res.json();
          }
          else
          {
            throw new Error('从服务端获取数据失败！');
          }
        }).then((data)=>{
          if (data.result === 'SUCCESS'){
            let deviceData = data.dataList;
            if (deviceData !== undefined) {
              let capabilities = deviceData.capabilities ? deviceData.capabilities : [];
              this.getEquipmentData(equipmentId,deviceData.attributes ? deviceData.attributes : [],capabilities);
            }
          }
        });
      }
    }
  }

  //获取设备接口
  getInterfaceData = (id) => {
    if (id !== undefined) {
      let { config } = this.props;
      if (config && config.data) {
        let template = config.data.eqpTmplId;
        let url = `${OltSerUrl.fetchDeviceInterfaceById}/${template}`;
        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;
            this.setState({ intfcList: dataList ? dataList : [] });
          }
        });
      }
    }
  }

  //获取设备信息
  getEquipmentData = (id,attributes,capabilities) => {
    if (id !== undefined) {
      let url = `${OltSerUrl.getEquipmentData}/${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;
          //用设备的属性替换模板默认属性
          let selCpblIds = dataList.cfgParamMap.selCpblIds;
          let selCapabilities = [];
          selCpblIds && capabilities.map((item) => {
            if (selCpblIds.includes(String(item.id))){
              selCapabilities.push(item);
            }
          });
          attributes.map((item)=> {
            item.valueStr = dataList.cfgParamMap[`equip_${item.id}`];
          });
          this.setState({ equipment: dataList,attributes,capabilities: selCapabilities });
        }
      });
    } else {
      this.setState({ equipment: {} });
    }
  }

  //生成编辑界面
  getAttributesEditContent = () => {
    let { attributes,equipment } = this.state;
    let content = [];
    if (equipment.cfgParamMap !== undefined) {
      attributes.map((item)=>{
        let displayValue = item.valueStr;
        content.push(
          <Row>
            <Col title={item.displayName} span={8} offset={1} style={{ 'text-align': 'right',height: '30px', 'line-height': '30px','text-overflow': 'ellipsis','white-space': 'nowrap','overflow': 'hidden' }} >
              {item.displayName}：
            </Col>
            <Col span={14} offset={1} style={{ 'text-align': 'left',height: '30px', 'line-height': '30px' }} >
              <Input style={{ width: '90%' }}
                onChange={(e) => this.onAttributeChange(e, item.id)}
                value={displayValue}
              />
            </Col>
          </Row>);
      });
    } else {
      attributes.map((item)=>{
        content.push(
          <Row>
            <Col title={item.displayName} span={8} offset={1} style={{ 'text-align': 'right',height: '30px', 'line-height': '30px','text-overflow': 'ellipsis','white-space': 'nowrap','overflow': 'hidden' }} >
              {item.displayName}：
            </Col>
            <Col span={14} offset={1} style={{ 'text-align': 'left',height: '30px', 'line-height': '30px' }} >
              <Input style={{ width: '90%' }}
                onChange={(e) => this.onAttributeChange(e, item.id)}
                value={item.valueStr}
              />
            </Col>
          </Row>);
      });
    }
    return content;
  }

  //生成界面
  getCapacitysContent = () => {
    let { capabilities } = this.state;
    let content = [];
    capabilities.map((item)=>{
      content.push(
        <Row>
          <Col
            span={21}
            offset={1}
            style={{
              height: '30px',
              'line-height': '30px',
              'text-overflow': 'ellipsis',
              'white-space': 'nowrap',
              'overflow': 'hidden',
              'text-align': 'left'
            }}
          >
            {item.name}
          </Col>
          <Col span={2} style={{ height: '30px','line-height': '30px' }} >
            <div onClick={(e) => this.onClickCapacity(e,item)} className='edit-interface-img'>
              <img src={require('./../../../assets/iot/img/list_nlsx.png')} alt='' style={{ position: 'relative',top: '5px' }} />
            </div>
          </Col>
        </Row>);
    });
    return content;
  }

  //获取当前设备
  getCurrentEquipment = () => {
    let { equipment } = this.state;
    return equipment;
  }

  //折叠面板折叠操作区内容
  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;
  }

  //保存设备属性信息
  savePropertyToEquipment = () => {
    let { attributes,equipment } = this.state;
    let equipmentAttributes = equipment.cfgParamMap;
    if (attributes !== undefined) {
      attributes.map((item)=>{
        let key = `equip_${item.id}`;
        let value = item.valueStr;
        //有属性：覆盖，没数据：添加
        if (equipmentAttributes.hasOwnProperty(key))
        {
          equipmentAttributes[key] = value;
        } else {
          Object.assign(equipmentAttributes,{ [key]: value });
        }
        //=============按要求做特殊处理，额外添加sid==================
        if (item.name === 'sourceId') {
          if (equipmentAttributes.hasOwnProperty('sid'))
          {
            equipmentAttributes.sid = value;
          } else {
            Object.assign(equipmentAttributes,{ sid: value });
          }
        }
        //================================================
      });
      //==============没有sourceId的情况==================
      if (!equipmentAttributes.hasOwnProperty('sid'))
      {
        Object.assign(equipmentAttributes,{ sid: '' });
      }
      //================================================
      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('编辑失败！');
        }
      });
    }
  }

  //更新名称
  updateName = (name) => {
    let { equipment } = this.state;
    let { config,getSubgraphData,subviewId,nodeId } = this.props;
    let oldName = this.name;
    this.name = name;
    if (equipment.id !== undefined) {
      let propertyContent = config.data;
      let newConfig = {
        label: name,
        type: config.type,
        data: propertyContent,
        style: config.style
      };
      let id = propertyContent.id;
      let postData = { id,name,nodeId,config: JSON.stringify(newConfig) };
      let url = `${OltSerUrl.updateNodeName}`;
      //提交后台
      AmosFetch.post(url,{ data: postData }).then(res => {
        if (res.ok) {
          return res.json();
        }
        else
        {
          throw new Error('从服务端获取数据失败！');
        }
      }).then((data)=>{
        if (data.result === 'SUCCESS'){
          if (data.dataList === -1){
            message.danger('设备名称重复！');
            this.name = oldName;
            this.setState({ attributes: this.state.attributes });
          } else {
            getSubgraphData(subviewId,nodeId);
          }
        } 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 { config,deleteNode,nodeId,doHiddenProperty } = this.props;
    let { collapseKey } = this.state;
    let propertyContent;
    let name;
    if (config !== undefined) {
      propertyContent = config.data ? config.data : {};
      name = config.label === undefined ? this.name : config.label;
    }
    // let displayImgUrl = propertyContent.img;
    // let srcImgUrl = displayImgUrl === '' ? `${OltSerUrl.fetchDeviceImg}/default.png` : `${OltSerUrl.fetchDeviceImg}/${displayImgUrl}`;
    return (
      <div className='device-property-panel'>
        {/*<div className='property-img-info'>
          <img src={srcImgUrl} alt='device' width='100%' height='100%' />
    </div>*/}
        <div className='head-one'>设备信息</div>
        <div className='head-two'>
          <div className='head-two-one' />
          <div className='head-two-two' onClick={(e)=>deleteNode(nodeId)}>
            移出
          </div>
          <div className='head-two-three' onClick={(e)=>doHiddenProperty(e)}>
            取消
          </div>
          <div className='head-two-four' onClick={(e)=>this.onClickProperty(e)}>
            完成
          </div>
        </div>
        <div className='amos-collapse-panel' ref={node => this.collapsepanel = node} >
          <Collapse activeKey={collapseKey}  onChange={key => this.changeCollapseSize(key)} >
            <Panel showArrow={false} header={this.getCollapseHead('基本信息','1')} key="1">
              <div className='property-basic-info'>
                <div style={{ height: '100%' }}>
                  <Row>
                    <Col span={4} offset={1} style={{ height: '30px','line-height': '30px' }} >
                      名称：
                    </Col>
                    <Col span={18} offset={1} style={{ 'text-align': 'left' }} >
                      <Editable value={name} onChange={this.updateName} showOkCancel={false} />
                    </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' }} >
                      {propertyContent.model}
                    </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' }} >
                      {propertyContent ? stringUtil(deviceCategoryEnum, parseInt(propertyContent.type)) : ''}
                    </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' }} >
                      {propertyContent.descr}
                    </Col>
                  </Row>
                </div>
              </div>
            </Panel>
            <Panel showArrow={false} header={this.getCollapseHead('基本属性','2')} key="2">
              <div className='property-property-info'>
                {this.getAttributesEditContent()}
              </div>
            </Panel>
            <Panel showArrow={false} header={this.getCollapseHead('数据采集','3')} key="3" >
              <div className='property-interface-info'>
                {this.getCapacitysContent()}
              </div>
            </Panel>
          </Collapse>
        </div>
      </div>
    );
  }
}

DevicePropertyPanel.propTypes = {
  config: PropTypes.object,
  form: PropTypes.any,
  getSubgraphData: PropTypes,
  subviewId: PropTypes.string,
  nodeId: PropTypes.string,
  showDeviceCapacityPanel: PropTypes.func,
  equipmentId: PropTypes.number,
  updateNodeConfig: PropTypes.func,
  cfgParamJson: PropTypes.object,
  deviceLabel: PropTypes.string,
  deleteNode: PropTypes.func,
  doHiddenProperty: PropTypes.func,
  closeCapacityInterfacePanel: PropTypes.func
};

export default createForm(DevicePropertyPanel);
