import React from 'react';
import { message, Modal, Form, Input } from 'antd';
import { Menu, Toolbar } from '@antv/x6-react-components';
import '@antv/x6-react-components/es/menu/style/index.css';
import '@antv/x6-react-components/es/toolbar/style/index.css';
// import { MainAreaWidget, ReactWidget } from '@jupyterlab/apputils';
// import { JupyterFrontEnd } from '@jupyterlab/application';
// import { dagDataIcon } from './icons';
import {
  ZoomInOutlined,
  ZoomOutOutlined,
  ToolOutlined,
  PlayCircleOutlined,
  SaveOutlined
} from '@ant-design/icons';
import { DagToData } from './utils';
// import MediateDataTable from './MediateDataTable';
import { uploadFile } from './request';

const Item = Toolbar.Item; // eslint-disable-line
const Group = Toolbar.Group; // eslint-disable-line

export default class ToolBar extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      modalVisible: false,
      packageData: ''
    };
  }

  showModal = () => {
    this.setState({ modalVisible: true });
  };

  submitEdit = () => {
    const node = this.props.graph.getSelectedCells()[0];
    node.data.packageData = this.state.packageData;
    this.setState({ modalVisible: false });
  };

  onClick = (name: string) => {
    // const zoomNumber = this.props.graph.zoom()
    switch (name) {
      case 'save':
        this.props.saveGraph(DagToData(this.props.graph, this.props.dagId));
        message.success('保存成功！');
        break;
      case 'zoomOut':
        this.props.graph.zoom(-0.1, {
          center: { x: 0, y: 0 }
        });
        break;
      case 'zoomIn':
        this.props.graph.zoom(0.1, {
          center: { x: 0, y: 0 }
        });
        break;
      default:
    }
  };

  async uploadDagFile() {
    const text = this.props.context.current;
    const filename = text.path.split('/').pop();
    const content = JSON.stringify(
      DagToData(this.props.graph, this.props.dagId)
    );
    let blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
    let file = new File([blob], filename, {
      lastModified: Date.now()
    });
    const dagfile = new FormData();
    dagfile.append('file', file);
    dagfile.append('project_id', 'test');
    dagfile.append('file_type', 'dag');
    const { data } = await uploadFile(dagfile);
    if (data.code === 200) {
      message.success('上传成功');
    } else {
      message.error(data.msg);
    }
  }

  DropDown(toolType: string) {
    const MenuItem = Menu.Item; // eslint-disable-line

    return (
      <>
        {toolType === 'run' && (
          <Menu>
            <MenuItem name="start" onClick={this.props.runDag}>
              启动执行
            </MenuItem>
          </Menu>
        )}
        {toolType === 'tool' && (
          <Menu>
            {/* <MenuItem
              name="dataList"
              onClick={() => {
                const widget = new MainAreaWidget({
                  content: ReactWidget.create(<MediateDataTable />)
                });
                widget.title.label = '中间数据列表';
                widget.title.icon = dagDataIcon;
                const app: JupyterFrontEnd = (window as any).jupyterlab;
                app.shell.add(widget, 'main');
              }}
            >
              中间数据列表
            </MenuItem> */}
            <MenuItem
              name="packageEdit"
              onClick={() => {
                const selected = this.props.graph.getSelectedCells();
                if (
                  selected.length === 1 &&
                  selected[0].data &&
                  selected[0].data.type === 'script'
                ) {
                  this.setState({
                    modalVisible: true,
                    packageData: selected[0].data.packageData
                  });
                } else {
                  message.warning('请选择单个脚本节点');
                }
              }}
            >
              依赖编辑
            </MenuItem>
            <MenuItem
              name="uploadDag"
              onClick={() => {
                this.uploadDagFile();
              }}
            >
              上传至项目目录
            </MenuItem>
          </Menu>
        )}
      </>
    );
  }

  render() {
    return (
      <div style={{ paddingRight: 16 }} className={this.props.className}>
        <Toolbar hoverEffect={true} size="big" onClick={this.onClick}>
          <Group>
            <Item
              name="save"
              icon={<SaveOutlined />}
              // tooltip="Save (Cmd/Ctrl + S)"
            />
          </Group>
          <Group>
            <Item
              name="run"
              dropdown={this.DropDown('run')}
              icon={<PlayCircleOutlined />}
            />
          </Group>
          <Group>
            <Item
              name="tool"
              dropdown={this.DropDown('tool')}
              icon={<ToolOutlined />}
            />
          </Group>
          <Group>
            <Item name="zoomOut" icon={<ZoomOutOutlined />} />
            <Item name="zoomIn" icon={<ZoomInOutlined />} />
          </Group>
        </Toolbar>
        {/* 脚本编辑弹窗 */}
        <Modal
          title="依赖编辑"
          open={this.state.modalVisible}
          onOk={this.submitEdit}
          okText="确定"
          destroyOnClose={true}
          className="package-modal"
          cancelText="取消"
          onCancel={() => {
            this.setState({ modalVisible: false });
          }}
        >
          <Form
            initialValues={{
              packageData: this.state.packageData
            }}
          >
            <Form.Item label="依赖编辑" name="packageData" required>
              <Input.TextArea
                placeholder="请输入节点需要的依赖"
                style={{ height: '80px' }}
                onChange={e => {
                  this.setState({ packageData: e.target.value });
                }}
              />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}
