import React from 'react';
import {
  PlusCircleOutlined,
  MinusCircleOutlined,
  QuestionCircleOutlined
} from '@ant-design/icons';
import {
  Form,
  Input,
  Space,
  Select,
  Button,
  Radio,
  message,
  Tooltip
} from 'antd';
import { getDebugTable, getLocalDebugTable, getSchema } from './request';
export default class OutputNodeInfo extends React.Component<any, any> {
  formRef = React.createRef();

  constructor(props: any) {
    super(props);
    this.state = {
      outputFieldEditing: false,
      outputTypeEditing: false,
      debugTable: [],
      localDebugTable: [],
      currentTablePath: 'node',
      nodeName: ''
    };
  }

  async getTableSchema(table_name: string) {
    const { data } = await getSchema(table_name);
    if (data.code === 200) {
      const output = data.data.map((item: any) => {
        const strs = item.split(':');
        return {
          dataField: strs[1],
          dataType: strs[2]
        };
      });
      (this.formRef.current as any)?.setFieldsValue({
        outputSource: output
      });
    } else {
      message.error('获取本地调试数据表失败');
    }
  }

  changeTablePath(e: any) {
    this.setState({ currentTablePath: e.target.value });
    (this.formRef.current as any).setFieldsValue({
      dataTable: '',
      outputSource: []
    });
  }

  async getDebugTableList() {
    const { data } = await getDebugTable({
      user_id: 'test',
      project_id: 'test'
    });
    if (data.code === 200) {
      this.setState({ debugTable: data.data });
    } else {
      message.error('获取调试数据表失败');
    }
  }
  async getLocalDebugTableList() {
    const { data } = await getLocalDebugTable();
    if (data.code === 200) {
      const list = data.data.table_list.map((item: any) => {
        return `${data.data.database_name}.${item}`;
      });
      this.setState({ localDebugTable: list });
    } else {
      message.error('获取本地调试数据表失败');
    }
  }

  componentDidMount() {
    (this.formRef.current as any).setFieldsValue({
      outputSource: this.props.nodeInfo.outputSource
    });
    this.setState({
      currentTablePath: this.props.nodeInfo.tablePath,
      nodeName: this.props.nodeInfo.nodeName
    });
    this.getDebugTableList();
    this.getLocalDebugTableList();
  }

  submit() {
    const { outputSource, nodeName, tablePath, dataTable } = (this.formRef
      .current as any).getFieldsValue();
    if (nodeName) {
      this.props.nodeInfo.outputSource = outputSource;
      this.props.nodeInfo.nodeName = nodeName;
      this.props.nodeInfo.tablePath = tablePath;
      this.props.nodeInfo.dataTableId = dataTable;
      this.props.node.setData({ ...this.props.nodeInfo });
      this.props.close();
      this.props.changeStatus(this.props.nodeInfo.nodeId);
    } else {
      message.error('请输入节点名字');
    }
  }

  onReset() {
    this.props.nodeInfo.nodeName = this.state.nodeName;
    this.props.node.setData({ ...this.props.nodeInfo });
    this.props.close();
  }

  enterOutputField(e: any, index: number) {
    const outputSource = (this.formRef.current as any).getFieldValue(
      'outputSource'
    );
    if (outputSource[index]) {
      outputSource[index]['dataField'] = e.target.value.trim();
    } else {
      outputSource.push({ dataField: e.target.value.trim() });
    }
  }

  changeOutputFieldType(val: string, index: number) {
    const outputSource = (this.formRef.current as any).getFieldValue(
      'outputSource'
    );
    if (outputSource[index]) {
      outputSource[index]['dataType'] = val;
    } else {
      outputSource.push({ dataType: val });
    }
  }

  handleOutputParam(val: number) {
    (this.formRef.current as any).setFieldsValue({
      dataTable: '',
      tablePath: ''
    });
    // const data = (this.formRef.current as any).getFieldValue('outputSource');
    // const checkData = data.filter((_: any, index: number) => index !== val);
    // (this.formRef.current as any).setFieldValue('outputSource', checkData);
  }

  render() {
    return (
      <div className="node-datasource">
        <Form
          ref={this.formRef as any}
          name="datasourceInfo"
          className="datasourceInfo"
          autoComplete="off"
          layout="vertical"
          initialValues={{
            outputSource: this.props.nodeInfo.outputSource,
            nodeName: this.props.nodeInfo.nodeName,
            dataTable: this.props.nodeInfo.dataTableId,
            tablePath: this.props.nodeInfo.tablePath
          }}
        >
          <Form.Item name="nodeName" label="节点名称:">
            <Input
              placeholder="请输入节点名称"
              onChange={e => {
                //渲染问题
                this.props.node.setData({
                  ...this.props.nodeInfo
                });
                this.props.nodeInfo.nodeName = e.target.value;
                this.props.node.setData({ ...this.props.nodeInfo });
              }}
            />
          </Form.Item>
          <Form.Item name="tablePath" label="选择调试表路径:">
            <Radio.Group
              onChange={e => {
                this.changeTablePath(e);
              }}
            >
              <Radio value="node">本地数据</Radio>
              <Radio value="local">系统数据</Radio>
            </Radio.Group>
          </Form.Item>
          <p>
            <Space>
              选择同结构数据表:
              <Tooltip title="会使用父节点的输出表结构覆盖该输出源的表结构。此操作为了确定dag输出源的表结构">
                <QuestionCircleOutlined />
              </Tooltip>
            </Space>
          </p>
          <Form.Item
            name="dataTable"
            style={{ width: '80%', marginTop: '5px' }}
          >
            <Select
              showSearch
              optionFilterProp="label"
              options={
                this.state.currentTablePath === 'node'
                  ? this.state.debugTable.map((item: any) => {
                      return { label: item.name, value: item.table_name };
                    })
                  : this.state.currentTablePath === 'local'
                  ? this.state.localDebugTable.map((item: any) => {
                      return { label: item, value: item };
                    })
                  : []
              }
              placeholder="选择调试数据表"
              onSelect={(val: any) => {
                this.getTableSchema(val);
              }}
            />
          </Form.Item>
          <p>输出:</p>
          <div className="fieldWrapper">
            <Form.List name="outputSource">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, ...restField }, index) => (
                    <Space
                      key={key}
                      style={{ display: 'flex', margin: '10px 0 -20px' }}
                      align="baseline"
                    >
                      <Form.Item
                        {...restField}
                        name={[name, 'dataField']}
                        rules={[{ required: true, message: '请填写字段' }]}
                      >
                        <Input
                          placeholder="字段名"
                          onChange={e => this.enterOutputField(e, index)}
                        />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'dataType']}
                        rules={[{ required: true, message: '请填写字段类型' }]}
                      >
                        <Select
                          onChange={val =>
                            this.changeOutputFieldType(val, index)
                          }
                          options={[
                            { label: 'string', value: 'string' },
                            { label: 'int', value: 'int' },
                            { label: 'text', value: 'text' },
                            { label: 'float', value: 'float' },
                            { label: 'double', value: 'double' }
                          ]}
                          placeholder="请选择字段类型"
                        />
                      </Form.Item>
                      {fields.length > 1 ? (
                        <MinusCircleOutlined
                          className="dynamic-delete-button"
                          onClick={() => {
                            this.handleOutputParam(index);
                            remove(name);
                          }}
                          style={{ color: '#147BD1' }}
                        />
                      ) : null}
                    </Space>
                  ))}
                  <Form.Item>
                    <Button
                      type="link"
                      onClick={() => {
                        return add();
                      }}
                      icon={<PlusCircleOutlined />}
                      style={{ paddingLeft: 0, paddingRight: 0 }}
                    >
                      添加输出
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </div>
          <Form.Item style={{ marginTop: '20px' }}>
            <Space>
              <Button
                type="primary"
                onClick={() => {
                  this.submit();
                }}
              >
                确认
              </Button>
              <Button
                onClick={() => {
                  this.onReset();
                }}
              >
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    );
  }
}
