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

const submitInterval = 5000;

export default class InformPage extends Component {
  state = {
    phone: '',
    name: '',
    isLoading: false,
    isDisable: false,
  };
  handleChangePhone(phone: string) {
    this.setState({
      phone: phone,
    });
    return phone;
  }
  handleChangeName(name: string) {
    this.setState({
      name: name,
    });
    return name;
  }
  onSubmit() {
    this.setState({
      isLoading: true,
      isDisable: true,
    });
    console.log(this.state.name, this.state.phone);
    Taro.request({
      url: getUrl('/user/update'),
      method: 'POST',
      data: {
        token: 'token_test',
        name: this.state.name,
        phone: this.state.phone,
      },
    })
      .then(res => {
        console.log(res.data);
        Taro.atMessage({
          message: pt.get().button.submitText.success,
          type: 'success',
        });
      })
      .catch(err => {
        console.log(err);
        Taro.atMessage({
          message: pt.get().button.submitText.error + err.toString(),
          type: 'error',
        });
      });
    this.setState({
      isLoading: false,
    });
    setTimeout(() => {
      this.setState({
        isDisable: false,
      });
    }, submitInterval);
  }

  render(): ReactNode {
    return (
      <View>
        <AtForm onSubmit={this.onSubmit.bind(this)}>
          <AtMessage />
          <AtInput
            clear
            required
            name='phone'
            title={pt.get().informPage.phoneText.title}
            type='number'
            placeholder={pt.get().informPage.phoneText.placeholder}
            value={this.state.phone}
            onChange={this.handleChangePhone.bind(this)}
          />
          <AtInput
            required
            clear
            name='name'
            title={pt.get().informPage.nameText.title}
            type='text'
            placeholder={pt.get().informPage.nameText.placeholder}
            value={this.state.name}
            onChange={this.handleChangeName.bind(this)}
          />
          <AtButton
            loading={this.state.isLoading}
            formType='submit'
            type='primary'
            disabled={this.state.isDisable}
          >
            {pt.get().button.buttonText.submit}
          </AtButton>
        </AtForm>
      </View>
    );
  }
}
