import React from 'react';
// import { PlusCircleOutlined } from '@ant-design/icons';
import {
  Form,
  Input,
  Space,
  Select,
  message,
  Checkbox,
  Radio,
  Button
} from 'antd';
import { getDebugTable, getLocalDebugTable, getSchema } from './request';
import { CheckboxChangeEvent } from 'antd/es/checkbox';

export default class DatasourceNodeInfo extends React.Component<any, any> {
  formRef = React.createRef();

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

  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('获取本地调试数据表失败');
    }
  }

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

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

  componentDidMount() {
    this.setState({
      currentTablePath: this.props.nodeInfo.tablePath,
      nodeName: this.props.nodeInfo.nodeName
    });
    this.getDebugTableList();
    this.getLocalDebugTableList();
  }

  onCheckAll(e: CheckboxChangeEvent) {
    const val = (this.formRef.current as any).getFieldValue('inputDatasource');
    const checkData = val.map((item: any) => ({
      ...item,
      dataSelect: e.target.checked
    }));
    (this.formRef.current as any).setFieldsValue({
      inputDatasource: checkData
    });
    this.setState({
      checkAll: e.target.checked
    });
  }

  submit() {
    const { inputDatasource, nodeName, tablePath, dataTable } = (this.formRef
      .current as any).getFieldsValue();
    console.log(inputDatasource);
    if (nodeName) {
      if (inputDatasource.length) {
        if (inputDatasource.find((item: any) => item.dataSelect)) {
          this.props.nodeInfo.inputSource = inputDatasource;
          this.props.nodeInfo.nodeName = nodeName;
          this.props.nodeInfo.tablePath = tablePath;
          this.props.nodeInfo.dataTableId = dataTable;
          this.props.nodeInfo.dataTableName = dataTable;
          this.props.node.setData({ ...this.props.nodeInfo });
          this.props.close();
          this.props.changeStatus(this.props.nodeInfo.nodeId);
        } else {
          message.error('请选择字段');
        }
      } else {
        message.error('请选择数据表');
      }
    } else {
      message.error('请输入节点名字');
    }
  }

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

  render() {
    return (
      <div className="node-datasource">
        <Form
          ref={this.formRef as any}
          name="datasourceInfo"
          className="datasourceInfo"
          autoComplete="off"
          layout="vertical"
          initialValues={{
            inputDatasource: this.props.nodeInfo.inputSource,
            dataTable: this.props.nodeInfo.dataTableId,
            nodeName: this.props.nodeInfo.nodeName,
            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>添加调试数据表:</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.localDebugTable.map((item: any) => {
                      return { label: item, value: item };
                    })
              }
              placeholder="选择调试数据表"
              onSelect={(val: any) => {
                this.getTableSchema(val);
              }}
            />
          </Form.Item>
          <p>输入源:</p>
          <Checkbox
            onChange={e => this.onCheckAll(e)}
            checked={this.state.checkAll}
          >
            全选
          </Checkbox>
          <div className="fieldWrapper">
            <Form.List name="inputDatasource">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, ...restField }) => (
                    <Space
                      key={key}
                      style={{ display: 'flex', margin: '10px 0 -20px' }}
                      align="baseline"
                    >
                      <Form.Item
                        {...restField}
                        name={[name, 'dataSelect']}
                        valuePropName="checked"
                      >
                        <Checkbox
                          onChange={e => {
                            this.setState({
                              checkAll: false
                            });
                          }}
                        />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'dataField']}
                        rules={[{ required: true, message: '请填写字段' }]}
                      >
                        <Input placeholder="字段名" disabled />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'dataType']}
                        rules={[{ required: true, message: '请填写字段类型' }]}
                      >
                        <Select
                          options={[
                            { label: 'string', value: 'string' },
                            { label: 'int', value: 'int' },
                            { label: 'text', value: 'text' },
                            { label: 'float', value: 'float' },
                            { label: 'double', value: 'double' }
                          ]}
                          placeholder="请选择字段类型"
                          disabled
                        />
                      </Form.Item>
                    </Space>
                  ))}
                  {/* <Form.Item>
                  <Button type="link" onClick={() => {
                    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>
    );
  }
}
