import React, {Component} from 'react'
import {http, getParam, browser, SendMessageToApp} from '@/utils'
import PythonDes from './pythomDes'
import PythonStudy from './pythonStudy'
import {connect} from "react-redux"
import {addDays} from "date-fns"
import cookie from "js-cookie"
import {setCurrentUser, startFetchUser} from "@/store/userAction"
import {Toast} from "antd-mobile"
import {WxLogin} from "@common/index"


@connect(state => ({
        user: state.user
    }),
    {setCurrentUser, startFetchUser}
)
class ML extends Component {
    constructor(props) {
        super(props)
        this.state = {
            isPay: '',
            userInfoList: [],
            isAppUpdate: false,
            backwardVersion: false, // 默认是新版本
            isWxlogin: false
        }
    }

    componentDidMount() {
        document.title = '机器学习小课 [精讲8大经典算法，在线编程，无需安装环境，会 python 即可学习] - 七月在线'
        const _this = this
        this.fetchCourseInfo()
        // 获取App登录信息
        window['loginInfo'] = result => {
            _this.loginInfo(result)
        }


        if (browser.isWeixin && getParam('oid')) {
            this.isweixinPay()
        }
        if (getParam('weixinpay')) {
            this.payCallback()
        }
    }

    // 微信内部支付回调
    isweixinPay = () => {
        let _this = this
        let weixin_code = getParam('code')
        if (weixin_code) {
            if (getParam('oid') === undefined) {
                return
            } else {
                http.get(`${API['base-api']}/pay/wxpay/pub_charge/oid/${getParam('oid')}/code/${weixin_code}`).then((res) => {
                    if (res.data.errno === 0) {
                        let data = res.data.data

                        function onBridgeReady() {
                            WeixinJSBridge.invoke(
                                'getBrandWCPayRequest', {
                                    appId: data.appId,                //公众号名称，由商户传入
                                    timeStamp: data.timeStamp,        //时间戳，自1970年以来的秒数
                                    nonceStr: data.nonceStr,          //随机串
                                    package: data.package,
                                    signType: data.signType,          //微信签名方式：
                                    paySign: data.paySign             //微信签名
                                },
                                function (res) {
                                    if (res.err_msg == "get_brand_wcpsys/order_status/ay_request:ok") {
                                        Toast.info('支付成功', 2)
                                        _this.intervalPayStatus = setInterval(function () {
                                            http.get(`${API['base-api']}/m/orderState/oid/${getParam('oid')}`).then(res => {
                                                if (res.data.errno === 401) {
                                                    clearInterval(_this.intervalPayStatus)
                                                    _this.intervalPayStatus = null
                                                    location.reload()
                                                }
                                            })
                                        }, 1000)
                                    } else {
                                        Toast.info('支付失败', 2)
                                    }
                                }
                            )
                        }

                        if (typeof WeixinJSBridge == "undefined") {
                            if (document.addEventListener) {
                                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
                            } else if (document.attachEvent) {
                                document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
                                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
                            }
                        } else {
                            onBridgeReady()
                        }
                    }
                })
            }
        }
    }
    // 支付完成之后获取状态
    payCallback = () => {
        const _this = this
        // 支付回调
        // 定时器轮训获取订单状态
        _this.intervalPayStatus = setInterval(function () {
            http.get(`${API['base-api']}/m/orderState/oid/${getParam('oid')}`).then(res => {
                if (res.data.errno === 401) {
                    clearInterval(_this.intervalPayStatus)
                    _this.intervalPayStatus = null
                    location.reload()
                }
            })
        }, 1000)
    }

    isWxloginFun = (val) => {
        this.setState({isWxlogin: val})
    }
    // 获取app登录数据
    loginInfo = (result) => {
        this.setState({
            userInfoList: result
        }, () => {
            if (this.state.userInfoList.length) {
                this.props.startFetchUser()
                this.appLogin()
            }
        })

    }

    // 保存cookie
    appLogin = () => {
        let expires = addDays(new Date(), 90)
        this.state.userInfoList.map((item, index) => {
            cookie.set("token", item.token, {expires, path: '/', domain: '.julyedu.com'})
            cookie.set("plat", item.plat, {expires, path: '/', domain: '.julyedu.com'})
            cookie.set("uid", item.uid, {expires, path: '/', domain: '.julyedu.com'})
            cookie.set("uname", item.uname, {expires, path: '/', domain: '.julyedu.com'})
            cookie.set("avatar_file", item.avatar_file, {expires, path: '/', domain: '.julyedu.com'})
        })

        if (cookie.get("token") && cookie.get("uid")) {
            this.setState({
                isAppUpdate: true
            })
            this.fetchCourseInfo()
        }

        this.props.setCurrentUser(this.transformUser(this.state.userInfoList))
    }

    transformUser = res => {
        let payload

        res.map((item, index) => {
            payload = {
                hasError: false,
                data: {
                    username: item.uname,
                    avatar: item.avatar_file,
                    token: item.token,
                    uid: item.uid
                },
                isFetching: false
            }
        })

        return payload
    }


    fetchCourseInfo = () => {
        const id = getParam('id')
        http.get(`${API.home}/m/course/detail/${id}`).then((res) => {
            const {data, code} = res.data
            if (code === 200) {
                let version = getParam('version')
                if (version) {
                    version = version.replace(/\./g, '').slice(0, 3)
                    if (browser.isAndroidApp && version < 453) { // 安卓的低版本
                        this.setState({
                            backwardVersion: true,
                            isPay: 0,
                        })
                    } else if (browser.isIOSApp && version < 380) { // ISO的低版本
                        this.setState({
                            backwardVersion: true,
                            isPay: 0,
                        })
                    } else { // 安卓/IOS 的高版本
                        if (data.course_info.is_pay === 1) { // 在APP内未登录-去登陆-登录后还显示此页；如果是已购买的用户 就需要跳转到 APP已购买的原生页面
                            SendMessageToApp('toSyllabusChapter', id) // 跳转到APP的已购买详情页 id 是课程ID
                            return
                        }
                        this.setState({
                            backwardVersion: false,
                            isPay: data.course_info.is_pay
                        })
                    }
                } else {
                    this.setState({
                        backwardVersion: false,
                        isPay: data.course_info.is_pay
                    })
                }
            }
        })
    }

    render() {
        const {isPay, isAppUpdate, backwardVersion, isWxlogin} = this.state
        // 旧版本 无论购买未购买 都跳转到 未购买的详情页； 如果是已购买就提示更新APP
        return (
            <div>
                {
                    isPay === 0 && (
                        <PythonDes
                            backwardVersion={backwardVersion}
                            isWxloginFun={this.isWxloginFun.bind(this)}
                            history={this.props.history}
                            isAppUpdate={isAppUpdate}
                            isPay={isPay}
                        />
                    )
                }
                {
                    (isPay === 1 && !getParam('version')) && <PythonStudy isAppUpdate={isAppUpdate} />
                }

                {
                    isWxlogin &&
                    <WxLogin history={this.props.history}/>
                }

            </div>
        )
    }
}

export default ML
