import { Component, ReactNode } from 'react';
import { AtForm, AtInput, AtButton, AtMessage } from 'taro-ui';
import { getUrl } from '@/service';
import Taro from '@tarojs/taro';
import pt from '@/plain-text';
import './member.scss';

const loginInterval = 5000;

export default class MemberPage extends Component {
  state = {
    stuid: '',
    passwd: '',
    isLoading: false,
    isDisable: false,
  };
  componentDidMount(): void {
    Taro.setNavigationBarTitle({
      title: pt.get().navBar.user.member,
    });
  }
  handleChangeStuid(stuid: string) {
    this.setState({
      stuid: stuid,
    });
    return stuid;
  }
  handleChangePasswd(passwd: string) {
    this.setState({
      passwd: passwd,
    });
    return passwd;
  }
  onSubmit() {
    this.setState({
      isLoading: true,
      isDisable: true,
    });
    console.log([this.state.stuid, this.state.passwd]);
    Taro.request({
      url: getUrl('/member/login'),
      method: 'POST',
      data: {
        token: 'token_test',
        name: this.state.stuid,
        passwd: this.state.passwd,
      },
    })
      .then(res => {
        console.log(res.data);
        Taro.atMessage({
          message: pt.get().button.loginText.success,
          type: 'success',
        });
      })
      .catch(err => {
        console.log(err);
        Taro.atMessage({
          message: pt.get().button.loginText.error + err.toString(),
          type: 'error',
        });
      });
    this.setState({
      isLoading: false,
    });
    setTimeout(() => {
      this.setState({
        isDisable: false,
      });
    }, loginInterval);
  }

  render(): ReactNode {
    return (
      <AtForm onSubmit={this.onSubmit.bind(this)}>
        <AtMessage />
        <AtInput
          required
          name='stuid'
          title={pt.get().memberPage.stuidText.title}
          type='number'
          clear
          placeholder={pt.get().memberPage.stuidText.placeholder}
          value={this.state.stuid}
          onChange={this.handleChangeStuid.bind(this)}
        />
        <AtInput
          clear
          required
          name='name'
          title={pt.get().memberPage.passwdText.title}
          type='password'
          placeholder={pt.get().memberPage.passwdText.placeholder}
          value={this.state.passwd}
          onChange={this.handleChangePasswd.bind(this)}
        />
        <AtButton
          loading={this.state.isLoading}
          formType='submit'
          type='primary'
          disabled={this.state.isDisable}
        >
          {pt.get().button.buttonText.login}
        </AtButton>
      </AtForm>
    );
  }
}
