import React, { Component } from 'react'
import './bargain-middle-page.scss'
import { HeaderBar, VList } from '@common'
import { Course } from '@common'
import { api, getParam, http, browser } from "@/utils"
import { Toast } from "antd-mobile"
import { Link, withRouter } from "react-router-dom"
import Ranking from './ranking'
import { differenceInSeconds, differenceInMinutes, differenceInHours, differenceInDays } from "date-fns"
import Overlay from '../detail/overlay'
import { compose } from "redux"
import { connect } from "react-redux";
import {getCourses} from './../detail/actions';

@connect(state => ({
    user: state.user
}))
class BargainMiddlePage extends Component {

    timer

    constructor(props) {
        super(props)
        this.state = {
            isShowOverlay: false,
            isOriginator: '',
            kanjiaIcon: require('./image/kanjia_icon.png'),
            course: {}, // 当前砍价课程
            courseList: [],  // 所有砍价课程
            data: '',
            bargainData: '',
            limitPeople: 0,
            outList: [],
            list: [],
            width: '0',
            isShowMore: '',
            status: '',
            hour: '',
            min: '',
            sec: '',
            day: '',
            amount: '',
            firendBaigainPrice: true,
            isshowYindao: false,
            isLoaidng: true
        }
    }

    componentDidMount() {
        this.getBargainRankList(getParam('id'), 1)
        this.getBargainCourse()
        this.getBargainInfo()
    }

    // 获取砍价信息
    getBargainInfo = () => {

        http.get(`${API.home}/m/bargain/info?bargaincode=${getParam('bargaincode')}&is_originator=${getParam('is_originator')}`).then((res) => {
            if (res.data.code === 200) {
                this.setState(
                    {
                        data: res.data.data,
                        isOriginator: res.data.data.is_originator,
                        originatorUid: res.data.data.originator_uid,
                        course: res.data.data.course,
                        limitPeople: res.data.data.course.limit_people,
                        bargainData: res.data.data.bargain,
                        width: (res.data.data.bargain.bargain_price / res.data.data.bargain.total_price).toFixed(2) * 100 + '%'
                    }, 
                    () => {
                        if (this.state.bargainData.expire_time) {
                            let date = this.state.bargainData.expire_time * 1000
                            let now = Date.now()
                            clearInterval(this.timer)
                            this.timer = setInterval(() => {
                                date -= 1000
                                let _d = new Date(date)
                                let s = differenceInSeconds(_d, now) % 60,
                                    m = differenceInMinutes(_d, now) % 60,
                                    h = differenceInHours(_d, now) % 24,
                                    d = differenceInDays(_d, now) % 24
                                this.setState({
                                    hour: h,
                                    min: m,
                                    sec: s,
                                    day: d
                                })

                            }, 1000)
                        }
                    }
                )
            } else {
                Toast.info(res.data.msg, 2)
            }
        })
    }

    // 获取砍价课程
    getBargainCourse = () => {
        http.get(`${API.home}/m/bargain/courseList`).then((res) => {
            if (res.data.code === 200) {
                this.setState({
                    courseList: res.data.data
                })
            } else {
                Toast.info(res.data.msg, 2)
            }
        })
    }

    // 获取助理好友
    getBargainRankList = (id, type) => {
        let data = {
            courseId: id,
            type: type
        }
        http.post(`${API.home}/m/bargain/rankList`, data).then((res) => {
            if (res.data.code === 200) {
                let arr = ['刀神', '刀王', '刀霸']
                let newList = res.data.data.out_list.map((item, i) => {
                    return {
                        ...item,
                        rank: arr[i]
                    }
                })
                this.setState({
                    list: res.data.data.list,
                    outList: newList
                })
            } else {
                Toast.info(res.data.msg, 2)
            }
        })
    }

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

    // 查看更多
    getMore = () => {
        this.setState({
            isShowMore: true
        })
    }
    // 自组件传给父组件的boxHide
    boxHide = (val) => {
        this.setState({isShowMore: val})
    }

    // 领取砍价神器
    toArtifact = () => {
        let data = {
            courseId: getParam('id')
        }
        http.post(`${API.home}/m/bargain/receiveLimit`, data).then((res) => {
            if (res.data.code === 200) {
                this.setState({
                    isShowOverlay: true,
                    status: 5,
                })
            } else {
                Toast.info(res.data.msg, 2)
            }
        })
    }

    // 使用砍价神器
    useArtifact = () => {
        this.toKanjia(getParam('id'), 2, 0)
    }

    // 砍价接口
    toKanjia = (id, type, uid) => {
        let data = {
            course_id: id,
            type: type,  // 1 用户自己砍价 2 使用砍价神器 3 好友助力砍价 4 好友第二次助力
            parent_uid: uid // 被助力人id 【自己本人操作传0】
        }
        http.post(`${API.home}/m/bargain/toBargain`, data).then((res) => {
            if (res.data.code === 200) {
                // is_success =0一切正常 =1 不能在砍了 =2关注公众号,可以再砍一刀！
                this.setState({
                    amount: res.data.data.amount
                })
                if (type === 2) {
                    this.setState({
                        isShowOverlay: true,
                        status: 6
                    })
                }

                if (res.data.data.is_success === 1) {
                    this.setState({
                        isShowOverlay: true,
                        status: 4
                    })
                } else if (res.data.data.is_success === 2) {
                    if (type === 3) {
                        this.setState({
                            isShowOverlay: true,
                            status: 2
                        })
                    } else if (type === 4) {
                        this.setState({
                            isShowOverlay: true,
                            status: 1,
                            firendBaigainPrice: false
                        })
                    }
                } else if (res.data.data.is_success === 0) {
                    if (type === 3) {
                        this.setState({
                            isShowOverlay: true,
                            status: 2
                        })
                    } else if (type === 4) {
                        this.setState({
                            isShowOverlay: true,
                            status: 3
                        })
                    }
                }

                this.getBargainInfo()


            } else {
                Toast.info(res.data.msg, 2)
            }
        })
    }


    // 帮好友砍价第一刀
    friendBargainFirst = () => {
        this.toKanjia(getParam('id'), 3, this.state.originatorUid)
    }

    // 帮好友砍价第二刀
    friendBargainSecond = () => {
        this.toKanjia(getParam('id'), 4, this.state.originatorUid)
    }

    // 邀请好友砍价
    shareFriendBargain = () => {
        this.setState({
            isShowOverlay: true,
            status: 7,
            isshowYindao: browser.isWeixin ? true : false
        })
    }

    // 关闭弹窗
    close = () => {
        this.setState({
            isShowOverlay: false,
            status: '',
        })
    }

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

    render() {
        let thirdRow, btn
        // is_artifact	 0-再邀请多少人可以使用 1-可以使用未领取 2-已领取 3-已使用
        if (this.state.bargainData.is_artifact === 0) {
            thirdRow =
                <div>再邀请<span className={'indicator'}>{this.state.bargainData.invite_num}</span>位好友助力即可获得<span
                    className={'indicator'}>【砍价神器】</span></div>
        } else if (this.state.bargainData.is_artifact === 1) {
            thirdRow = <div>恭喜你获得<span className={'indicator'}>【砍价神器】</span></div>
            btn = <button className={'artifact-btn'} onClick={this.toArtifact}>立即领取</button>
        } else if (this.state.bargainData.is_artifact === 2) {
            thirdRow = <div>恭喜你获得<span className={'indicator'}>【砍价神器】</span></div>
            btn = <button className={'artifact-btn'} onClick={this.useArtifact}>立即使用</button>
        }


        let bargainBtn
        if (this.state.isOriginator !== 1 && this.state.data.assist_status === 0 && this.state.data.bargain_status === 0) {
            bargainBtn = <button className='active-btn' onClick={this.friendBargainFirst}>帮好友砍一刀</button>
        } else if (this.state.isOriginator !== 1 && this.state.data.assist_status === 1) {
            bargainBtn = <button className='active-btn' onClick={this.friendBargainSecond}>再砍一刀</button>
        } else if (this.state.isOriginator !== 1 && this.state.data.assist_status === 2) {
            bargainBtn = <button className={'invalid-btn'}>已帮好友助力</button>
        } else if (this.state.data.bargain_status === 1 || this.state.data.bargain_status === 2) {
            bargainBtn = <button className={'invalid-btn'}>砍价结束</button>
        } else if (this.state.isOriginator === 1 && this.state.data.bargain_status === 0) {
            bargainBtn = <button className='active-btn' onClick={this.shareFriendBargain}>邀请好友砍价</button>
        }
        return (
            <div className={'bargain-middle-page'}>
                <HeaderBar title='砍价详情' arrow={true} cart={true}></HeaderBar>
                {/*<Loading isLoading={this.state.isLoaidng}>*/}
                <div className="top">
                    <div className="bargain-area">
                        {
                            this.state.isOriginator !== 1 &&
                            <p className='bargain-tip'>你的好友发现一门精品课程，快来一起帮他砍价：</p>
                        }

                        <ul>
                            <VList
                                img={this.state.course.course_img}
                                info={
                                <CourseDes
                                    isOriginator={this.state.isOriginator}
                                    data={this.state.data}
                                    toCart={this.toCart}/>
                                }
                            />
                        </ul>
                        <div className="bargain-detail">
                            <div className="top">
                                <div>
                                    已砍<span className={'reduced-price'}>{this.state.bargainData.bargain_price}元</span>
                                </div>
                                {
                                    this.state.data.bargain_status === 0 &&
                                    <div>
                                        <span
                                            className={'time hour'}>{String(this.state.hour).padStart(2, 0)}</span> :&nbsp;
                                        <span
                                            className={'time min'}>{String(this.state.min).padStart(2, 0)}</span> :&nbsp;
                                        <span className={'time sec'}>{String(this.state.sec).padStart(2, 0)}</span>
                                        <span className={'inactive'}> 后砍价结束</span>
                                    </div>
                                }
                                {
                                    this.state.data.bargain_status === 1 && this.state.isOriginator === 1 &&
                                    <span className={'inactive'}>砍价结束</span>
                                }

                            </div>
                            <div className="middle">
                                <span style={{width: this.state.width}}></span>
                            </div>
                            {
                                this.state.isOriginator === 1 && this.state.data.bargain_status === 0 &&
                                <div>
                                    {thirdRow}
                                    {btn}
                                </div>
                            }

                            {
                                this.state.isOriginator === 1 && this.state.data.bargain_status === 1 &&
                                <div>
                                    砍价金额将于
                                    <span className={'time hour'}>{String(this.state.day).padStart(2, 0)}</span><span
                                    className={'unit'}> 天 </span>
                                    <span className={'time min'}>{String(this.state.hour).padStart(2, 0)}</span><span
                                    className={'unit'}> 时 </span>
                                    <span className={'time sec'}>{String(this.state.min).padStart(2, 0)}</span><span
                                    className={'unit'}>分</span>
                                    后清零，请尽快完成支付
                                </div>
                            }

                            <div className={'button'}>
                                {bargainBtn}
                            </div>

                        </div>
                    </div>
                    <div className="bargain-records">
                        <div className="title">砍价记录</div>
                        <ul>
                            {
                                this.state.outList && this.state.outList.length > 0 && this.state.outList.map((item, index) => {
                                    return (
                                        <li key={index}>
                                            <div className="left">
                                                <img className='avatar' src={item.avatar_file} alt=""/>
                                                <span className={'nickname'}>{item.user_name}</span>
                                                <span className="rank-tag">{item.rank}</span>
                                            </div>
                                            <div className="right">
                                                <img className='kanjia-icon' src={this.state.kanjiaIcon} alt=""/>
                                                砍掉<span className={'price'}>{item.amount}</span>
                                            </div>
                                        </li>
                                    )
                                })

                            }

                        </ul>
                        <div className="more" onClick={this.getMore}>查看更多>></div>
                    </div>
                </div>
                <div className="bargain-course-list" id='bargainCourse'>
                    <div className="title-wrapper">
                        <div className="title">我要砍价</div>
                        <div className="subtitle">邀请{this.state.limitPeople}位以上好友帮忙砍价可获得【砍价神器】</div>
                    </div>
                    <ul>
                        {
                            this.state.courseList && this.state.courseList.length > 0 && this.state.courseList.map((item, index) => {
                                return <Course
                                    className={'text-overflow-2'}
                                    key={index}
                                    id={item.course_id}
                                    img={item.image_name}
                                    title={item.course_title}
                                    toDetail={this.toCourseDetail}
                                    bottom={
                                    <CourseBottom
                                        item={item}
                                        toCart={this.toCart}
                                        toDetail={this.toCourseDetail}
                                    />
                                    }
                                />
                            })
                        }
                    </ul>
                </div>
                <Link to={'/preferential'} className={'preferential'}>查看更多精品课程 >></Link>


                {/*更多好友砍价*/}
                <Ranking list={this.state.list} icon={this.state.kanjiaIcon} limitPeople={this.state.limitPeople}
                         isShowMore={this.state.isShowMore} boxHide={this.boxHide}></Ranking>


                {
                    this.state.isShowOverlay &&
                    <Overlay>

                        {/*砍价成功去分享*/}
                        {
                            this.state.status === 7 &&
                            <BargainSuccess isshowYindao={this.state.isshowYindao} limitPeople={this.state.limitPeople}
                                            close={this.close}/>
                        }


                        {/*引导关注公众号*/}
                        {
                            this.state.status === 1 &&
                            <PublicNumber
                                money={this.state.amount}
                                avatar={this.props.user.data.avatar}
                                firendBaigainPrice={this.state.firendBaigainPrice}/>
                        }

                        {/*好友成功砍第一刀*/}
                        {
                            this.state.status === 2 &&
                            <BargainFirst
                                bargainSecond={this.friendBargainSecond}
                                money={this.state.amount}
                            />
                        }
                        {/*好友成功砍第二刀*/}
                        {
                            this.state.status === 3 &&
                            <BargainSecond close={this.close} money={this.state.amount}/>
                        }
                        {/*不能在砍了*/}
                        {
                            this.state.status === 4 &&
                            <NotBargain close={this.close} limitPeople={this.state.limitPeople}/>
                        }
                        {/*领取砍价神器*/}
                        {
                            this.state.status === 5 &&
                            <Artifact useArtifact={this.useArtifact}/>
                        }
                        {/*使用砍价神器*/}
                        {
                            this.state.status === 6 &&
                            <UseArtifact toCart={this.toCart} money={this.state.amount}
                                         allMoney={this.state.bargainData.bargain_price}/>
                        }

                        {
                            this.state.status !== 7 &&
                            <i onClick={this.close} className={'iconfont iconiconfront-2 bargain-close'}></i>
                        }
                    </Overlay>

                }
                {/*</Loading>*/}

            </div>
        );
    }
}

function CourseDes(props) {
    const data = props.data && props.data.course
    return (
        <div className={'des'}>
            <div className="course-title text-overflow-2">
                {data.course_title}
            </div>
            <div className="price-bar">
                <span className={'discount-price'}>￥{data.course_price}</span>
                {
                    props.isOriginator === 1 &&
                    <button className={'purchase-btn'}
                            onClick={props.toCart}>¥{data.pay_price}去支付
                    </button>
                }
            </div>
        </div>
    )
}

function CourseBottom(props) {
    let Buttons
    if (props.item.bargain_status === 2) {
        // Buttons = <Link to={`/detail?id=${props.item.course_id}`} className={'bargain'}>我要砍价</Link>
        Buttons = <a href="javascript:;" onClick={() => props.toDetail(props.item.course_id)} className={'bargain'}>我要砍价</a>
    } else if (props.item.bargain_status === 3) {
        Buttons = <Link to={`/play/video?id=${props.item.course_id}`} className={'bargain'}>去学习</Link>
    } else {
        Buttons = (
            <div className="btns">
                {/*<button className={classnames('bargain-btn', {invalid: props.item.bargain_status === 2})}>*/}
                {/*{props.item.bargain_status === 2 ? '砍价结束' : '继续砍价'}*/}
                {/*</button>*/}
                {
                    props.item.bargain_status === 1 &&
                    <button className='invalid'>砍价结束</button>
                }
                {
                    props.item.bargain_status === 0 &&
                    <a href="javascript:;" onClick={() => props.toDetail(props.item.course_id)} className={'bargain-btn'}>我要砍价</a>

                }


                <button onClick={props.toCart}
                        className={'purchase-btn'}>¥{props.item.pay_price}去支付
                </button>
            </div>
        )
    }
    return (
        <div className="course-bottom">
            <div className={'course-price'}>
                <span className={'discount-price'}>¥{props.item.price1}</span>
                <span className={'original-price'}>¥{props.item.price0}</span>
            </div>
            {Buttons}
        </div>
    )
}


function PublicNumber(props) {
    return (
        <div className='bargain-public-number'>

            <img className='avait' src={props.avatar} alt=""/>

            {
                props.firendBaigainPrice &&
                <p className='status-title ff4'>谢谢你帮我砍了{props.money}元！</p>
            }
            <p className='status-dec'>关注公众号，可以再砍一刀哦~</p>
            <img className='public-number-img'
                 src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/tinypng-common/right_weixin.png" alt=""/>
        </div>
    )
}

function BargainFirst(props) {
    return (
        <div className='bargain-first'>
            <img className='top-img' src={require('./image/kanjia_cg_icon.png')} alt=""/>
            <p className='status-title'>谢谢你帮我砍了<span className='ff4'>{props.money}元</span>！</p>
            <p className='status-dec'>你还可以帮我再砍一刀哦~</p>
            <button className='bargain-href' onClick={props.bargainSecond}>再砍一刀</button>
        </div>
    )
}

function BargainSecond(props) {
    return (
        <div className='bargain-second'>
            <img className='top-img' src={require('./image/kanjia_cg_icon.png')} alt=""/>
            <p className='status-title'>厉害了，又帮好友砍掉<span className='ff4'>{props.money}元</span>！</p>
            <a className='bargain-href' href='#bargainCourse' onClick={props.close}>我也要砍价</a>
        </div>
    )
}

function NotBargain(props) {
    return (
        <div className='not-bargain'>
            <img className='middle-img' src={require('./image/kanjia_no_iccon.png')} alt=""/>
            <p className='status-title'>你的好友用【砍价神器】把我砍蒙圈了<br/>不能再砍了哦~</p>
            <p className='status-dec'>邀请{props.limitPeople}位以上好友帮忙砍价可获得【砍价神器】</p>
            <a className='bargain-href' href='#bargainCourse' onClick={props.close}>我也要砍价</a>
        </div>
    )
}

function Artifact(props) {
    return (
        <div className='artifact-box'>
            <p className='top-tip'>恭喜你获得【砍价神器】！</p>
            <p className='middle-tip'>
                您可以使用
                <span className={'indicator'}>【砍价神器】</span>
                再砍一刀
            </p>
            <button className='use-artifact' onClick={props.useArtifact}>立即使用</button>
        </div>
    )
}

function UseArtifact(props) {
    return (
        <div className='use-artifact-box'>
            <img className='top-img' src={require('./image/kanjia_cg_icon.png')} alt=""/>
            <p className='top-tip'>厉害了，又砍掉了{props.money}元！</p>
            <p className='middle-tip'>
                你已经砍了
                <span className={'indicator'}>{props.allMoney}元</span>
                没见过你这么能砍的人...
            </p>
            <p className='btm-tip'>
                不能再砍了哦~
            </p>
            <button className='tubuy' onClick={props.toCart}>去支付</button>
        </div>
    )
}


function BargainSuccess(props) {
    return (
        <div>
            <div className='close-bargain-success' onClick={props.close}></div>

            <div className="bargain-success">
                {
                    props.isshowYindao &&
                    <i className='iconfont iconyindao'></i>
                }
                <p>分享到微信群邀请更多好友帮忙砍价</p>
                <p>超过{props.limitPeople}位好友助力可获得<span className={'indicator'} style={{color: '#FF4000'}}>【砍价神器】</span>哦
                </p>
            </div>
        </div>
    )
}


export default withRouter(BargainMiddlePage);
