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


@connect(state => ({
        user: state.user
    }),
    {setCurrentUser, startFetchUser}
)

class NewVip extends Component {
    state = {
        userInfoList: [],
        isSetmeal: [],
        isshowPrice: false,
        notice_content: '', // 提示
        countdown: '', // 倒计时
        cutindex: 0,
        lowPrice: '',
        tobuyID: '',
        list1: [
            {
                img: 'https://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/39376e2038.png',
                src: '/getDetail?id=280'
            },
            {
                img: 'https://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/e61f810c30.png',
                src: '/getDetail?id=293'
            },
            {
                img: 'https://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/1b56e21e68.png',
                src: '/getDetail?id=196'
            },
            {
                img: 'https://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/07dafc3480.png',
                src: '/getDetail?id=216'
            },
            {
                img: 'https://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/d9ca2ad5e8.png',
                src: '/getDetail?id=262'
            },
            {
                img: 'https://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/a7e5ab0af6.png',
                src: '/getDetail?id=232'
            },
            {
                img: 'https://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/c9a6779b75.png',
                src: '/getDetail?id=181'
            },
            {
                img: 'https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/19VIP/newvip/h5/more2.png',
                src: ''
            }
        ], // 特权1
        list2: [
            {
                img: 'https://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/3665c01210.png',
                src: '/getDetail?id=136'
            },
            {
                img: 'https://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/c7b0eeff40.png',
                src: '/getDetail?id=123'
            },
            {
                img: 'https://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/bfaddc5039.png ',
                src: '/getDetail?id=140'
            },
            {
                img: 'https://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/ab8bb774c3.png',
                src: '/getDetail?id=133'
            },
            {
                img: 'https://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/efa0cad9a5.jpg',
                src: '/getDetail?id=146'
            },
            {
                img: 'https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/19VIP/newvip/h5/more1.png',
                src: ''
            }
        ],  // 特权2
        teaList: [
            {
                img: 'https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/19VIP/newvip/h5/chen.png',
                name: '陈博士'
            },
            {
                img: 'https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/19VIP/newvip/h5/seven.png',
                name: 'Seven'
            },
            {
                img: 'https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/19VIP/newvip/h5/zhu.png',
                name: '褚博士'
            },
            {
                img: 'https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/19VIP/newvip/h5/yang.png',
                name: '杨老师'
            },
            {
                img: 'https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/19VIP/newvip/h5/guan.png',
                name: '管博士'
            },
            {
                img: 'https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/19VIP/newvip/h5/li.png',
                name: '李弘杨'
            },
            {
                img: 'https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/19VIP/newvip/h5/sun.png',
                name: '孙老师'
            },
            {
                img: 'https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/19VIP/newvip/h5/shi.png',
                name: '史老师'
            }
        ], // 讲师
        tip: ['365*24小时不间断使用', '超高性能GPU硬件环境', '预装主流DL框架和数据集', '可自由上传私人数据集'],
    }

    componentDidMount() {
        this.fetchNotice()
        this.fetchVipBag()

        // 获取App登录信息
        window['loginInfo'] = result => {
            this.loginInfo(result)
        }
        document.title = 'VIP会员限时特惠，全平台在线课程免费学，GPU云实验平台免费用！——七月在线';
    }

    // 获取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.fetchNotice()
            this.fetchVipBag()
        }

        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
    }


    fetchVipBag = () => {
        const _this = this
        http.get(`${API.home}/sys/vip_bag`).then(res => {
            const {code, data, msg} = res.data
            if (code === 200) {
                _this.setState({
                    isSetmeal: data
                })

                let lowPrice = Math.min.apply(Math, _this.state.isSetmeal.map((item) => {
                    return item.price1
                }))
                _this.setState({
                    lowPrice: lowPrice
                })

                _this.setState({
                    cutindex: _this.state.isSetmeal.findIndex(item => item.price1 == lowPrice)
                })
                _this.setState({
                    tobuyID: _this.state.isSetmeal[_this.state.cutindex].course_id
                })
            } else {
                Toast.info(msg, 2, null, false)

            }
        })
    }

    fetchNotice = () => {
        const _this = this
        http.get(`${API.home}/sys/notice`).then(res => {
            const {code, data, msg} = res.data
            if (code === 200) {
                _this.setState({
                    notice_content: data.notice_content,
                    date: data.date
                })

                let date = data.date * 1000,
                    day = 0,
                    hours = 0,
                    minutes = 0,
                    seconds = 0
                setInterval(function () {
                    date -= 1000
                    day = `${parseInt(date / (60 * 60 * 24 * 1000))}`
                    hours = `${parseInt((date - day * 86400000) / (60 * 60 * 1000))}`.padStart(2, 0)
                    minutes = `${parseInt((date - day * 86400000 - hours * 3600000) / 60000)}`.padStart(2, 0)
                    seconds = `${parseInt((date - day * 86400000 - hours * 3600000 - minutes * 60000) / 1000)}`.padStart(2, 0)
                    _this.setState({
                        countdown: `剩余${day}天${hours}时${minutes}分${seconds}秒`
                    })
                }, 1000)
            } else {
                Toast.info(msg, 2, null, false)
            }
        })
    }


    // 立即购买显示弹窗
    showPrice = () => {
        const isLogin = !this.props.user.hasError
        if (!isLogin) {
            this.toLogin()
        } else {
            this.setState({
                isshowPrice: true
            })
        }
    }

    toLogin = () => {
        if (!getParam('version')) {
            this.props.history.push('/passport')
        } else {
            SendMessageToApp("toLogin")
        }
    }

    // 关闭弹窗
    close = () => {
        this.setState({
            isshowPrice: false
        })
    }

    // 选择
    tochecked = (item, index) => {
        this.setState({
            cutindex: index,
            tobuyID: item.course_id
        })
    }

    // 弹窗中的去购买
    tobuy = () => {
        const {isSetmeal, cutindex, tobuyID} = this.state
        let id = tobuyID === '' ? isSetmeal[cutindex].course_id : tobuyID
        if (!getParam('version')) {
            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, null, false)
                }
            })
        } else {
            SendMessageToApp("toPay", id)
        }
    }

    render() {
        const {notice_content, date, countdown, list1, list2, tip, teaList, isSetmeal, cutindex, isshowPrice, lowPrice} = this.state
        return (
            <div className='new-vip'>
                {/*banner*/}
                <div className="banner"><img
                    src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/19VIP/newvip/h5/vip-banner.png" alt=""/></div>

                {/*vip倒计时*/}
                {
                    (notice_content || date) &&
                    <div className="notice">
                        {
                            notice_content &&
                            <div className="tip">
                                <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/19VIP/newvip/h5/linlin_icon.png"
                                     alt=""/>
                                <span>{notice_content}</span>
                            </div>
                        }
                        {
                            date &&
                            <div className="time">{countdown}</div>
                        }
                    </div>
                }

                {/*VIP尊享五大服务*/}
                <div className="privilege-box">
                    <div className="privilege-name">VIP尊享五大服务</div>

                    {/*特权1*/}
                    <div className="privilege-content">
                        <PrivilegeTitle num="一" title="直播课程抢先学"/>
                        <PrivilegeCourse data={list1}/>
                    </div>

                    <Connect position={'left'}/>
                    <Connect position={'right'}/>

                    {/*特权2*/}
                    <div className='privilege-content'>
                        <PrivilegeTitle num="二" title="畅学全平台视频课程"/>
                        <PrivilegeCourse data={list2}/>
                    </div>

                    <Connect position={'left'}/>
                    <Connect position={'right'}/>

                    {/*特权3*/}
                    <div className='privilege-content'>
                        <PrivilegeTitle num="三" title="GPU&CPU双云平台免费用"/>

                        <div className="privilege-list-row">
                            <div className="privilege-list-gpu">
                                <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/19VIP/newvip/h5/gpu1_bj%402x.png"
                                     alt=""/>
                                <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/19VIP/newvip/h5/gpu2_bj%402x.png"
                                     alt=""/>
                            </div>

                            <div className="privilege-list-tip">
                                {
                                    tip.map((item, index) => {
                                        return (
                                            <div className='privilege-tip-item' key={index}>
                                                <span>{index + 1}</span>
                                                {item}
                                            </div>
                                        )
                                    })
                                }
                            </div>
                        </div>
                    </div>

                    <Connect position={'left'}/>
                    <Connect position={'right'}/>

                    {/*特权4*/}
                    <div className='privilege-content'>
                        <PrivilegeTitle num="四" title="讲师/助教团队24小时答疑"/>


                        <p className={'privilege-teacher'}>多达100人的AI师资团队提供咨询、答疑服务，助力涨薪</p>


                        <TeacherList data={teaList}/>
                    </div>

                    <Connect position={'left'}/>
                    <Connect position={'right'}/>

                    {/*特权5*/}
                    <div className='privilege-content'>
                        <PrivilegeTitle num="五" title="在线作业及测评平台"/>

                        <div className='privilege-test'>
                            <img
                                src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/19VIP/newvip/h5/ce1_bj%402x.png"
                                alt=""/>
                            <img
                                src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/19VIP/newvip/h5/ce2_bj%402x.png"
                                alt=""/>
                        </div>
                    </div>
                </div>
                <div className="tobuy" onClick={() => this.showPrice()}>
                    {lowPrice}元 立即报名
                </div>


                {
                    isshowPrice &&
                    <div>
                        <div className="checkout-mbc" onClick={() => this.close()}></div>
                        <div className="checkout-box">
                            <div className="title">
                                <span>选择套餐</span>
                                <span className={'close'} onClick={() => this.close()}>&#10005;</span>
                            </div>
                            {
                                isSetmeal.map((item, index) => {
                                    return (
                                        <div
                                            className={`checkout-list ${cutindex === index ? "list-checked" : 'list-check'}`}
                                            key={index}
                                            onClick={() => this.tochecked(item, index)}
                                        >
                                            <div className="type">{item.bag_name}</div>
                                            <div className='center'>
                                                {
                                                    item.discounts_reason === '首购特惠' &&
                                                    <div className="discounts-reason">{item.discounts_reason}</div>

                                                }
                                                {
                                                    item.discounts_reason !== '首购特惠' &&
                                                    <div className="discounts-reason discounts-reason2">{item.discounts_reason}</div>
                                                }
                                                <div className="price">
                                                    ¥
                                                    <span className={'new-price'}>{item.price1}</span>
                                                    <s className={'old-price'}>¥{item.price0}</s>
                                                </div>
                                            </div>
                                            <div className="check-box">
                                                <span className={`${cutindex === index ? "checked" : 'check'}`}></span>
                                            </div>
                                        </div>
                                    )
                                })
                            }

                            <button className='check-tobuy' onClick={() => this.tobuy()}>立即购买</button>
                        </div>
                    </div>
                }


            </div>
        )
    }
}

function PrivilegeTitle(props) {
    return (
        <div className="privilege-title"><img
            src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/19VIP/newvip/h5/viplog.png" alt=""/>
            <span>服务{props.num}</span> {props.title}
        </div>
    )
}

function PrivilegeCourse(props) {
    return (
        <div className="privilege-list">
            {
                props.data.map((item, index) => {
                    return (
                        <div key={index}>
                            {
                                item.src === '' &&
                                <a className={'course-box'}>
                                    <img src={item.img} alt=""/>
                                </a>
                            }
                            {
                                item.src !== '' &&
                                <a className={'course-box'} href={item.src}>
                                    <img src={item.img} alt=""/>
                                </a>
                            }
                        </div>
                    )
                })
            }

        </div>
    )
}

function TeacherList(props) {
    return (
        <div className="teacher-list">
            {
                props.data.map((item, index) => {
                    return (
                        <div className="teacher-item" key={index}>
                            <img src={item.img} alt=""/>
                            <span>{item.name}</span>
                        </div>
                    )
                })
            }
        </div>
    )
}

function Connect(props) {
    return (
        <div className={`connect ${props.position}`}>
            <span className='top'></span>
            <span className='con'></span>
            <span className='bottom'></span>
        </div>
    )
}


export default withRouter(NewVip)
