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, postRequirements, getRequirementsStatus } 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: '',
      status: ''
    };
  }

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

  submitEdit = async () => {
    const { data } = await postRequirements({
      requirements: this.state.packageData,
      dag_uuid: this.props.dagId
    });
    if (data.code === 200) {
      this.props.saveGraph(
        DagToData(this.props.graph, this.props.dagId, this.state.packageData)
      );
      this.setState({ modalVisible: false });
      message.success('添加成功');
    } else {
      message.success(data.msg);
    }
  };

  onClick = (name: string) => {
    switch (name) {
      case 'save':
        const text = this.props.context.current;
        text.ready.then(() => {
          const dagJson: any = text.model.toJSON();
          this.props.saveGraph(
            DagToData(this.props.graph, this.props.dagId, dagJson.requirements)
          );
          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:
    }
  };

  uploadDagFile() {
    const text = this.props.context.current;
    const filename = text.path.split('/').pop();
    text.ready.then(async () => {
      const dagJson: any = text.model.toJSON();
      const content = JSON.stringify(
        DagToData(this.props.graph, this.props.dagId, dagJson.requirements)
      );
      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);
      }
    });
  }

  openRequirements() {
    const text = this.props.context.current;
    text.ready.then(async () => {
      const dagJson: any = text.model.toJSON();
      const { data } = await getRequirementsStatus(this.props.dagId);
      if (data.code === 200) {
        let status = '暂无依赖';
        if (data.data !== '暂无依赖') {
          status =
            data.data.status === 0
              ? '队列中'
              : data.data.status === 1
              ? '运行中'
              : data.data.status === 2
              ? '成功'
              : '失败';
        }
        this.setState({
          modalVisible: true,
          packageData: dagJson.requirements,
          status
        });
      } else {
        message.success(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={() => {
                this.openRequirements();
              }}
            >
              依赖编辑
            </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
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 18 }}
            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.Item label="状态" name="status">
              <span>{this.state.status}</span>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}
