import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Connect } from 'amos-framework';
import { Polylines as Lines } from 'amos-3d';
import { omit } from 'amos-tool';
import { initView3DLinkAction } from './../../../services/3dService';
import { eventTopics } from './../consts';
import conf from './../conf';

const eventConnect = Connect.eventConnect;

/**
 * Link 线路
 *
 * @class Polylines
 * @extends {Component}
 */
@eventConnect
class Polylines extends Component {

  static propTypes = {
    toggleRoad: PropTypes.bool,
    subscribe: PropTypes.func
  };

  constructor(props) {
    super(props);
    this.state = {
      links: []
    };
    this.asyncLoadLink();
  }

  componentDidMount() {
    this.props.subscribe(eventTopics.linkdata_change, (topic, data) => {
      this.changeLinkData(data);
    });
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.props.toggleRoad !== prevProps.toggleRoad){
      this.asyncLoadLink();
    }
  }

  asyncLoadLink = () => {
    const { toggleRoad } = this.props;
    if (toggleRoad){
      initView3DLinkAction().then(d => {
        this.changeLinkData(d);
      });
    } else {
      this.changeLinkData([]);
    }
  }

  changeLinkData = (links) => {
    this.setState({
      links
    });
  }

  dataFmt = (raw) => {
    return {
      linePath: raw.linkPath
    };
  }

  render() {
    const { links } = this.state;
    const restProps = omit(this.props, ['toggleRoad']);
    return (
      <Lines
        lineType="FatLine"
        fatlineProps={conf.link.fatlineProps}
        selectedColor={conf.link.selectColor}
        lines={links}
        dataFmt={this.dataFmt}
        {...restProps}
      />
    );
  }
}

export default Polylines;
