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

import './index.scss';
import { connect } from '@tarojs/redux';

import { updateUserInfo, UserState } from '../../store/rootReducers/userinfo';
import { appLogin } from '../../api/customer';
import { shareHandle } from '@/common/shareMethod';

type PageDispatchProps = {
  updateUserInfo: (e: UserState | { token: string }) => void;
};

type PageOwnProps = {};

type PageState = {
  errorText: string;
};

type IProps = PageDispatchProps & PageOwnProps;

interface Index {
  props: IProps;
  state: PageState;
}

@connect(
  () => ({}),
  dispatch => ({
    updateUserInfo(entity: UserState) {
      dispatch(updateUserInfo(entity));
    },
  }),
)
class Index extends Component {
  config: Config = {};

  constructor(props: IProps) {
    super(props);
    this.state = {
      errorText: '',
    };
  }
  onShareAppMessage = shareHandle;

  componentWillMount() {
    Taro.showLoading();
    this.loginHandle();
  }

  checkUser() {
    Taro.getStorage({
      key: 'token',
    })
      .then(res => {
        const data = res.data;
        console.log('token ' + data);
      })
      .catch(() => {
        this.loginHandle();
      });
  }

  loginHandle() {
    const { updateUserInfo } = this.props;
    Taro.login()
      .then(res => {
        console.log(res);
        const code = res.code;
        updateUserInfo({
          code,
        });
        appLogin({
          code: res.code,
        })
          .then(res => {
            const data = res.data;
            updateUserInfo(data);
            Taro.redirectTo({
              url: '/pages/Home/Home',
            });
          })
          .catch(err => {
            console.log(err);
            Taro.hideLoading();
            Taro.redirectTo({
              url: '/pages/Login/Login',
            });
          });
      })
      .catch(err => {
        console.log(err);
      });
  }

  render() {
    const { errorText } = this.state;
    return <View className='Index'>{errorText}</View>;
  }
}

export default Index as ComponentClass<PageOwnProps, PageState>;
