import React, {Component} from 'react'
import './index.scss'
import Description from './Description/index.js'
import Study from './Study/index.js'
import Team from './Team/index.js'
import Experience from './Experience/index.js'
import Progream from './Progream/index.js'
import Selection from './Selection'
import Mask from './../poup/index.js'
import InAction from "./InAction"
import ShareRank from "@components/detail/shareRank"
import {http, getParam, SendMessageToApp, browser} from '@/utils'
import {connect} from 'react-redux'
import {Toast} from "antd-mobile"
import {CallApp} from "@common/index"

@connect(state => ({
    user: state.user
}))
class PythonDes extends Component {
    constructor(props) {
        super(props)
        this.state = {
            syllabus: [], // 阶梯学习
            allSyllabus: [], // 阶梯学习
            allSyllabusShow: false,
            allPractice: [], // 课后实操
            toApp: false,
            payMoney: 0,
            isOnline: true, //课程是否上架
            courseInfo: {},
            isShowChannel: window.sessionStorage.getItem('isShowSiteWindowByChannel'),
            orderId: ''
        }
    }

    // 立即报名
    // signUp = () => {
    //   this.statistics(3)
    //   // 已登录
    //   if (!this.props.user.hasError) {
    //     this.toDetail()
    //   } else {// 未登录
    //     this.toLogin()
    //   }
    // }

    // 立即体验type=1、立即报名type=3、9.9特价试学type=2
    tryLearn = type => {
        this.statistics(type)
        // 已登录
        if (!this.props.user.hasError) {
            this.creatOid(type)
        } else {// 未登录
            this.toLogin()
        }
    }
    creatOid = (type) => {
        let url = ''
        if (type == 3) {
            url = `${API['base-api']}/sys/it_baoming/create`
        } else {
            url = `${API['base-api']}/sys/trial_create`
        }
        http.post(url, {course_id: getParam('id')}).then(res => {
            const {errno, data, msg} = res.data
            if (errno === 200) {
                this.setState({
                    orderId: data.oid
                })
                this.weixinPay(data.oid)
            } else {
                Toast.info(msg, 2)
            }
        })
    }
    // 微信支付
    weixinPay = (orderId) => {
        // 微信内部-支付
        if (browser.isWeixin) {
            window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx23dac6775ac82877&redirect_uri=" + encodeURIComponent(window.location.href + "&aa=bb&oid=" + orderId).toLowerCase() + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
        } else {
            // 微信外部-支付
            http.get(`${API['base-api']}/pay/wxpay/wap_charge/oid/${orderId}`).then((res) => {
                if (res.data.errno === 0) {
                    window.location.href = res.data.data.url + "&redirect_url=" + encodeURIComponent(window.location.href + "&weixinpay=1&oid=" + orderId).toLowerCase()
                } else {
                    Toast.info(res.data.msg, 2)
                }
            })
        }
    }

    toLearn = () => {
        const {backwardVersion} = this.props
        http.post(`${API['home']}/m/it/user/trialCourse`, {course_id: getParam('id')}).then((res) => {
            const {code, msg} = res.data
            if (code == 200) {
                if (!getParam('version')) { // H5
                    this.setState({
                        toApp: true
                    })
                } else { // APP
                    if (backwardVersion) {
                        Toast.info('当前版本不支持该课程模式，请升级到最新版本或前往PC端体验', 2)
                    } else {
                        SendMessageToApp("toLearn", getParam('id'))
                    }
                }
            } else {
                Toast.info(msg, 2)
            }
        })
    }

    closePop = () => {
        this.setState({
            toApp: false
        })
    }

    toDetail = () => {
        const {backwardVersion} = this.props
        const id = getParam('id')
        if (!getParam('version')) { // H5
            http.get(`${API['base-api']}/m/cart/addtopreorder/[${id}]`).then((res) => {
                if (res.data.errno === 0) {
                    this.props.history.push(`/order?id=${id}`, {simple: 1})
                } else {
                    Toast.info(res.data.msg, 2)
                }
            })
        } else { // APP
            if (backwardVersion) {
                Toast.info('当前版本不支持该课程模式，请升级到最新版本或前往PC端购买', 2)
                let onlyoneUse = setTimeout(() => {
                    clearTimeout(onlyoneUse)
                    onlyoneUse = null
                    SendMessageToApp('toPay', id)
                }, 2000)
            } else {
                SendMessageToApp('toPay', id)
            }
        }
    }

    toLogin = () => {
        if (!getParam('version')) { // H5
            if (browser.isWeixin) {
                this.props.isWxloginFun(true);
            } else {
                this.props.history.push('/passport')
            }
        } else { // APP
            SendMessageToApp("toLogin")
        }
    }

    showAll = (key) => {
        if (key === 1) {
            this.setState({
                syllabus: this.state.allSyllabus,
                allSyllabusShow: true,
            })
        }
        if (key === 2) {
            this.setState({
                practice: this.state.allPractice,
                allPracticeShow: true,
            })
        }
    }
    hideSome = (key) => {
        if (key === 1) {
            this.setState({
                syllabus: this.state.allSyllabus.slice(0, 2),
                allSyllabusShow: false,
            })
        }
        if (key === 2) {
            this.setState({
                practice: this.state.allPractice.slice(0, 2),
                allPracticeShow: false,
            })
        }
    }

    getStatus = () => {
        http.get(`${API['home']}/web/it_detail?course_id=${getParam('id')}`).then(res => {
            const {code, data, msg} = res.data
            if (code == 200) {
                this.setState({
                    syllabus: data.syllabus.slice(0, 2),
                    allSyllabus: data.syllabus,
                    allPractice: data.practice,
                    payMoney: data.course_info.price1,
                    courseInfo: data.course_info
                })
            } else {
                Toast.info(msg)
            }
        })
    }

    componentDidMount() {
        this.getStatus()

        const {backwardVersion, isPay} = this.props
        if (backwardVersion && isPay === 1) {
            Toast.info('当前版本不支持该课程模式，请升级到最新版本或前往PC端学习', 2)
        }
    }

    // 统计
    statistics = type => {
        http.post(`${API.home}/web/it_click_num/${getParam('id')}`, {type})
    }


    shouldComponentUpdate(nextProps, nextState, nextContext) {
        if (this.props.isAppUpdate !== nextProps.isAppUpdate) {
            this.getStatus()
            return false
        }
        return true
    }

    render() {
        const {
            syllabus,
            allSyllabusShow,
            toApp,
            payMoney,
            isOnline,
            courseInfo
        } = this.state
        return (
            <div className={'python__des'}>
                <div className={'des__start'}></div>
                {
                    !!courseInfo.is_dist && <ShareRank courseInfo={courseInfo}/>
                }
                <div className={'course__introduce'}></div>
                {
                    isOnline
                        ? (
                            <div className={'bottom__btn_group'}>
                                <div className={'course__price'}>
                                    <div className={'money'}>{payMoney}<span style={{fontSize: '18px'}}>元</span></div>
                                    <div className={'discount'}>
                                        限时特惠
                                        <div className={'triangle'}></div>
                                    </div>
                                </div>

                                <div className={'btn__group'}>
                                    <div className={'try__study'} onClick={() => {
                                        this.tryLearn(3)
                                    }}>立即报名
                                    </div>
                                    <div className={'sign__now'} onClick={() => {
                                        this.tryLearn(2)
                                    }}>9.9特价试学
                                    </div>
                                </div>
                            </div>
                        )
                        : (
                            <div className="bottom__btn_group">
                                <p className="online__label">Python人工智能</p>
                                <button className="online__button">即将上架 敬请期待</button>
                            </div>
                        )
                }

                {
                    this.state.isShowChannel == 1 &&
                    <CallApp className='toapp'/>
                }
                {/* 课程介绍 */}
                <Description/>

                <Study syllabus={syllabus} allSyllabusShow={allSyllabusShow} show={this.showAll}
                       hide={this.hideSome}></Study>

                {/*精选习题*/}
                <Selection/>

                {/*项目实战*/}
                <InAction/>

                <Team/>

                {/* 试学体验 */}
                <Experience tryLearn={this.tryLearn} isOnline={isOnline}/>
                <img
                    style={{
                        display: 'block',
                        width: '100%',
                        height: '8px'
                    }}
                    src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/mlCourse/m/di.png"
                    alt=""
                />

                {/* 常见问题 */}
                <Progream/>
                {
                    toApp && (<Mask type={1} closePop={this.closePop}/>)
                }
            </div>
        )
    }
}

function DefineItem(props) {
    const {item, item: {desInfo}} = props
    return (
        <div className={'number_one'}>
            <img className={'trophy'} src={item.titleUrl}></img>
            <p className={'item__title'}>{item.title}</p>
            <p className={'item__subtitle'} style={{width: item.subWidth}}>{item.subTitle}</p>
            <img style={{width: desInfo.width, height: desInfo.height}} src={item.bottomUrl}></img>
        </div>
    )
}

export default PythonDes
