import React from "react";
import { Tabs, Spin } from "antd";
import classNames from "classnames";

import HomePage from "../../layouts/HomePage";
import styles from "./index.less";

const { TabPane } = Tabs;

export default class RootTabs extends React.Component {
  constructor(props) {
    super(props);
    this.newTabIndex = 0;
    const panes = [];
    this.state = {
      activeKey: 0,
      panes
    };
  }

  onChange = activeKey => {
    this.setState({ activeKey });
    this.props.onTabChange([activeKey]);
    this.antTabsBarStyle();
  };
  onEdit = (targetKey, action) => {
    this[action](targetKey);
  };
  antTabsBarStyle = newstyles => {
    // if (this.state.panes.length = 0) return;
    if (!newstyles) {
      document.querySelector(".ant-tabs-bar").style = {};
      document.querySelector(".ant-tabs-bar").style.transition = "0s";
      return;
    }
    for (const style in newstyles) {
      document.querySelector(".ant-tabs-bar").style[style] = newstyles[style];
      document.querySelector(".ant-tabs-bar").style.transition = "0s";
    }
  };
  add = (title, content, key) => {
    const { panes } = this.state;
    const activeKey = key;
    const samePanes = this.state.panes.filter(pane => pane.key === key);
    if (samePanes.length > 0) {
      this.setState({ panes, activeKey });
      return;
    }
    panes.push({ title, content, key });
    this.setState({ panes, activeKey });
  };
  remove = targetKey => {
    let { activeKey } = this.state;
    let lastIndex;
    this.state.panes.forEach((pane, i) => {
      if (pane.key === targetKey) {
        lastIndex = i - 1;
      }
    });
    const panes = this.state.panes.filter(pane => pane.key !== targetKey);
    if (lastIndex >= 0 && activeKey === targetKey) {
      activeKey = panes[lastIndex].key;
    }
    this.setState({ panes, activeKey });
    this.props.onTabChange([activeKey]);
  };
  render() {
    if (this.state.panes.length > 0) {
      return (
        <Tabs
          className={styles.antTabs}
          onChange={this.onChange}
          activeKey={this.state.activeKey}
          type="editable-card"
          onEdit={this.onEdit}
        >
          {this.state.panes.map(pane => (
            <TabPane tab={pane.title} key={pane.key} closable={pane.closable}>
              <pane.content />
            </TabPane>
          ))}
        </Tabs>
      );
    } else {
      return <HomePage />;
    }
  }
}
