import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Editable, Input, Collapse, Checkbox, Row, Col } from 'amos-framework';
import { Select } from 'amos-antd';
import { PubSub } from 'ray-eventpool';
import { CONFIG_PANEL_HIDE_TOPIC, SELECT_STATUS_CHANGE_TOPIC } from './../../common/ActionConf';
import { monitorTypeArr, periodArr } from './../../common/TaskEnum';
import { fetchTemplatOrEqpQuotaPropertyAction, fetchCapacityInterfaceAction } from './../../../../services/deviceService';
import ThresholdInput from './ThresholdInput';
import ThresholdName from './ThresholdName';

const Panel = Collapse.Panel;
const CheckboxGroup = Checkbox.Group;
const Option = Select.Option;

/**
 *
 *
 * @class QuotaPropertyPanel
 * @extends {Component}
 */
class QuotaPropertyPanel extends Component {
  constructor(props) {
    super(props);
    this.propertyId = []; //当前id范围
    this.quotaParam = {}; //选中的能力属性ID
    this.state = {
      collapseKey: ['1', '2', '3'],
      propertyList: {},
      interfaceList: {},
      interfaceProperty: {}, //接口属性键值对
      updateFlag: false
    };
  }

  componentDidMount() {
    let { id, equipment } = this.props;
    this.getCapacityInfos(equipment ? equipment.id : 0, id);
  }

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

  onAttributeChange = () => {};

  onChangeChecked = params => {
    let propertyId = this.propertyId;
    let filterQuotaParam = [];
    params.map(item => {
      if (propertyId !== undefined && propertyId.includes(item)) {
        filterQuotaParam.push(item);
      }
    });
    let { updateQuotaPropertyCell, id } = this.props;
    let quotaParam = this.quotaParam;
    updateQuotaPropertyCell(id, filterQuotaParam);
    if ((quotaParam[id] === undefined || quotaParam[id].length === 0) && filterQuotaParam.length > 0) {
      this.changeStatus();
    }
    quotaParam[id] = filterQuotaParam;
    this.quotaParam = quotaParam;
    this.setState({ updateFlag: false });
  };

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

  onMonitorTypeChange = value => {
    let { taskParam } = this.props;
    let { updateQuotaTaskCell, id } = this.props;
    taskParam[id].monitorPeriod = value;
    updateQuotaTaskCell(id, taskParam[id]);
    this.setState({ updateFlag: false });
  };

  onInterfaceAttributeChange = (key, value) => {
    let { interfaceProperty } = this.state;
    let { updateInterfacePropertyCell } = this.props;
    interfaceProperty[key] = value;
    updateInterfacePropertyCell(key, value);
    this.setState({ interfaceProperty });
  };

  getInterfaceBaseContent = () => {
    let content = [];
    let { id } = this.props;
    let { interfaceList } = this.state;
    let intfc = interfaceList[id];
    intfc &&
      content.push(
        <div key={'interface-base'} className="property-config-common">
          <div title={'通讯方式'} className="property-key-style">
            {'通讯方式'}：
          </div>
          <div style={{ width: '136px', float: 'left' }}>
            <div className="property-normal-label" title={intfc.name}>
              {intfc.name}
            </div>
          </div>
        </div>
      );
    return content;
  };

  getInterfaceAttributesEditContent = () => {
    let content = [];
    let { id, equipment, enable, updateInterfacePropertyCell, capacity } = this.props;
    let { interfaceProperty, interfaceList } = this.state;
    let intfc = interfaceList[id];
    content.push(
      <div key={'title'} className="interface-property-title">
        通讯参数
      </div>
    );
    intfc &&
      intfc.attributes.map(item => {
        let intfcKey = `cpbl_intfc_${capacity.id}_${intfc.id}_${item.id}`;
        let value = interfaceProperty[intfcKey];
        if (value === undefined) {
          if (equipment !== undefined && equipment.id !== undefined) {
            let param = equipment.cfgParamMap;
            value = param[intfcKey] ? param[intfcKey] : value;
          } else {
            value = item.valueStr;
          }
        }
        interfaceProperty[intfcKey] = value;
        updateInterfacePropertyCell(intfcKey, value);
        content.push(
          <div key={item.id} className="property-config-common">
            <div className="property-key-style" title={item.displayName}>
              {item.displayName}：
            </div>
            <div style={{ width: '136px', float: 'left' }}>
              {enable ? (
                <Editable
                  value={value ? value : item.valueStr}
                  onChange={e => this.onInterfaceAttributeChange(intfcKey, e)}
                  showOkCancel={false}
                  style={{ width: '136px' }}
                  placeholder={'请输入'}
                  innerValueStyle={{ width: '136px' }}
                />
              ) : (
                <div className="property-normal-label" title={value ? value : item.valueStr}>
                  {value ? value : item.valueStr}
                </div>
              )}
            </div>
          </div>
        );
      });
    return content;
  };

  getAttributesEditContent = () => {
    let content = [];
    let checkBoxContent = [];
    let { updateQuotaPropertyCell, id, equipment, capacity, enable, quotaSelectedStatus, resetStatus, updateCapacityThresholdInfo, eqpThreshold } = this.props;
    let { propertyList } = this.state;
    let quotaParam = this.quotaParam;
    let tempParam = []; //判断需要选中的值
    if (quotaParam[id] === undefined) {
      //首次打开，界面无该能力的缓存
      if (equipment !== undefined && equipment.id !== undefined) {
        //编辑时
        let param = equipment.cfgParamMap.quotaSelected;
        if (param && param[capacity.id] !== undefined) {
          tempParam = param[capacity.id];
        }
      } else {
        //新增时，默认所有
        propertyList[id] &&
          propertyList[id].map(item => {
            tempParam.push(item.id);
          });
        updateQuotaPropertyCell(id, tempParam);
      }
      if (tempParam.length !== 0) {
        quotaParam[id] = tempParam;
        this.quotaParam = quotaParam;
      }
    } else {
      //界面有该能力的缓存，直接用缓存
      tempParam = quotaParam[id];
    }
    //添加checkbox
    let propertyId = [];
    let selectedItem = [];
    //控制第一个的样式
    let count = 0;
    propertyList[id] &&
      propertyList[id].map(item => {
        propertyId.push(item.id);
        if (item.isUser) {
          selectedItem.push(item.id);
        }
        let textStyle = 'threshold-name-root';
        if (count === 0) {
          textStyle = 'threshold-name-first-root';
        }
        count = count + 1;
        checkBoxContent.push(<ThresholdName key={'title'} textStyle={textStyle} name={item.displayName} disabled={!enable} value={item.id} />);
        checkBoxContent.push(<Checkbox key={item.id} disabled={!enable} value={item.id} />);
        let isHidden = true;
        /**
         * type: 1表示变量，2表示常量，3表示标签，4输出
         * dataType:1表示整型，2表示浮点型，3表示布尔型，4表示枚举，5表示字符串，6表示密码
         */
        if ((item.type === 1 || item.type === 4) && (item.dataType === 1 || item.dataType === 2)) {
          isHidden = false;
        }
        //如果保存过，使用保存的值，否则使用属性的默认值
        let infoKey = `${capacity.id}_${item.id}`;
        let thresholdValue = eqpThreshold[infoKey];
        if (thresholdValue === undefined) {
          thresholdValue = {};
          thresholdValue.upper = item.maxValue;
          thresholdValue.lower = item.minValue;
        }
        checkBoxContent.push(
          <ThresholdInput
            updateCapacityThresholdInfo={updateCapacityThresholdInfo}
            unit={item.unit}
            key={'threshold'}
            disabled={!enable}
            value={item.id}
            upper={thresholdValue.upper}
            lower={thresholdValue.lower}
            infoKey={infoKey}
            isHidden={isHidden}
          />
        );
      });
    this.propertyId = propertyId; //存贮当前id范围
    //---------------------------------------------
    //quotaSelectedStatus有值，说明是能力加减图片单击事件
    //需要同步处理checkbox的选择状态
    //---------------------------------------------
    if (quotaSelectedStatus) {
      let propertyId = this.propertyId;
      let filterQuotaParam = [];
      tempParam = [];
      propertyList[id] &&
        propertyList[id].map(item => {
          tempParam.push(item.id);
          if (propertyId !== undefined && propertyId.includes(item.id)) {
            filterQuotaParam.push(item.id);
          }
        });
      updateQuotaPropertyCell(id, filterQuotaParam);
      quotaParam[id] = filterQuotaParam;
      this.quotaParam = quotaParam;
      resetStatus();
    } else if (quotaSelectedStatus === false) {
      tempParam = [];
      updateQuotaPropertyCell(id, []);
      quotaParam[id] = [];
      this.quotaParam = quotaParam;
      resetStatus();
    }
    //---------------------------------------------
    content.push(
      <div key={'group'} className="template-config-common">
        <CheckboxGroup selects={tempParam} vertical isCheckall={enable} onChange={this.onChangeChecked}>
          {checkBoxContent}
        </CheckboxGroup>
      </div>
    );
    return content;
  };

  getCapacityInfos = (eqpId, id) => {
    fetchCapacityInterfaceAction(id).then(data => {
      if (data !== null) {
        let { interfaceList } = this.state;
        interfaceList[id] = data;
        this.setState({ interfaceList });
      }
    });
    fetchTemplatOrEqpQuotaPropertyAction(eqpId, id).then(data => {
      if (data !== null) {
        let { propertyList } = this.state;
        propertyList[id] = data;
        this.setState({ propertyList });
      }
    });
  };

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

  getTaskContent = () => {
    let content = [];
    let { capacity, enable, taskParam, id } = this.props;
    let monitorPeriod = taskParam[id].monitorPeriod === 0 ? undefined : taskParam[id].monitorPeriod;
    let monitorType = capacity.monitorType;
    content.push(
      <div key={'type'} className="property-config-common">
        <Row>
          <Col span={6} offset={0} className="property-key-style">
            {'监测方式：'}
          </Col>
          <Col span={16} offset={0} style={{ width: '136px' }}>
            <Select value={capacity.monitorType} style={{ width: 136 }} disabled placeholder="监测方式">
              {monitorTypeArr.map(data => (
                <Option key={data.value} value={data.value}>
                  {data.title}
                </Option>
              ))}
            </Select>
          </Col>
        </Row>
      </div>
    );
    if (monitorType == 1) {
      content.push(
        <div key={'task'} className="property-config-common">
          <Row>
            <Col span={6} offset={0} className="property-key-style">
              {'采集周期：'}
            </Col>
            <Col span={16} offset={0} style={{ width: '136px' }}>
              <Select disabled={!enable} value={monitorPeriod} style={{ width: 136 }} placeholder="请选择" onSelect={this.onMonitorTypeChange}>
                {periodArr.map(data => (
                  <Option key={data.value} value={data.value}>
                    {data.title}
                  </Option>
                ))}
              </Select>
            </Col>
          </Row>
        </div>
      );
    }

    return content;
  };

  closeQuotaPanel = () => {
    PubSub.publish(CONFIG_PANEL_HIDE_TOPIC.trigger, {});
  };

  changeStatus = () => {
    let { capacity } = this.props;
    PubSub.publish(SELECT_STATUS_CHANGE_TOPIC.trigger, {
      cpbId: capacity.id,
      status: true
    });
  };

  render() {
    let { collapseKey } = this.state;
    let { capacity } = this.props;
    return (
      <div className="quota-property-root">
        <div className="quota-property-head">
          <div className="common-property-text">采集模型</div>
          <div className="del-button-view" onClick={this.closeQuotaPanel}>
            关闭
          </div>
        </div>
        <div className="quota-property-content">
          <div className="quota-property-title">{capacity.name}</div>
          <Collapse activeKey={collapseKey} onChange={key => this.onChangeCollapseSize(key)}>
            <Panel showArrow={false} header={this.getCollapseHead('设备接口', '1')} key="1">
              <div className="interface-base-info">{this.getInterfaceBaseContent()}</div>
              <div className="interface-property-info">{this.getInterfaceAttributesEditContent()}</div>
            </Panel>
            <Panel className="capacity-property-info" showArrow={false} header={this.getCollapseHead('采集指标', '2')} key="2">
              {this.getAttributesEditContent()}
            </Panel>
            <Panel showArrow={false} header={this.getCollapseHead('监听方式', '3')} key="3">
              <div className="interface-property-info">{this.getTaskContent()}</div>
            </Panel>
          </Collapse>
        </div>
      </div>
    );
  }
}

QuotaPropertyPanel.propTypes = {
  getImgPath: PropTypes.func,
  id: PropTypes.number,
  updateQuotaPropertyCell: PropTypes.func,
  device: PropTypes.object,
  equipment: PropTypes.object,
  capacity: PropTypes.object,
  updateQuotaTaskCell: PropTypes.func,
  enable: PropTypes.bool,
  taskParam: PropTypes.object,
  quotaSelectedStatus: PropTypes.bool,
  resetStatus: PropTypes.func,
  updateInterfacePropertyCell: PropTypes.func,
  updateCapacityThresholdInfo: PropTypes.func,
  eqpThreshold: PropTypes.object
};

export default QuotaPropertyPanel;
