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 { 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'
import stringify from 'json-stringify-safe'


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


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

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

class App extends Component {

  static displayName = 'App'

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

  records = []

  pathnameBlacklist = ['/country', '/passport']

  firstLoad = true

  componentWillMount() {
    if (!getParam('version')) {
      if (!cookie.get('qimoClientIdedu')) {
        this.getqimoClientId()
      } else {
        window.qimoClientId = cookie.get('qimoClientIdedu')
      }
    }
  }

  componentDidMount() {
    this.umengStatistic()
    //平台信息
    !getParam('version') && cookie.set('plat', '5', {domain: '.julyedu.com'})


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

    this.getUser()
    this.utm()

    const {history} = this.props


    this.setNavigationRecord(this.props.location, this.props.history.action)
    this.setPreviousLocation()


    history.listen((location, action) => {
      this.firstLoad = false
      this.setNavigationRecord(location, action)
      this.utm()

      if (cookie.get('uid') && this.props.user.hasError) {
        this.getUser()
      }
      if (location.pathname === '/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
            }
          }
        }
      } else {
        this.removeShareCodeCookie()
      }
    })

    if (!getParam('version')) {
      this.QimoClient()
    }
  }

  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})
    }

    location.state && location.state.records
      ? (location.state.records = this.records)
      : location.state ? location.state = {...location.state, records: this.records}
      : (location.state = {records: this.records})
  }


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

    if (zhihu_cb) {
      let data = {
        'zhihu_cb': zhihu_cb
      }

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

    }
  }

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

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

      //针对2019双旦活动特殊处理，活动结束后删掉
      //treasure_code=3538333139312c31&origin=2&aa=bb&code=0211aiYB1VVOL60rmWWB1367YB11aiY7&state=STATE
      if (getParam('treasure_code') == '3538333139312c31' && code == '0211aiYB1VVOL60rmWWB1367YB11aiY7') {
        return
      }

      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 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)
            this.props.setCurrentUser(initialState)
          }
        })


    } else {
      http.get(`${API.home}/m/user_info`).then(res => {
        this.props.setCurrentUser(this.transformUser(res))
      })
    }

  }

  componentDidUpdate() {

    this.setPreviousLocation()

    if (!this.props.user.hasError && getParam('redirect')) {
      window.location.href = getParam('redirect')
    }
  }

  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
        }
      } = 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) {
      //移除红包统计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: {}
      }
    }
  }


  // 七陌客服代码 start
  getqimoClientId = () => {
    http.post(`${API['home']}/qiMoUserId`)
      .then(res => {
        if (res.data.code == 200) {
          window.qimoClientId = res.data.data.userId
          cookie.set('qimoClientIdedu', res.data.data.userId, {domain: '.julyedu.com'})
        }
      })
      .catch(function () {
      })
  }

  QimoClient = () => {

    let zhihu_cb = getParam('cb')
    var src = ''
    // 知乎投放
    if (zhihu_cb) {
      src = 'https://webchat.7moor.com/javascripts/7moorInit.js?accessId=e2ca4f90-2d04-11ea-84c3-43908ae47640&autoShow=false&language=ZHCN'
    } else {
      // m端
      src = 'https://webchat.7moor.com/javascripts/7moorInit.js?accessId=fbcf9aa0-2d03-11ea-84c3-43908ae47640&autoShow=false&language=ZHCN'
    }

    var script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = src
    script.async = 'async'
    document.body.appendChild(script)

  }

  // 七陌客服代码 end


  render() {
    return <>
      <Routes/>
      {/*<Link className={'year19-index'} to="/year/yearindex">*/}
        {/*<img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/newyear20/PC/pc-yearindex.png" alt=""/>*/}
      {/*</Link>*/}
    </>
  }
}

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