App.js 10.1 KB
Newer Older
1
import React, { Component } from 'react'
zhanghaozhe committed
2 3
import Routes from './router'
import cookie from 'js-cookie'
4 5 6 7 8 9 10 11
import { connect } from "react-redux"
import { setCurrentUser, startFetchUser } from "@/store/userAction"
import { initialState } from "@/store/userReducer"
import { withRouter, Link } from 'react-router-dom'
import { compose } from 'redux'
import { getParam, http, browser } from "@/utils"
import { Toast } from "antd-mobile"
import { addDays } from 'date-fns'
xuzhenghua committed
12
import stringify from 'json-stringify-safe'
13
import Hammer from 'hammerjs'
14

zhanghaozhe committed
15 16

//拦截ajax请求,返回mock数据
zhanghaozhe committed
17 18
/*import mock from '@/utils/mock'
mock()*/
zhanghaozhe committed
19 20 21


// 默认样式
zhanghaozhe committed
22
import './assets/css/index.scss'
zhanghaozhe committed
23 24

// iconfont
zhanghaozhe committed
25
import './assets/font/iconfont.css'
zhanghaozhe committed
26

27
class App extends Component {
28 29 30 31 32
  constructor(props) {
    super(props)
    this.state = {
      isShowActivityEntry: 0,
      isShowChannel: 0
xuzhenghua committed
33
    }
34 35
    this.globalEntry = null
  }
36

37
  static displayName = 'App'
zhanghaozhe committed
38

39
  previousLocation = {pathname: '/', search: '', hash: ''}
40

41
  records = []
FE committed
42

43
  pathnameBlacklist = ['/country', '/passport']
zhanghaozhe committed
44

45
  firstLoad = true
xuzhenghua committed
46

xuzhenghua committed
47

48 49 50 51 52 53
  componentWillMount() {
    let url = window.location.href;
    if (url.indexOf('ccode') > -1) {
      if (!getParam('ccode').includes('%')) {
        cookie.set('ccode', getParam('ccode'), {expires: 1, domain: '.julyedu.com', path: '/'})
      }
xuzhenghua committed
54
    }
55
  }
xuzhenghua committed
56

57 58 59
  componentDidMount() {
    //是否显示宝箱全局入口
    this.isShowGlobalEntryInTime()
zhanghaozhe committed
60

61 62 63
    this.umengStatistic()
    //平台信息
    !getParam('version') && cookie.set('plat', '5', {domain: '.julyedu.com'})
zhanghaozhe committed
64

zhanghaozhe committed
65

66 67 68
    if (browser.isWeixin && browser.isIOS) {
      sessionStorage.setItem('enter_url', window.location.href)
    }
zhanghaozhe committed
69

70 71
    this.getUser()
    this.utm()
zhanghaozhe committed
72

73
    const {history} = this.props
zhanghaozhe committed
74 75


76 77
    this.setNavigationRecord(this.props.location, this.props.history.action)
    this.setPreviousLocation()
zhanghaozhe committed
78

xuzhenghua committed
79

80 81 82 83
    history.listen((location, action) => {
      this.firstLoad = false
      this.setNavigationRecord(location, action)
      this.utm()
xuzhenghua committed
84

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
      if (cookie.get('uid') && this.props.user.hasError) {
        this.getUser()
      }
      if (location.pathname.startsWith('/passport')) {
        window.localStorage.setItem('binding_redirect', stringify(this.previousLocation))
      }
      const {pathname, state} = location
      if (pathname.startsWith('/passport')) {
        location.state = {
          ...state,
          ...{
            from: {
              pathname: this.previousLocation.pathname,
              search: this.previousLocation.search,
              hash: this.previousLocation.hash
xuzhenghua committed
100
            }
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
          }
        }
      } else {
        this.removeShareCodeCookie()
      }
    })
  }

  // 获取宝箱阶段
  getStage = () => {
    let ccode = cookie.get('ccode')
    http.get(`${API.home}/activity/stage?ccode=${ccode}`).then(res => {
      const {code, data, msg} = res.data
      if (code === 200) {
        // treasure_stage,宝箱阶段,0-不在活动时间,1-活动时间内
        this.setState({
          isShowActivityEntry: data.treasure_stage,
          isShowChannel: data.is_show_site_window_by_channel
        }, () => {
zhanghaozhe committed
120
          data.treasure_stage && this.bindGlobalEntry()
xuzhenghua committed
121
        })
122

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        window.sessionStorage.setItem('isShowSiteWindowByChannel', data.is_show_site_window_by_channel)
      } else {
        Toast.info(msg, 2)
      }
    })
  }

  umengStatistic = () => {
    // 友盟统计
    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)
  }

  removeShareCodeCookie = () => {
    cookie.remove('share_code', {path: '/', domain: '.julyedu.com'})
  }

  setNavigationRecord = (location, action) => {
    const {pathname, search, hash} = location
    let isLastRecord = location.pathname === (this.records.length && this.records[this.records.length - 1].pathname)
    let needHistoryMutation = location.pathname !== this.previousLocation.pathname

    switch (action) {
      case 'POP':
        if (needHistoryMutation) {
          this.firstLoad ? this.records.push({pathname, search, hash}) : this.records.pop()
        } else {
          this.records[this.records.length - 1] = location
        }
        break
      case 'REPLACE':
        this.records.length > 1 && (this.records[this.records.length - 1] = {pathname, search, hash})
        break
      default:
        !isLastRecord && this.records.push({pathname, search, hash})
xuzhenghua committed
160
    }
161

162 163 164 165 166
    location.state && location.state.records
      ? (location.state.records = this.records)
      : location.state ? location.state = {...location.state, records: this.records}
      : (location.state = {records: this.records})
  }
xuzhenghua committed
167

168

169 170 171
  utm = () => {
    // utm统计  m站全站统计广告投放、以及统计详情页浏览
    let zhihu_cb = getParam('cb')
xuzhenghua committed
172

173 174 175 176
    if (zhihu_cb) {
      let data = {
        'zhihu_cb': zhihu_cb
      }
xuzhenghua committed
177

178 179 180
      http.post(`${API['home']}/sys/zhihu/firstRecord`, data)
        .then(res => {
        })
xuzhenghua committed
181

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    }
  }

  getUser = () => {
    //获取用户信息
    this.props.startFetchUser()

    //微信
    let code = getParam('code')
    let oid = getParam('oid')
    if (code && !oid) {

      http.get(`${API["passport-api"]}/m/wx_loginInfo/code/${code}?redirect=${encodeURIComponent(window.location.href)}`)
        .then(res => {
          let data = res.data
          if (data.errno == 200) {
            if (data.data['is_bind_mobile']) {
              window.location.assign(data.data.url)
            } else {
              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: '/'})
206 207 208 209 210 211 212 213 214

              const search = new URLSearchParams(window.location.search)
              search.delete('code')
              search.delete('aa')
              if (search.has('state') && search.get('state') === 'STATE') {
                search.delete('state')
              }
              const loc = window.location
              loc.replace(loc.origin + loc.pathname + '?' + search.toString() + loc.hash)
xuzhenghua committed
215
            }
216 217 218 219 220
          } else {
            Toast.info(data.msg)
            this.props.setCurrentUser(initialState)
          }
        })
xuzhenghua committed
221

zhanghaozhe committed
222

223 224 225 226
    } else {
      http.get(`${API.home}/m/user_info`).then(res => {
        this.props.setCurrentUser(this.transformUser(res))
      })
227
    }
xuzhenghua committed
228

229
  }
xuzhenghua committed
230

231
  componentDidUpdate() {
xuzhenghua committed
232

233
    this.setPreviousLocation()
zhanghaozhe committed
234

235 236
    if (!this.props.user.hasError && getParam('redirect')) {
      window.location.href = getParam('redirect')
237
    }
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
  }

  setPreviousLocation = () => {
    const {location} = this.props
    let isInBlacklist = this.pathnameBlacklist.some(item => location.pathname.startsWith(item))
    !isInBlacklist && (this.previousLocation = location)
  }

  transformUser = res => {
    let payload
    if (res.data.code === 200) {
      //移除红包统计cookie
      this.removeShareCodeCookie()
      const {
        msg, data: {
          avatar_file: avatar,
          user_name: username,
          is_vip: isVIP,
          uid,
          code
xuzhenghua committed
258
        }
259 260 261 262 263 264 265 266 267 268 269
      } = res.data

      payload = {
        hasError: false,
        msg,
        data: {
          username,
          isVIP,
          avatar,
          uid,
          code
xuzhenghua committed
270
        }
271 272 273 274 275 276 277 278
      }
    } else {
      payload = {
        hasError: true,
        msg: res.data.msg,
        code: res.data.code,
        data: {}
      }
xuzhenghua committed
279
    }
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
    return payload
  }

  transformWxUser = res => {
    let data = res.data
    if (data.errno == 200) {
      //移除红包统计cookie
      this.removeShareCodeCookie()
      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: {}
      }
FE committed
308
    }
309
  }
xuzhenghua committed
310

311
  bindGlobalEntry = () => {
zhanghaozhe committed
312 313
    if (!this.globalEntry) {
      return
xuzhenghua committed
314
    }
315 316 317 318
    const mc = new Hammer(this.globalEntry)
    const {history} = this.props
    const _this = this
    const entryWidth = this.globalEntry.offsetWidth
319
    const velocityThreshold = 0.4
320 321 322 323 324 325 326

    mc.on('panright tap panend', function (e) {
      if (e.type === 'tap') {
        history.push('/box/boxActive')
      } else if (e.type === 'panright') {
        _this.globalEntry.style.transform = `translateX(${e.deltaX}px)`
      } else {
327
        if (e.deltaX > entryWidth / 2 || e.velocityX > velocityThreshold) {
328 329 330
          _this.globalEntry.style.transition = `.2s`
          _this.globalEntry.style.transform = `translateX(${entryWidth + 10}px)`
          _this.closeGlobalEntry()
xuzhenghua committed
331
        } else {
332 333
          _this.globalEntry.style.transition = `.2s`
          _this.globalEntry.style.transform = `translateX(0px)`
zhanghaozhe committed
334
        }
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
      }
    })
  }

  closeGlobalEntry = () => {
    localStorage.setItem('globalEntryClosedTime', Date.now().toString())
    this.setState({
      isShowActivityEntry: 0
    })
  }

  isShowGlobalEntryInTime = () => {
    const lastCloseTime = localStorage.getItem('globalEntryClosedTime')
    if (lastCloseTime) {
      const pastDate = new Date(parseInt(lastCloseTime))
      const now = new Date()
      if (now.getFullYear() > pastDate.getFullYear() || now.getMonth() > pastDate.getMonth() || now.getDate() > pastDate.getDate()) {
        this.getStage()
      }
    } else {
      this.getStage()
zhanghaozhe committed
356
    }
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
  }

  render() {
    return <>
      <Routes/>
      {
        !!this.state.isShowActivityEntry && !!this.state.isShowChannel &&
        <div className="year19-index" ref={el => this.globalEntry = el} onTransitionEnd={() => {
          this.globalEntry.style.transition = ''
        }}>
          <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/treasure-active/m/global-entry.png"
               alt=""/>
        </div>
      }
    </>
  }
373 374
}

zhanghaozhe committed
375
export default compose(
376 377 378 379 380
  connect(
    state => ({user: state.user}),
    {setCurrentUser, startFetchUser}
  ),
  withRouter
381
)(App)