import React, { Component } from 'react'
import { VList } from '../../common'
import { Tabs, WhiteSpace, Toast } from 'antd-mobile'
import './courselist.scss'
import HeaderSearch from '../../common/HeaderSearch/index'
import { http, getParam } from "@/utils"
import Loading from '@/common/Loading'
import { connect } from 'react-redux';
import { StickyContainer, Sticky } from "react-sticky";


function stopScroll(e) {
    e.preventDefault()
}

@connect(({user}) => ({
    user
}))
class Classify extends Component {
    constructor(props) {
        super(props)
        this.state = {
            ispull: false,
            display: 'none',
            arr: [{basics: []}, {advanced: []}],
            allClass: [],
            data: [],
            activeTab: decodeURIComponent(getParam('name')),
            isLoading: true,
            top: 44
        }

    }

    componentDidMount() {
        this.getTabs()
        this.getList()

        const el = document.querySelector('.search-nav');
        this.setState({
            top: el.offsetHeight
        });
    }

    componentWillUnmount() {
        document.removeEventListener('touchmove', stopScroll)
    }


    // 获取tabs接口
    getTabs = () => {
        let data = 0
        http.get(`${API.home}/m/course/classify/${data}`)
            .then((res) => {
                const _this = this
                if (res.data.code === 200) {
                    if (res.data.data.common.length > 0) {
                        let arr = ['basics', 'advanced']
                        let arr2 = [{basics: []}, {advanced: []}]
                        let arr3 = []
                        arr.forEach(function (item, index) {
                            arr2[item] = res.data.data.common[index]
                            res.data.data.common[index].list.forEach(function (item, index) {
                                arr3.push({'title': item.c_name, 'id': item.c_id})
                            })
                        })
                        _this.setState({
                            arr: arr2,
                            allClass: arr3
                        })
                    }
                } else {
                    Toast.info(res.data.msg, 2)
                }

            })
            .catch(err => {
                console.log(err)
            })
    }

    // 获取课程接口
    getList = () => {
        const _this = this
        _this.setState((state, props)=>({
            isLoading: true
        }));
        http.get(`${API.home}/m/course/list/${getParam('id')}`).then((res) => {
            if (res.data.code === 200) {
                _this.setState({
                    data: res.data.data,
                    isLoading: false
                })
            }
        })
    }


    // 点击横向滚动tab查询
    ontabclick = (tab) => {
        this.props.history.push(`/courselist?id=${tab.id}&name=${tab.title}`)
        this.getList()
        this.setState({
            activeTab: decodeURIComponent(getParam('name'))
        });
    }

    // 上下展示
    pulldown = () => {
        this.setState(status => ({
            ispull: !status.ispull,
            display: status.ispull ? 'none' : 'block'
        }), () => {
            this.state.ispull ? document.addEventListener('touchmove', stopScroll, {
                passive: false
            }) : document.removeEventListener('touchmove', stopScroll)
        });
    }

    // 弹窗里面tab点击查询
    labelclick = (item) => {
        this.props.history.push(`/courselist?id=${item.c_id}&name=${item.c_name}`)
        this.getList()
        this.setState(status => ({
            ispull: !status.ispull,
            display: status.ispull ? 'none' : 'block',
            activeTab: decodeURIComponent(getParam('name'))
        }))
    }

    toCourseDetail = (id) => {
        const {dispatch, history} = this.props;
        // dispatch(getCourses(id, () => {
        history.push(`/detail?id=${id}`)
        // }));
    }

    toClassify = () => {
        this.props.history.replace('/classify');
    }

    render() {
        const {user = {}} = this.props;
        let isLogin = user.data && user.data.uid ? true : false;
        const bottom = (
            <i className={'iconfont iconiconfront-69 pull-down'}></i>
        )
        const top = (
            <i className={'iconfont iconiconfront-71 pull-down'}></i>
        )

        let page = this.state.allClass.findIndex((item) => item.title === this.state.activeTab)
        return (
            <div className='class-child'>
                <HeaderSearch
                    isLogin={isLogin}
                    toHref={this.toClassify}
                />
                <Loading isLoading={this.state.isLoading}>
                    <div className='class-content'>
                        {/* <WhiteSpace/> */}
                        <div onClick={this.pulldown.bind(this)}>
                            {this.state.ispull ? top : bottom}
                        </div>
                        <StickyContainer>
                            {/* <Tabs
                                tabs={this.state.allClass}
                                animated={false}
                                page={page}
                                onChange={(tab) => this.ontabclick(tab)}
                                renderTabBar={props => <div className={'custom-render-bar'}>
                                    <Tabs.DefaultTabBar {...props}/>
                                </div>}
                            > */}
                            <Tabs
                                tabs={this.state.allClass}
                                animated={false}
                                page={page}
                                onChange={(tab) => this.ontabclick(tab)}
                                renderTabBar={props => {
                                    return (
                                        <Sticky>
                                            {({ style }) => {
                                                return (
                                                    <div style={{ ...style, top: `${this.state.top}px`, zIndex: 1 }}>
                                                        <Tabs.DefaultTabBar {...props} />
                                                    </div>
                                                )
                                            }}
                                        </Sticky>
                                    )
                                }}
                            >
                                <div className='tabs'>
                                    <ul>
                                        {this.state.data && this.state.data.length > 0 && this.state.data.map((item, index) => {
                                            const Info = (
                                                <div className="info">
                                                    <p className='title'
                                                       onClick={() => this.toCourseDetail(item.course_id)}>
                                                        {item.course_title}
                                                    </p>
                                                    <p className='contact text-overflow-2'>{item.desc}</p>
                                                    <div className='des'>
                                                        {!item.is_buy && <p className="course-price">
                                                            <span className="new">¥{item.price1}</span>
                                                            <span className="old">¥{item.price0}</span>
                                                        </p>
                                                        }
                                                        {item.is_buy &&
                                                        <span className="isbuy">已购买</span>
                                                        }
                                                    </div>
                                                </div>
                                            )
                                            const status = (
                                                !item.is_buy &&
                                                <div>
                                                    {item.bargain_num === 0 && item.groupon_num !== 0 &&
                                                    <p className='course-status'>拼团减{item.groupon_num}元</p>
                                                    }
                                                    {item.bargain_num !== 0 && item.groupon_num === 0 &&
                                                    <p className='course-status'>砍价减{item.bargain_num}元</p>
                                                    }
                                                    {
                                                        item.is_aist && <span className='return_cash'></span>
                                                    }
                                                </div>
                                            )
                                            return (
                                                <VList
                                                    key={index}
                                                    status={status}
                                                    img={item.image_name}
                                                    id={item.course_id}
                                                    info={Info}
                                                    toDetail={this.toCourseDetail}
                                                />
                                            )
                                        })}
                                    </ul>
                                </div>
                            </Tabs>

                        </StickyContainer>
                        <WhiteSpace/>
                    </div>
                    <div className='mbc-box' style={{display: this.state.display}}>
                        {
                            this.state.arr.basics &&
                            <div className="tabcontent">
                                <ClassCourse activeTab={this.state.activeTab} data={this.state.arr.basics.list}
                                             title={this.state.arr.basics.name} labelclick={this.labelclick}/>
                                <ClassCourse activeTab={this.state.activeTab} data={this.state.arr.advanced.list}
                                             title={this.state.arr.advanced.name} labelclick={this.labelclick}/>
                            </div>
                        }
                    </div>
                </Loading>
            </div>
        )
    }

}

function ClassCourse(props) {
    return (
        <div className="class-course">
            <p className='course-items-title'>{props.title}</p>
            <div className='items-box'>
                {
                    props.data && props.data.length > 0 && props.data.map((item, index) => {
                        return (
                            <span className={props.activeTab === item.c_name ? 'active-label' : 'item-label'}
                                  key={index} onClick={e => props.labelclick(item)}>{item.c_name}</span>
                        )
                    })
                }
            </div>
        </div>
    )
}

export default Classify;
