import './demo5.css';
import Button from '../../button';
import Checkbox from '../../checkbox';
import Field from '..';
import Input from '../../input';
import React from 'react';
import ReactDOM from 'react-dom';

interface PageStates {
  checkboxStatus: boolean;
}
class App extends React.Component <{}, PageStates> {
  field: Field;
  constructor(props) {
    super(props);
    this.state = {
      checkboxStatus: true,
    };
    // @ts-ignore
    this.field = new Field(this, { scrollToFirstError: -10 });
  }
  isChecked(rule, value) {
    if (!value) {
      return Promise.reject(new Error('consent agreement not checked '));
    }
    return Promise.resolve(null);

  }

  userName(rule, value) {
    if (value === 'frank') {
      return new Promise((resolve, reject) => {
        setTimeout(() => reject(new Error('name existed')), 200);
      });
    }
    return new Promise(resolve => {
      setTimeout(() => resolve(null), 200);
    });

  }

  render() {
    const init = this.field.init;

    return (
      <div className="demo">
        <Input
          defaultValue=""
          placeholder="try frank"
          {...init('username', {
            rules: [
              {
                validator: this.userName,
                trigger: [ 'onBlur', 'onChange' ],
              },
            ],
          })}
        />
        {/* @ts-ignore */}
        {this.field.getState('username') === 'loading' ? 'validating...' : ''}
        {this.field.getError('username') ? (
          <span style={{ color: 'red' }}>
            {this.field.getError('username').join(',')}
          </span>
        ) : (
          ''
        )}
        <br />
        <br />
        agreement:
        {/* @ts-ignore */}
        <Checkbox
          {...init('checkbox', {
            valueName: 'checked',
            rules: [{ validator: this.isChecked }],
          })}
        />
        {this.field.getError('checkbox') ? (
          <span style={{ color: 'red' }}>
            {this.field.getError('checkbox').join(',')}
          </span>
        ) : (
          ''
        )}
        <br />
        <br />
        <Button
          type="primary"
          onClick={() => {
            this.field.validatePromise().then(({ errors, values }) => {
              console.log(errors, values);
            });
          }}
        >
          validate
        </Button>
        <Button
          onClick={() => {
            this.field.reset();
          }}
        >
          reset
        </Button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('field-demo-5'));
