import React, { Component } from 'react';
import { browserHistory } from 'amos-react-router';
import { parseText } from 'amos-tool';
import { PubSub } from 'ray-eventpool';
import { TREE_FETCH_TOPIC } from './ruleStatge/modelConf/stageConf';
import { pathMapping } from './../../routes/customRoutes';
import RuleLibrary from './ruleLibrary/RuleLibrary';
import { rulelibListAction } from './../../services/ruleDesignService';

class RuleDesign extends Component {
  constructor(props) {
    super(props);
    this.param = {};
    this.state = {
      ruleLib: []
    };
  }

  componentDidMount() {
    this.reload();
    this.pubsub_update = PubSub.subscribe(TREE_FETCH_TOPIC.treeFetch, (topic, { id }) => {
      if (id) {
        this.param.orgCode = id;
        this.reload();
      }
    });
  }

  componentWillUnmount() {
    PubSub.unsubscribe(this.pubsub_update);
  }

  /**
   * 双击进入规则库界面
   */
  onPushToRule = obj => {
    browserHistory.push(parseText(pathMapping.ruledeploy, { libkey: obj.id }));
  };

  /**
   * 查询
   */
  onSearchRuleLib = e => {
    let reqParam = this.param;
    Object.assign(reqParam, { name: e.target.value });
    rulelibListAction(reqParam).then(d => {
      this.setState({
        ruleLib: d.content
      });
    });
  };

  reload = () => {
    rulelibListAction(this.param).then(d => {
      this.setState({
        ruleLib: d.content
      });
    });
  };

  render() {
    const { ruleLib } = this.state;
    return (
      <div className="rule-lib-container">
        <RuleLibrary onPushToRule={this.onPushToRule} ruleLib={ruleLib} reload={this.reload} onSearchRuleLib={this.onSearchRuleLib} />
      </div>
    );
  }
}

export default RuleDesign;
