import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { PubSub } from 'ray-eventpool';
import { OltSerUrl } from '../../../consts/urlConsts';
import { AmosFetch } from '../../../utils/processor';
import dt2react from 'dt2react';
import './addDevicePanel.scss';
import AddDevicePanelHead from './AddDevicePanelHead';
import AddDevicePanelBody from './AddDevicePanelBody';
import InterfacePropertyPanel from './propertyPanel/InterfacePropertyPanel';
import QuotaPropertyPanel from './propertyPanel/QuotaPropertyPanel';
import { CONFIG_PANEL_SHOW_TOPIC,CONFIG_PANEL_HIDE_TOPIC } from './../common/ActionConf';
import { addEditEquipmentAction,fetchAllTemplatOrEqpQuotaPropertyAction } from './../../../services/deviceService';
import OnlineTest from './../onlineTestManger/OnlineTest';
import { message } from 'amos-framework';

/**
 *
 *
 * @class AddDevicePanel
 * @extends {Component}
 */
class AddDevicePanel extends Component {
  constructor(props){
    super(props);
    this.interfaceCellStatus = {};
    this.quotaCellStatus = {};
    this.interfacePropertys = {};
    this.quotaSelected = {};
    this.equipmentProperty = {};
    this.basicInfo = {};
    this.taskParam = {};
    this.eqpThreshold = {};
    this.imgFile = {};//图片名称
    this.statusCount = 0;//当前已更新的数据采集个数
    this.statusSum = 0;//数据采集个数
    this.state = {
      configType: undefined,
      currentId: undefined,
      quotaSelectedStatus: undefined,
      refreshCellStatus: false,//是否要强制更新数据采集状态
      exprotButton:"none"
    };
  }
  componentWillMount() {

  }

  componentDidMount(){
    this.pubsub_open = PubSub.subscribe(CONFIG_PANEL_SHOW_TOPIC.configPanelShow, (e, { type,id,intfc,capacity,onlinTestSwich,intfcList,quotaList,quotaSelected,status }) => {
      if (type === 3) {
        //测试界面需要重新获取数据
        let { equipment,device } = this.props;
        this.fetchAllTemplatOrEqpQuotaProperty(device.id, equipment ? equipment.id : 0);
        this.setState({ refreshCellStatus: true });
      }
      this.setState({ configType: type,currentId: id,intfc,capacity,onlinTestSwich,intfcList,quotaList,quotaSelected,quotaSelectedStatus: status });
    });
    this.pubsub_close = PubSub.subscribe(CONFIG_PANEL_HIDE_TOPIC.configPanelHide, (e, { type,id }) => {
      this.closePanel();
    });
    let { equipment,device } = this.props;
    this.fetchAllTemplatOrEqpQuotaProperty(device.id, equipment ? equipment.id : 0);
  }

  componentWillReceiveProps(nextProps) {
    let { equipment,device } = this.props;
    if (device.id !== nextProps.device.id || equipment && nextProps.equipment && ( equipment.id !== nextProps.equipment.id )) {
      this.fetchAllTemplatOrEqpQuotaProperty(nextProps.device.id, nextProps.equipment ? nextProps.equipment.id : 0);
    }
  }

  componentWillUnmount() {
    PubSub.unsubscribe(this.pubsub_open);
    PubSub.unsubscribe(this.pubsub_close);
  }

  getConfigPanelByType = () => {
    let { configType,currentId,intfc,capacity,onlinTestSwich,intfcList,quotaList } = this.state;
    let content = [];
    if (configType === 1) {
      this.openPanel();
      content.push(<InterfacePropertyPanel
        key={'interface'}
        updateInterfacePropertyCell={this.updateInterfacePropertyCell}
        id={currentId}
        intfc={intfc}
        getImgPath={this.getImgPath}
        {...this.props}
      />);
    } else if (configType === 2) {
      this.openPanel();
      content.push(<QuotaPropertyPanel
        key={'quota'}
        updateQuotaPropertyCell={this.updateQuotaPropertyCell}
        updateQuotaTaskCell={this.updateQuotaTaskCell}
        updateInterfacePropertyCell={this.updateInterfacePropertyCell}
        updateCapacityThresholdInfo={this.updateCapacityThresholdInfo}
        id={currentId}
        capacity={capacity}
        device={this.props.device}
        getImgPath={this.getImgPath}
        taskParam={this.taskParam}
        eqpThreshold={this.eqpThreshold}
        quotaSelectedStatus={this.state.quotaSelectedStatus}
        resetStatus={this.resetStatus}
        {...this.props}
      />);
    } else if (configType === 3) {
      this.openPanel();
      content.push(<OnlineTest
        key={'test'}
        onlinTestSwich={onlinTestSwich}
        intfcList={intfcList}
        quotaList={quotaList}
        quotaSelected={this.quotaSelected}
        saveEquipmnet={this.saveEquipmnet}
        exprotButton = {this.state.exprotButton}
      />);
    }
    return content;
  }

  getImgPath = (index,collapseKey) => {
    let styleName;
    if (collapseKey.includes(index)) {
      styleName = 'rotate-negative-ninety';
    } else {
      styleName = 'rotate-ninety';
    }
    return (<img src={require('./../../../assets/iot/deviceManage/arrow.png')} alt='' className={styleName} />);
  }

  openPanel = () => {
    let mainPanel = this.mainContent;
    mainPanel && dt2react.addStyle(mainPanel,'width','calc(100% - 300px)');
  }

  closePanel = () => {
    let mainPanel = this.mainContent;
    mainPanel && dt2react.addStyle(mainPanel,'width','100%');
  }

  updateInterfaceCellStatus = (key,value) => {
    let interfaceCellStatus = this.interfaceCellStatus;
    interfaceCellStatus[key] = value;
    this.interfaceCellStatus = interfaceCellStatus;
  }

  updateQuotaCellStatus = (key,value) => {
    let quotaCellStatus = this.quotaCellStatus;
    quotaCellStatus[key] = value;
    this.quotaCellStatus = quotaCellStatus;
  }

  updateQuotaPropertyCell = (key,value) => {
    let quotaSelected = this.quotaSelected;
    quotaSelected[key] = value;
    this.quotaSelected = quotaSelected;
  }

  updateInterfacePropertyCell = (key,value) => {
    let interfacePropertys = this.interfacePropertys;
    interfacePropertys[key] = value;
    this.interfacePropertys = interfacePropertys;
  }

  updateDevicePropertyCell = (equipmentProperty) => {
    this.equipmentProperty = equipmentProperty;
  }

  updateBasicInfo = (basicInfo) => {
    this.basicInfo = basicInfo;
  }

  updateQuotaTaskCell = (key,value) => {
    let taskParam = this.taskParam;
    taskParam[key] = value;
    this.taskParam = taskParam;
  }

  updateCapacityThresholdInfo = (key,value) => {
    let eqpThreshold = this.eqpThreshold;
    eqpThreshold[key] = value;
    this.eqpThreshold = eqpThreshold;
  }

  /**
   * 设置图片
   *
   * @memberof AddDevice
   */
  setImgFile = (imgFile) => {
    this.imgFile = imgFile;
  }

  /**
   *
   *保存图片
   * @memberof UpLoadImg
   */
  saveEquipmentAction = () => {
    let basicInfo = this.basicInfo;
    if (basicInfo.name === undefined || basicInfo.name.trim() === '') {
      message.danger('请输入设备名称');
      return;
    }
    const reader = new FileReader();
    reader.addEventListener('load', () => this.upLoadImgToSave(reader.result));
    let imgFile = this.imgFile;
    if (JSON.stringify(imgFile) === '{}') {
      let imgInfo = { 'binaryImg': null,'imgName': null };
      this.saveEquipmnet(imgInfo);
    } else {
      reader.readAsBinaryString(this.imgFile);
    }
  };

  /**
   *
   *提交图片至后台
   * @memberof UpLoadImg
   */
  upLoadImgToSave = (binaryImg) => {
    let name = this.imgFile.name;
    let imgInfo = { 'binaryImg': binaryImg,'imgName': name };
    this.saveEquipmnet(imgInfo);
  };

  getEnableIntfcIds = () => {
    let selIntfcIds = [];
    let interfaceCellStatus = this.interfaceCellStatus;
    for (let i in this.interfaceCellStatus) {
      if (interfaceCellStatus[i]) {
        selIntfcIds.push(i);
      }
    }
    return selIntfcIds;
  }

  getEnableCapacityfcIds = () => {
    let selCpblIds = [];
    let quotaCellStatus = this.quotaCellStatus;
    for (let i in this.quotaCellStatus) {
      if (quotaCellStatus[i]) {
        selCpblIds.push(i);
      }
    }
    return selCpblIds;
  }

  getEnableAttriSourceId = () => {
    let sid;
    let {attributes} = this.props.device;
      attributes.map((item)=>{
      let value = item.name;
      if (value && value === 'sourceId') {
        sid= this.equipmentProperty[`equip_${item.id}`];
        return sid;
      }    
    });
   return sid;
  }
  saveEquipmnet = (imgInfo,flag) => {
    console.table(this.interfaceCellStatus);//Map<接口ID,是否启用>
    console.table(this.quotaCellStatus);//Map<指标ID,是否启用>

    console.table(this.interfacePropertys);//Map<接口属性ID,接口属性值>
    console.table(this.quotaSelected);//Map<指标ID,List<勾选的指标属性ID>>
    console.table(this.equipmentProperty);//Map<设备属性ID,设备属性值>
    console.table(this.basicInfo);//name,descr,iconName,iconBanaryString
    console.table(this.eqpThreshold);//能力属性上下限
    let basicInfo = this.basicInfo;
    let taskParam = this.taskParam;
    let threshold = this.eqpThreshold;
    Object.assign(basicInfo,imgInfo);
    let { equipment } = this.props;
    if (equipment && equipment.id) {
      Object.assign(basicInfo,{ id: equipment.id });
    }
    let propertyMap = {
      sid:this.getEnableAttriSourceId(),
      selIntfcIds: this.getEnableIntfcIds(),
      selCpblIds: this.getEnableCapacityfcIds(),
      quotaSelected: this.quotaSelected,
      ...this.interfacePropertys,
      ...this.equipmentProperty
    };
    let data = {
      propertyMap,
      basicInfo,
      taskParam,
      threshold
    };
    if (flag){
      this.todoTest(data,flag);
    } else {
      addEditEquipmentAction(data).then(data => {
        if (data === null) {
          message.danger('设备名称重复');
        } else {
          message.success('保存成功');
          this.imgFile = {};
          let { updateMainView,device,resourceFlag,pageConfig } = this.props;
          updateMainView({ flag: '3',device,resourceFlag,equipment: data,pageConfig });
          // updateMainView({ flag: '4',device,resourceFlag,equipment: data });
        }
      });
    }
  }

  todoTest=(data,flag)=>{
    let url = `${OltSerUrl.ToDoDeviceTest}/${flag}`;
      AmosFetch.post(url,{ data }).then(res => {
        if (res.ok) {
          return res.json();
        }
        else
        {
          throw new Error('从服务端获取数据失败！');
        }
      }).then((data)=>{
        if (data.result === 'SUCCESS'){
          //this.setState({exprotButton:"inline"})
          console.log(data);
        }
        else
        {
          message.info(data.message);
        }
      });
    
  }

  fetchAllTemplatOrEqpQuotaProperty = (devId,eqpId) => {
    fetchAllTemplatOrEqpQuotaPropertyAction(devId,eqpId).then(data => {
      if (data !== null) {
        let threshold = data.threshold;
        let property = data.property;
        //默认指标
        let content = {};
        property.map(item => {
          let cpblId = item.cpblId;
          let tempId = content[cpblId];
          if (tempId === undefined) {
            tempId = [];
          }
          tempId.push(item.id);
          content[cpblId] = tempId;
        });
        this.quotaSelected = content;
        //默认门限
        threshold.map(item => {
          let infoKey = `${item.cpblId}_${item.cpblPropertyId}`;
          let thresholdData = {
            upper: item.maxValue,
            lower: item.minValue
          };
          let eqpThreshold = this.eqpThreshold;
          eqpThreshold[infoKey] = thresholdData;
          this.eqpThreshold = eqpThreshold;
        });
      }
    });
  }

  resetStatus = () => {
    this.setState({ quotaSelectedStatus: undefined });
  }

  //还原未保存的数据采集选中状态
  changeRefreshCellStatus = () => {
    let statusCount = this.statusCount;
    let statusSum = this.statusSum * 2 - 1;
    if (statusCount < statusSum) {
      statusCount = statusCount + 1;
      this.statusCount = statusCount;
    } else {
      //已处理的数量等于总数时重置状态
      this.setState({ refreshCellStatus: !this.state.refreshCellStatus });
      this.statusCount = 0;
    }
  }

  //设置数据采集总数
  setSumValue = (sum) => {
    this.statusSum = sum;
  }

  render() {
    return (
      <div className='add-device-panel-root'>
        <div className='add-device-panel' ref={node => this.mainContent = node} >
          <div className='add-device-panel-top'>
            <AddDevicePanelHead saveEquipmentAction={this.saveEquipmentAction} {...this.props} />
          </div>
          <div className='add-device-panel-body' >
            <AddDevicePanelBody
              updateInterfaceCellStatus={this.updateInterfaceCellStatus}
              updateQuotaCellStatus={this.updateQuotaCellStatus}
              updateDevicePropertyCell={this.updateDevicePropertyCell}
              updateBasicInfo={this.updateBasicInfo}
              setImgFile={this.setImgFile}
              interfaceStatus={this.interfaceCellStatus}
              quotaCellStatus={this.quotaCellStatus}
              quotaSelected={this.quotaSelected}
              updateQuotaTaskCell={this.updateQuotaTaskCell}
              refreshCellStatus={this.state.refreshCellStatus}
              changeRefreshCellStatus={this.changeRefreshCellStatus}
              saveEquipmnet={this.saveEquipmentAction}
              setSumValue={this.setSumValue}
              {...this.props}
            />
          </div>
        </div>
        <div className='add-device-config-panel'>
          {this.getConfigPanelByType()}
        </div>
      </div>
    );
  }
}

AddDevicePanel.propTypes = {
  updateMainView: PropTypes.func,
  device: PropTypes.object,
  resourceFlag: PropTypes.string,
  equipment: PropTypes.object,
  enable: PropTypes.bool,
  pageConfig: PropTypes.object
};

AddDevicePanel.defaultProps = {
  enable: true
};

export default AddDevicePanel;
