import React, { Component } from 'react'
import './index.scss'
import { http, SendMessageToApp, getParam, browser } from '@/utils'
import CommonContainer from './../../common/commonContainer/index'
import CourseItem from '../../../../blessingPreheat/courseItem/index'
import { withRouter } from "react-router-dom"
import CommonPopup from './../../common/commonPopup/index'
import { Toast } from 'antd-mobile'
import QRCode from 'qrcode'
import { connect } from "react-redux"
import dateFns from 'date-fns';

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

class YearCourse extends Component {
    constructor(props) {
        super(props)
        this.state = {
            tofreeStudy: false,
            basic: {
                course: [],
                courseList: [],
                isMore: false,
                addshowMore: false,
            },
            advanced: {
                course: [],
                courseList: [],
                isMore: false,
                addshowMore: false,
            },
            higher: {
                course: [],
                courseList: [],
                isMore: false,
                addshowMore: false,
            },
            expand: {
                course: [],
                courseList: [],
                isMore: false,
                addshowMore: false,
            },
            bigcourse: {
                course: [],
                courseList: [],
                isMore: false,
            },
            freecourse: {
                course: [],
                courseList: [],
                isMore: false,
            },
            groupcourse: {
                course: [],
                courseList: [],
                isMore: false,
            },
            isshowFollow: false, // 是否提示关注公众号
            wish: {
                id: '',
                key: ""
            },
            followBarcode: '',
            qrUrl: '',
            sum: '',
            removable: '',
            currentId: '',
        }
    }

    componentDidMount() {
        this.getTeamInfo()
        this.getLength()
        this.fetchBigCourse()
        // this.fetchFreeCourse()
        this.fetchGroupCourse()
        // AI之路-基础
        this.fetchAICourse('one', false)
        // AI之路-进阶
        this.fetchAICourse('two', false)
        // AI之路-高阶
        this.fetchAICourse('three', false)
        // AI之路-拓展
        this.fetchAICourse('four', false)
    }

    shouldComponentUpdate(nextProps, nextState, nextContext) {
        if (this.props.isAppUpdate !== nextProps.isAppUpdate) {
            this.getTeamInfo()
            this.getLength()
            this.fetchBigCourse()
            // this.fetchFreeCourse()
            this.fetchGroupCourse()
            // AI之路-基础
            this.fetchAICourse('one')
            // AI之路-进阶
            this.fetchAICourse('two')
            // AI之路-高阶
            this.fetchAICourse('three')
            // AI之路-拓展
            this.fetchAICourse('four')
            return false
        }
        return true
    }

    getLength = () => {
        let _this = this
        http.get(`${API.home}/activity/wish_sum`).then(res => {
            const { code, data } = res.data
            if (code == 200) {
                _this.setState({
                    sum: data.sum
                })
            }
        })
    }

    fetchBigCourse = () => {
        const { bigcourse } = this.state
        http.get(`${API.home}/activity/preheat_data`).then(res => {
            const { code, data } = res.data
            if (code === 200) {
                this.setState({
                    bigcourse: Object.assign({}, bigcourse, {
                        isMore: false,
                        course: data,
                        courseList: data,
                    })
                })
            }
        })
    }
    fetchFreeCourse = () => {
        const { freecourse } = this.state
        http.get(`${API['base-api']}/assistance/detail`).then(res => {
            const { errno, data } = res.data
            if (errno === 200) {
                this.setState({
                    freecourse: Object.assign({}, freecourse, {
                        isMore: data.course_info.length > 4 ? true : false,
                        course: data.course_info.length > 4 ? data.course_info.filter((item, index) => index < 4) : data.course_info,
                        courseList: data.course_info,
                    })
                })
            }
        })
    }

    fetchGroupCourse = () => {
        const { groupcourse } = this.state
        http.get(`${API.home}/activity/excellent_course`).then(res => {
            const { code, data } = res.data
            if (code === 200) {
                this.setState({
                    groupcourse: Object.assign({}, groupcourse, {
                        isMore: data.length > 4 ? true : false,
                        course: data.length > 4 ? data.filter((item, index) => index < 4) : data,
                        courseList: data,
                    })
                })
            }
        })
    }

    fetchAICourse = (key, addshowMore) => {
        http.get(`${API.home}/activity/four_stage/${key}`).then(res => {
            const { code, data } = res.data
            if (code === 200) {
                this.getList(key, data, addshowMore)
            }
        })
    }

    getList = (key, data, addshowMore) => {
        const { basic, advanced, higher, expand } = this.state
        if (key === 'one') {
            this.setState({
                basic: Object.assign({}, basic, {
                    isMore: data.length > 4 && !addshowMore ? true : false,
                    course: data.length > 4 && !addshowMore ? data.filter((item, index) => index < 4) : data,
                    courseList: data,
                    addshowMore: addshowMore,
                })
            })
        }
        if (key === 'two') {
            this.setState({
                advanced: Object.assign({}, advanced, {
                    isMore: data.length > 4 && !addshowMore ? true : false,
                    course: data.length > 4 && !addshowMore ? data.filter((item, index) => index < 4) : data,
                    courseList: data,
                    addshowMore: addshowMore,
                })
            })
        }
        if (key === 'three') {
            this.setState({
                higher: Object.assign({}, higher, {
                    isMore: data.length > 4 && !addshowMore ? true : false,
                    course: data.length > 4 && !addshowMore ? data.filter((item, index) => index < 4) : data,
                    courseList: data,
                    addshowMore: addshowMore,
                })
            })
        }
        if (key === 'four') {
            this.setState({
                expand: Object.assign({}, expand, {
                    isMore: data.length > 4 && !addshowMore ? true : false,
                    course: data.length > 4 && !addshowMore ? data.filter((item, index) => index < 4) : data,
                    courseList: data,
                    addshowMore: addshowMore,
                })
            })
        }
    }

    toQQque = () => {
        if (!getParam('version')) {
            location.href = 'http://q.url.cn/s/Vbkup6m?_type=wpa'
        } else {
            SendMessageToApp("toQQ", 'https://q.url.cn/AB8aue?_type=wpa&qidian=true')
        }
    }

    // 去课程详情页
    toCourse = (courseId) => {
        const { history } = this.props
        if (!getParam('version')) {
            history.push(`/detail?id=${courseId}`)
        } else {
            SendMessageToApp("toCourse", courseId)
        }
    }

    handleToMore = (key) => {
        let data = {}
        if (this.state[key]['isMore']) {
            data[key] = {
                isMore: !this.state[key]['isMore'],
                course: this.state[key]['courseList'],
                courseList: this.state[key]['courseList'],
                addshowMore: !this.state[key]['addshowMore']
            }
            this.setState({
                ...data
            })
        } else {
            data[key] = {
                isMore: !this.state[key]['isMore'],
                course: this.state[key]['courseList'].filter((item, index) => index < 4),
                courseList: this.state[key]['courseList'],
                addshowMore: !this.state[key]['addshowMore']
            }

            this.setState({
                ...data
            })
        }
    }

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

    // 免费学习
    freeStudy = () => {
        this.setState({
            tofreeStudy: true,
        })
    }

    // 关闭弹框
    closePopup = () => {
        this.setState({
            tofreeStudy: false,
        })
    }

    closePopupWish = () => {
        const _this = this
        _this.setState({
            isshowFollow: false
        })

        setTimeout(function () {
            _this.toJoinList(_this.state.wish.id, _this.state.wish.key)
        }, 200)
    }

    getQRcodeUrl = () => {
        let _this = this
        http.get(`${API['base-api']}/wx/user_temporary_qrcode/${_this.props.user.data.uid}`)
            .then(res => {
                const { errno, data, msg } = res.data
                if (errno == 0) {
                    this.setState({
                        qrUrl: data.url
                    })
                    QRCode.toDataURL(data.url, (err, url) => {
                        this.setState({
                            followBarcode: url,
                        })
                    })
                } else {
                    Toast.info(msg, 2)
                }
            })
    }

    // 点击加入心愿单登录验证，在判断是否关注公众号，已关注的话直接加入，未关注弹出二维码弹窗，点击关闭按钮加入心愿单
    addWishList = (id, key) => {
        const _this = this
        const isLogin = !this.props.user.hasError
        _this.setState({
            wish: {
                id: id,
                key: key
            }
        })

        if (isLogin) {
            _this.isFollow(id, key)
        } else {
            _this.toLogin()
        }
    }

    isFollow = (id, key) => {
        const _this = this
        http.get(`${API.home}/sys/user/isFollowWeChat`).then(res => {
            const { code, data, msg } = res.data
            if (code === 200) {
                _this.setState({
                    isshowFollow: !data.is_follow
                })

                if (!_this.state.isshowFollow) {
                    _this.toJoinList(id, key)
                } else {
                    _this.getQRcodeUrl()
                }
            } else {
                Toast.info(msg, 2)
            }
        })
    }

    toJoinList = (id, key) => {
        const _this = this
        http.post(`${API.home}/activity/join_list`, { course_id: id })
            .then(res => {
                const { code, msg } = res.data
                if (code == 200) {
                    Toast.success('已成功加入心愿单', 3)
                    _this.getLength()
                    if (key === '1') {
                        _this.fetchAICourse('one', _this.state.basic.addshowMore)
                    }
                    if (key === '2') {
                        _this.fetchAICourse('two', _this.state.advanced.addshowMore)
                    }
                    if (key === '3') {
                        _this.fetchAICourse('three', _this.state.higher.addshowMore)
                    }
                    if (key === '4') {
                        _this.fetchAICourse('four', _this.state.expand.addshowMore)
                    }
                    if (key === 'group') {
                        _this.fetchGroupCourse()
                    }
                } else {
                    Toast.info(msg, 2)
                }
            })
    }

    // 安卓手机保存二维码
    saveImage = () => {
        let version = getParam('version')
        version = typeof version === 'string' ? version.replace('.', '').replace('.', '').slice(0, 3) : ''
        const QRCodeUrl = this.state.qrUrl
        if (version && parseInt(version) < 451) {
            Toast.info('当前不支持此功能，升级到最新版本app可以点击保存二维码！', 3, null, false)
        } else {
            SendMessageToApp('generateQRCode', QRCodeUrl)
        }
    }

    saveImage2 = () => {
        let version = getParam('version')
        version = typeof version === 'string' ? version.replace('.', '').replace('.', '').slice(0, 3) : ''
        const QRCodeUrl = 'https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/2018christyear/h5/qrcode.jpg'
        if (version && parseInt(version) < 451) {
            Toast.info('当前不支持此功能，升级到最新版本app可以点击保存二维码！', 3, null, false)
        } else {
            SendMessageToApp('saveImage', QRCodeUrl)
        }
    }

    // 获取队伍信息
    getTeamInfo = () => {
        http.get(`${API.home}/sys/treasure/teamInfo`).then(res => {
            const { code, data, msg } = res.data
            if (code === 200) {
                const { info, removable_data } = data
                this.setState({
                    removable: info.removable,
                    currentId: info.removable > 0 ? removable_data[0].id : null
                })
            } else {
                Toast.info(msg)
            }
        })
    }

    // 跳转到我的宝箱列表页
    toBoxList = () => {
        const isLogin = !this.props.user.hasError
        const { currentId } = this.state
        let search = ''
        if (currentId) {
            search = `?id=${currentId}`
        }
        if (isLogin) {
            if (!getParam('version')) {
                this.props.history.push(`/box/yearTreasure${search}`)
            } else {
                this.props.history.push(`/box/yearTreasure${search}?version=${getParam('version')}`)
            }
        } else {
            this.toLogin()
        }
    }

    toYearWish = () => {
        const isLogin = !this.props.user.hasError
        if (isLogin) {
            if (!getParam('version')) {
                this.props.history.push('/year/yearWish')
            } else {
                this.props.history.push(`/year/yearWish?version=${getParam('version')}`)
            }

        } else {
            this.toLogin()
        }

    }

    toInviteFriends = (oid, params = {}) => {
        const { history } = this.props
        if (getParam('version')) {
            let data = {
                title: `【仅剩${params.number}个名额】我${params.price}元拼了《${params.course_title}》`,
                desc: params.course_title,
                link: `${API.m}/togroup?id=${oid}&is_originator=1`,
                imgUrl: params.image_name,
            }
            SendMessageToApp("toShare", data)
        } else {
            history.push(`/togroup?id=${oid}`);
        }
    }

    isCountDown = (condition, val) => {
        if (condition) {
            return val;
        }
        return '';
    }

    formatTitleAndKey = (key) => {
        let data = null;
        switch (key) {
            case 1:
                data = {
                    title: '基础',
                    key: 'basic'
                };
                break;
            case 2:
                data = {
                    title: '进阶',
                    key: 'advanced'
                };
                break;
            case 3:
                data = {
                    title: '高阶',
                    key: 'higher'
                };
                break;
            case 4:
                data = {
                    title: '扩展',
                    key: 'expand'
                };
                break;
            default:
                data = null;
                break;
        }
        return data;
    }

    formatCourseData = (key) => {
        const { basic, advanced, higher, expand } = this.state;
        let data = null;
        switch (key) {
            case 1:
                data = basic;
                break;
            case 2:
                data = advanced;
                break;
            case 3:
                data = higher;
                break;
            case 4:
                data = expand;
                break;
            default:
                data = null;
                break;
        }
        return data;
    }

    toCart = (id) => {
        const { history } = this.props;
        http.post(`${API.home}/m/cart/add`, {
            course_id: id
        }).then((res) => {
            const { code, msg } = res.data;
            // code 15001 已加入购物车
            if (code === 200 || code === 15001) {
                if(getParam('version')) {
                    SendMessageToApp('toShoppingCart')
                }else {
                    history.push('/shopcart');
                }
            } else if (code === 4030 || code === 4040) {
                this.toLogin();
            } else {
                Toast.info(msg, 2);
            }
        })
    };

    toContinueBargain = (id, price, code, image) => {
        const { history } = this.props;
        if(getParam('version')) {
            let data = {
                title: '我发现一门好课，快来帮我砍价吧！',
                desc: `我已经砍了${price}元，看看你能砍多少`,
                link: `${API.m}/bargain-middle-page?id=${id}&bargaincode=${code}&is_originator=1`,
                imgUrl: image,
            }
            SendMessageToApp("toShare", data)
        }else {
            history.push(`/bargain-middle-page?id=${id}&bargaincode=${code}&is_originator=1`);
        }
    }

    // 砍完价去支付
    bargainToOrder = (id) => {
        const { history, user } = this.props;
        if(user.hasError) {
            this.toLogin();
        }else{
            if(getParam('version')) {
                SendMessageToApp('toPay', id)
            }else {
                http.get(`${API['base-api']}/m/cart/addtopreorder/[${id}]`).then((res) => {
                    const { errno, msg } = res.data;
                    if (errno === 0) {
                        history.push(`/order?id=[${id}]`, {bargain: 1});
                    } else {
                        Toast.info(msg, 2);
                    }
                })
            }
        }
    }

    render() {
        const {
            bigcourse,
            freecourse,
            groupcourse,
            basic,
            advanced,
            higher,
            expand,
            removable,
            sum,
        } = this.state
        const { stage,treasureStage } = this.props
        return (
            <div className={'year-index-course'}>

                {
                    removable > 0 && (
                        <div className='nav-right-wish nav-right'>
                            <span onClick={this.toBoxList} className='nav-right__link'>未开宝箱
                                <i className="nav-right__number">{removable}</i>
                            </span>
                        </div>
                    )
                }
            </div>
        )
    }
}

export default withRouter(YearCourse)
