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

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

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

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

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

  // 获取能力数据
  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;
    if (interfaceList !== undefined) {
      interfaceList.map(item => {
        content.push(
          <Row>
            <Col
              span={21}
              offset={1}
              style={{
                textAlign: 'left',
                height: '30px',
                lineHeight: '30px',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                overflow: 'hidden'
              }}
            >
              {item.intfcName}
            </Col>
            <Col span={2} style={{ height: '30px', lineHeight: '30px' }}>
              <div onClick={e => this.onClickInterface(e, item)} className="edit-interface-img">
                <img src={require('./../../../assets/iot/img/list_nlsx.png')} alt="" />
              </div>
            </Col>
          </Row>
        );
      });
    }
    return content;
  };

  // 构建信息界面
  getCapacityPropertyContent = () => {
    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;
        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;
  };

  // 构建信息界面
  getCapacityPropertyEditContent = () => {
    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) {
      let quotaSelected = equipment.cfgParamMap.quotaSelected;
      let quotaList = quotaSelected[capacityBasicInfo.id];
      propertyList.map(item => {
        if (quotaList && quotaList.includes(item.id)) {
          let displayValue = equipment.cfgParamMap[`cpbl_${capacityBasicInfo.id}_${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 { closeDeviceCapacityPanel } = this.props;
    closeDeviceCapacityPanel();
  };

  // 保存设备属性信息
  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_${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') {
            message.success('编辑成功！');
          } else {
            message.danger('编辑失败！');
          }
        });
    }
  };

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

  render() {
    let { capacityBasicInfo } = this.props;
    let { protocolName, collapseKey } = this.state;
    return (
      <div className="device-capacity-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="device-capacity-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' }}>
                      {capacityBasicInfo.name}
                    </Col>
                  </Row>
                  <Row>
                    <Col span={4} offset={1} style={{ height: '30px', lineHeight: '30px' }}>
                      协议：
                    </Col>
                    <Col span={18} offset={1} style={{ textAlign: 'left', height: '30px', lineHeight: '30px' }}>
                      {protocolName}
                    </Col>
                  </Row>
                  <Row>
                    <Col span={4} offset={1} style={{ height: '30px', lineHeight: '30px' }}>
                      类型：
                    </Col>
                    <Col span={18} offset={1} style={{ textAlign: 'left', height: '30px', lineHeight: '30px' }}>
                      {stringUtil(capacityClassifyEnum, parseInt(capacityBasicInfo.type))}
                    </Col>
                  </Row>
                </div>
              </div>
            </Panel>
            <Panel showArrow={false} header={this.getCollapseHead('采集指标', '2')} key="2">
              <div className="device-capacity-property">{this.getCapacityPropertyEditContent()}</div>
            </Panel>
            <Panel showArrow={false} header={this.getCollapseHead('设备接口', '3')} key="3">
              <div className="device-capacity-interface">{this.getCapacityInterfaceContent()}</div>
            </Panel>
          </Collapse>
        </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;
