import React, { Component } from 'react';

import { is_weixn } from '../utils';
import { APP_ID } from '../config';
import UserInfoContext, { defaultUserinfo } from '../context/userinfo-context';

import { Route, Switch, Redirect } from 'react-router-dom';
import Home from './Home/Index';
import Login from './Login/Login';
import PublicCar from './PublicCar/index';
import PublicCarDeal from './PublicCarDeal/index';
import Repair from './Repair/index';
import RepairDeal from './RepairDeal/index';
import NoMatch from './NoMatch';

import { wxAuth } from '../api/index';
import { Toast } from 'antd-mobile';
import store from '../store/index';

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isWx: is_weixn(),
      userContext: {
        userinfo: defaultUserinfo,
        updateUserInfo: this.updateUserInfo,
      },
      loadingText: '加载中...',
    };
  }
  getParams = str => {
    let obj = {};
    const searchParams = new URLSearchParams(str);
    let keys = searchParams.keys();
    for (const key of keys) {
      obj[key] = searchParams.get(key);
    }
    return obj;
  };
  renderIndex = props => {
    console.log(props);
    const {
      userContext: {
        userinfo: { login },
      },
      loadingText,
    } = this.state;
    const { history, location } = props;
    let params = this.getParams(location.search);
    if (login) {
      return <div style={{ margin: '60px 24px 0' }}>{loadingText}</div>;
    }
    if (params.code) {
      console.log('fetch UserInfo');
      console.log('redirect', params);
      wxAuth({
        code: params.code,
      })
        .then(res => {
          console.log(res);
          const { firstLogin, user, author } = res.data;
          store.updateUserId(user.userId);
          this.updateUserInfo({ ...user, login: true, author });
          if (firstLogin) {
            history.replace('/login');
          } else {
            history.replace('/home');
          }
        })
        .catch(err => {
          console.log(err);
          Toast.fail(err.msg || '获取授权失败！');
          this.updateUserInfo({ login: true });
          this.setState({
            loadingText: '请求授权失败！请重新进入或刷新页面！',
          });
        });
    } else {
      console.log('go in wxAuth');
      this.goWechatAuth();
    }

    return <div style={{ margin: '60px 24px 0' }}>{loadingText}</div>;
  };
  goWechatAuth = () => {
    let rUrl = encodeURIComponent(window.location.origin);
    window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APP_ID}&redirect_uri=${rUrl}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
    return <div style={{ margin: '60px 24px 0' }}>授权中。。。</div>;
  };
  validateUserinfo = (props, code, Component) => {
    const {
      userContext: {
        userinfo: { login, author },
      },
    } = this.state;

    if (!login) {
      console.log('no login');
      // product 需要修改为去微信授权
      // return <Component />;
      return this.goWechatAuth();
    }
    let item = author.find(i => i.code === code);
    if (item.type) {
      return <Component {...props} />;
    } else {
      Toast.fail('无权使用该功能');
      const from = { pathname: '/home' };
      return <Redirect to={from} />;
    }
  };
  updateUserInfo = data => {
    this.setState({
      userContext: {
        ...this.state.userContext,
        userinfo: { ...this.state.userContext.userinfo, ...data },
      },
    });
  };
  render() {
    const { userContext } = this.state;

    return (
      <div className="App">
        <UserInfoContext.Provider value={userContext}>
          <Switch>
            <Route exact path="/" render={this.renderIndex} />
            <Route path="/home" component={Home} />
            <Route path="/login" component={Login} />
            <Route
              path="/publicCar"
              render={props =>
                this.validateUserinfo(props, 'CSHQ0003', PublicCar)
              }
            />
            <Route
              path="/publicCarDeal"
              render={props =>
                this.validateUserinfo(props, 'CSHQ0004', PublicCarDeal)
              }
            />
            <Route
              path="/Repair"
              render={props => this.validateUserinfo(props, 'CSHQ0001', Repair)}
            />
            <Route
              path="/RepairDeal"
              render={props =>
                this.validateUserinfo(props, 'CSHQ0002', RepairDeal)
              }
            />
            <Route component={NoMatch} />
          </Switch>
        </UserInfoContext.Provider>
      </div>
    );
  }
}

export default App;
