import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Collapse, Editable, message } from 'amos-framework';
import OltSerUrl from '../../../../consts/urlConsts';
import TopoUpLoadIcon from './TopoUpLoadIcon';
import { deviceCategoryEnum } from './../../../deviceManage/common/DeviceEnum';
import { stringUtil } from './../../../deviceManage/common/DeviceLang';
import { updateEquipmentNameAction, updateEquipmentConfigAction, addeEditEqpImgAction } from './../../../../services/topoService';

const Panel = Collapse.Panel;
/**
 *
 *
 * @class DeviceBasicInfoConfig
 * @extends {Component}
 */
class DeviceBasicInfoConfig extends Component {
  constructor(props) {
    super(props);
    this.deviceConfigParam = {};
    this.state = {
      collapseKey: ['1', '2']
    };
  }
  componentWillMount() {}

  componentDidMount() {}

  componentWillReceiveProps(nextProps) {}

  componentWillUnmount() {}

  //折叠面板区滑动条控制
  onChangeCollapseSize = key => {
    if (key !== undefined && key.length !== undefined) {
      this.setState({ collapseKey: key });
    }
  };

  onAttributeChange = (key, value) => {
    let { equipmentId, nodeId, showProperty } = this.props;
    let postData = {
      id: equipmentId
    };
    let { attributes } = this.props.currentDeviceConfig.device;
    attributes.map(item => {
      let name = item.name;
      if (name && name === 'sourceId') {
        postData['sid'] = value;
      }
    });
    postData[key] = value;
    updateEquipmentConfigAction(postData).then(res => {
      let deviceConfigParam = this.deviceConfigParam;
      deviceConfigParam[key] = value;
      showProperty(nodeId);
    });
  };

  /**
   * 设置图片
   *
   * @memberof AddDevice
   */
  setImgFile = imgFile => {
    const reader = new FileReader();
    reader.addEventListener('load', () => this.saveImgFileAction(reader.result, imgFile.name));
    if (JSON.stringify(imgFile) === '{}') {
      let imgInfo = { binaryImg: null, imgName: null };
      this.saveEquipmnet(imgInfo);
    } else {
      reader.readAsBinaryString(imgFile);
    }
  };

  //折叠面板折叠操作区内容
  getCollapseHead = (name, index) => {
    let imgPath = this.props.getImgPath(index, this.state.collapseKey);
    let content = [];
    content.push(
      <div className="config-collapse-head">
        <label className="config-collapse-text">{name}</label>
        {imgPath}
      </div>
    );
    return content;
  };

  getDeviceConfigInfo = () => {
    let { currentDeviceConfig } = this.props;
    let equipment = currentDeviceConfig ? currentDeviceConfig.eqp : undefined;
    let equipmentPropertys = currentDeviceConfig ? currentDeviceConfig.eqpProperty : undefined;
    let deviceConfigParam = this.deviceConfigParam;
    let content = [];
    equipmentPropertys &&
      equipmentPropertys.map(item => {
        let value = deviceConfigParam[`equip_${item.id}`];
        if (value === undefined) {
          let param = equipment.cfgParamMap;
          value = param[`equip_${item.id}`] ? param[`equip_${item.id}`] : value;
        }
        deviceConfigParam[`equip_${item.id}`] = value;
        content.push(
          <div key={item.id} className="topo-property-common">
            <div className="property-label-name" title={item.displayName}>
              {item.displayName}：
            </div>
            <Editable
              value={value}
              onChange={e => this.onAttributeChange(`equip_${item.id}`, e)}
              showOkCancel={false}
              style={{ width: '126px', marginLeft: '10px' }}
              innerValueStyle={{ width: '126px' }}
              placeholder={'请输入'}
            />
          </div>
        );
      });
    return content;
  };

  /**
   *
   *提交图片至后台
   * @memberof UpLoadImg
   */
  saveImgFileAction = (binaryImg, name) => {
    let { equipmentId } = this.props;
    let imgInfo = { id: equipmentId, binaryImg: binaryImg, imgName: name };
    addeEditEqpImgAction(imgInfo).then(result => {});
  };

  updateEquipmentName = (key, newName) => {
    let { currentDeviceConfig, showProperty } = this.props;
    let equipment = currentDeviceConfig ? currentDeviceConfig.eqp : undefined;
    if (equipment) {
      let { config, getSubgraphData, subviewId, nodeId } = this.props;
      let oldName = this.name;
      this.name = newName;
      let propertyContent = config.data;
      let newConfig = {
        label: newName,
        type: config.type,
        data: propertyContent,
        style: config.style
      };
      let id = propertyContent.id;
      let postData = { id, name: newName, nodeId, config: JSON.stringify(newConfig) };
      //提交后台
      updateEquipmentNameAction(postData).then(res => {
        if (res === -1) {
          message.danger('设备名称重复！');
          this.name = oldName;
          // this.setState({ attributes: this.state.attributes });
        } else {
          getSubgraphData(subviewId, nodeId);
          showProperty(nodeId);
        }
      });
    }
  };

  render() {
    let { collapseKey } = this.state;
    let { currentDeviceConfig } = this.props;
    let equipment = currentDeviceConfig ? currentDeviceConfig.eqp : undefined;
    let device = currentDeviceConfig ? currentDeviceConfig.device : undefined;
    let defaultImg = equipment && equipment.logo ? `${OltSerUrl.fetchDeviceImg}/icon/${equipment.logo}` : undefined;
    return (
      <div className="topo-config-basic-root">
        <Collapse activeKey={collapseKey} onChange={key => this.onChangeCollapseSize(key)}>
          <Panel showArrow={false} header={this.getCollapseHead('设备信息', '1')} key="1">
            <div className="device-basic-info">
              <div className="topo-basic-name">
                <div className="property-label-name">设备名称：</div>
                <Editable
                  value={equipment && equipment.name}
                  onChange={e => this.updateEquipmentName('name', e)}
                  showOkCancel={false}
                  style={{ width: '140px', marginLeft: '10px' }}
                  innerValueStyle={{ width: '140px' }}
                  placeholder={'请输入'}
                />
              </div>
              <div className="topo-basic-descr">
                <div className="property-label-name">设备描述：</div>
                <div className="property-normal-label" title={equipment && equipment.descr}>
                  {equipment && equipment.descr}
                </div>
              </div>
              <div className="topo-basic-icon">
                <TopoUpLoadIcon
                  enable
                  style={{ top: '-18px', 'max-width': '130px', 'max-height': '130px' }}
                  setImgFile={this.setImgFile}
                  defaultImg={defaultImg}
                />
              </div>
              <div className="topo-basic-catalog">
                <div className="property-label-name">设备类别：</div>
                <div className="property-normal-label" title={stringUtil(deviceCategoryEnum, device && device.type)}>
                  {stringUtil(deviceCategoryEnum, device && device.type)}
                </div>
              </div>
              <div className="topo-basic-industry">
                <div className="property-label-name">所属行业：</div>
                <div className="property-normal-label" title={device && device.equipTemplateIndustry.name}>
                  {device && device.equipTemplateIndustry.name}
                </div>
              </div>
              <div className="topo-type-name">
                <div className="property-label-name">设备类型：</div>
                <div className="property-normal-label" title={device && device.name}>
                  {device && device.name}
                </div>
              </div>
              <div className="topo-basic-model">
                <div className="property-label-name">备注：</div>
                <div className="property-normal-label" title={device && device.model}>
                  {device && device.model}
                </div>
              </div>
            </div>
          </Panel>
          <Panel showArrow={false} header={this.getCollapseHead('设备属性', '2')} key="2">
            <div className="device-basic-property">{this.getDeviceConfigInfo()}</div>
          </Panel>
        </Collapse>
      </div>
    );
  }
}

DeviceBasicInfoConfig.propTypes = {
  getImgPath: PropTypes.func,
  currentDeviceConfig: PropTypes.object,
  getSubgraphData: PropTypes.func,
  subviewId: PropTypes.string,
  nodeId: PropTypes.string,
  equipmentId: PropTypes.number,
  config: PropTypes.object,
  showProperty: PropTypes.func
};

export default DeviceBasicInfoConfig;
