import React, { Component } from 'react'
import Routes from './router'
import cookie from 'js-cookie'
import { connect } from "react-redux";
import { setCurrentUser, startFetchUser } from "@/store/userAction";
import { withRouter } from 'react-router-dom'
import { compose } from 'redux'
import { getParam, http, browser } from "@/utils";
import { Toast } from "antd-mobile";
import { addDays } from 'date-fns'


//拦截ajax请求，返回mock数据
/*import mock from '@/utils/mock'
mock()*/


// 默认样式
import './assets/css/index.scss';

// iconfont
import './assets/font/iconfont.css';

class App extends Component {

    previousLocation = {
        ...{
            state: {
                from:
                    {
                        pathname: this.props.location.pathname,
                        search: this.props.location.search,
                        hash: this.props.location.hash
                    }
            }
        },
        ...this.props.location
    }

    componentDidMount() {
        // 友盟统计
        const script = document.createElement('script');
        script.src = 'https://s22.cnzz.com/z_stat.php?id=1265696973&web_id=1265696973';
        script.language = 'JavaScript';
        document.body.appendChild(script);

        this.setNavigationRecord(this.props.location)


        //平台信息
        cookie.set('plat', '5', {domain: '.julyedu.com'})

        if (browser.isWeixin && browser.isIOS) {
            sessionStorage.setItem('enter_url', window.location.href)
        }

        this.getUser()

        const routeMatchRule = /binding-tel|forgot|set-password/
        const {history} = this.props
        history.listen((location, action) => {
            this.setNavigationRecord(location)
            if (cookie.get('uid') && this.props.user.hasError) {
                this.getUser()
            }
            const {pathname} = location
            if (pathname.startsWith('/passport')) {
                if (routeMatchRule.test(pathname)) {
                    return
                }
                location.state = {from: this.previousLocation};
            }
        })


    }

    setNavigationRecord = (location) => {
        let {location: _location} = this.props
        let {state: _state = {}} = _location
        let {state = {}} = location
        location.state = {
            ...state, ...{
                record: _state.record ?
                    [..._state.record, {pathname: location.pathname, search: location.search, hash: location.hash}] :
                    [{pathname: location.pathname, search: '', hash: ''}]
            }
        }
    }

    getUser = () => {

        this.props.startFetchUser()
        http.get(`${API.home}/m/user_info`).then(res => {
            this.props.setCurrentUser(this.transformUser(res))
        })
        //微信
        let code = getParam('code')

        if (code) {

            http.get(`${API['home']}/m/wx_loginInfo/code/${code}`)
                .then(res => {
                    let data = res.data
                    if (data.errno == 200) {
                        if (data.data['is_bind_mobile']) {
                            window.location.assign(data.data.url)
                        } else {
                            let user = this.transformWxUser(res)
                            let {role, uid, token} = data.data
                            let expires = addDays(new Date(), 90)
                            cookie.set('role', role, {expires, domain: '.julyedu.com', path: '/'})
                            cookie.set('uid', uid, {expires, domain: '.julyedu.com', path: '/'})
                            cookie.set('token', token, {expires, domain: '.julyedu.com', path: '/'})
                            this.props.setCurrentUser(user)
                        }
                    } else {
                        Toast.info(data.msg)
                    }
                })


        }
    }

    componentDidUpdate() {
        const {location} = this.props
        this.previousLocation = location.pathname.startsWith('/passport') ?
            this.previousLocation.pathname === '/' ? location : this.previousLocation : location
    }


    transformUser = res => {
        let payload
        if (res.data.code === 200) {
            const {
                msg, data: {
                    avatar_file: avatar,
                    user_name: username,
                    is_vip: isVIP,
                    uid,
                    code
                }
            } = res.data

            payload = {
                hasError: false,
                msg,
                data: {
                    username,
                    isVIP,
                    avatar,
                    uid,
                    code
                }
            }
        } else {
            payload = {
                hasError: true,
                msg: res.data.msg,
                code: res.data.code,
                data: {}
            }
        }
        return payload
    }

    transformWxUser = res => {
        let data = res.data
        if (data.errno == 200) {
            let {uid, token, avatar_file: avatar, uname: username,} = data.data

            return {
                hasError: false,
                data: {
                    uid,
                    token,
                    avatar,
                    username
                },
                msg: data.msg
            }
        } else {
            let {code, msg} = data.data
            return {
                code,
                msg,
                hasError: true,
                data: {}
            }
        }
    }

    render() {
        return <Routes/>
    }
}

export default compose(
    connect(
        state => ({user: state.user}),
        {setCurrentUser, startFetchUser}
    ),
    withRouter
)(App)