import { ComponentClass } from 'react';
import Taro, { Component, Config } from '@tarojs/taro';
import { View, Button, Input, Navigator } from '@tarojs/components';

import './Login.scss';
import { appLogin } from '../../api/customer';
import { connect } from '@tarojs/redux';
import { updateUserInfo, UserState } from '../../store/rootReducers/userinfo';
import { NotRegisterCode } from '../../constants/index';
import { shareHandle } from '@/common/shareMethod';

type PageDispatchProps = {
  userinfo: UserState;
  updateUserInfo: (e: UserState) => void;
};

type PageState = {
  fetching: boolean;
  account: string;
  pwd: string;
};

interface Login {
  props: PageDispatchProps;
  state: PageState;
}

@connect(
  ({ userinfo }) => ({ userinfo }),
  dispatch => ({
    updateUserInfo(data: UserState) {
      dispatch(updateUserInfo(data));
    },
  }),
)
class Login extends Component {
  config: Config = {
    navigationBarTitleText: '多彩校园',
  };

  constructor(props) {
    super(props);
    this.state = {
      fetching: false,
      account: '',
      pwd: '',
    };
  }
  onShareAppMessage = shareHandle;

  validataLoginData(): boolean {
    const { account, pwd } = this.state;
    if (!account || account.length !== 11) {
      Taro.showToast({
        title: '请输入手机号码',
        icon: 'none',
      });
      return false;
    }
    if (!pwd || pwd.length < 6) {
      Taro.showToast({
        title: '请输入密码',
        icon: 'none',
      });
      return false;
    }
    return true;
  }

  loginHandle(): void {
    if (this.state.fetching) return;
    if (this.validataLoginData()) {
      this.setState({
        fetching: true,
      });
      const { updateUserInfo, userinfo } = this.props;
      const { account, pwd } = this.state;
      console.log('in loginHandle');
      appLogin({
        loginAccount: account,
        password: pwd,
        code: userinfo.code,
      })
        .then(res => {
          const data = res.data;
          console.log(data);
          updateUserInfo(data);
          Taro.reLaunch({
            url: '/pages/Home/Home',
          });
        })
        .catch(err => {
          console.log(err);

          if (err.code && err.code === NotRegisterCode) {
            updateUserInfo({
              customerPhone: account,
            });
            setTimeout(() => {
              this.setState({
                fetching: false,
              });
              Taro.navigateTo({
                url: '/pages/Register/Register',
              });
            }, 2000);
          } else {
            this.setState({
              fetching: false,
            });
          }
        });
    }
  }

  render() {
    const { account, pwd } = this.state;
    return (
      <View className='Login'>
        <View className='Login-title'>欢迎来到多彩校园</View>
        <View>
          <Input
            className='Login-input'
            placeholder-class='Login-input-placeholder'
            placeholder='请输入账号手机号'
            type='number'
            value={account}
            maxLength={11}
            onInput={({ detail: { value } }) => {
              this.setState({
                account: value,
              });
              return value;
            }}
          />
          <Input
            className='Login-input'
            placeholder-class='Login-input-placeholder'
            password
            placeholder='请输入密码'
            value={pwd}
            maxLength={20}
            onInput={({ detail: { value } }) => {
              this.setState({
                pwd: value,
              });
              return value;
            }}
          />
        </View>

        <View className='Login-regist'>
          <View>
            还没有账号？
            <Navigator
              className='Login-regist-btn'
              url='/pages/Register/Register'>
              注册
            </Navigator>
          </View>
          <Navigator
            className='Login-regist-btn'
            url='/pages/ResetPwd/ResetPwd'>
            忘记密码
          </Navigator>
        </View>
        <Button className='Login-btn' onClick={this.loginHandle}>
          登录
        </Button>
      </View>
    );
  }
}

export default Login as ComponentClass<PageDispatchProps, PageState>;
