import React, { Component, useState } from 'react'
import './bargain.scss'
import { Flex, Toast } from "antd-mobile"
import Overlay from '../overlay'
import BargainInfo from './bargainInfo'
import {differenceInSeconds, differenceInMinutes, differenceInHours, differenceInDays} from "date-fns"
import { api, getParam, http } from "@/utils"
import Ranking from "@/components/bargainMiddlePage/ranking"
import { compose } from "redux"
import { withRouter } from 'react-router-dom'
import {connect} from "react-redux";
import { Object } from 'core-js'


class Bargain extends Component {
    constructor(props) {
        super(props)
        this.state = {
            isShowOverlay: false,
            kanjiaIcon: require('./image/kanjia_icon.png'),
            info: '',
            outList: [],
            list: [],
            limitPeople: '',
            status: '',
            bargainCode: '',
            time: '',
            barInfo: {},
            country: '86',
            price: 0, // 每次砍价砍掉的价格
            sum: 0 // 累计砍掉的价格
        }
    }

    componentDidMount() {
        this.getBargainInfo();
        this.judgePopupTypeFromCountry();
    }

    // 选择区号后进入
    judgePopupTypeFromCountry = () => {
    const { country, delCountryNum } = this.props;
    if(country.from && country.from === 'bargain') {
        this.setState({
            country: country.num,
            isShowOverlay: true,
            status: 3,
        });

        // 清除
        delCountryNum();
    }
  }

    // 获取助理好友
    getBargainRankList = (params = {}) => {
        http.post(`${API.home}/m/bargain/rankList`, params).then((res) => {
            if (res.data.code === 200) {
                this.setState({
                    list: res.data.data.list,
                    outList: res.data.data.list[0]
                })
            } else {
                Toast.info(res.data.msg, 2)
            }
        })
    }


    //获取砍价信息
    getBargainInfo = (isFetch = true) => {
        let data = {
            courseId: getParam('id')
        }
        http.post(`${API.home}/m/bargain/courseDetail`, data).then((res) => {
            const { code, data, msg = '' } = res.data;
            if (code === 200) {
                this.setState({
                    barInfo: data,
                    // info: res.data.data,
                    // limitPeople: res.data.data.limit_people,
                    // bargainCode: res.data.data.bargain_code
                });
                if(isFetch) {
                    // 砍价状态 0-砍价中，1砍价结束，待支付，2砍价过期（没有砍价记录没有砍价信息），3已购买
                    if (data.bargain_status === 0 || data.bargain_status === 1 ) {
                        this.getBargainRankList({
                            type: 0,
                            bargain_code: data.bargain_code
                        });
                    }
                }
            } else {
                Toast.info(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: 1
                });
                this.getBargainInfo(false);
            } else {
                Toast.info(res.data.msg, 2)
            }
        })
    }

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

    // 加入购物车
    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);
            }
        })
    }
    // 继续砍价
    continueBargain = () => {
        const { barInfo = {} } = this.state;
        const code = barInfo.bargain_code;
        this.props.history.push(`/bargain-middle-page?id=${getParam('id')}&bargaincode=${code}&is_originator=1`)
    }

    // 我要砍价
    iWantBargain = () => {
        const { history, user } = this.props
        const uid = user && user.data && user.data.uid;
        if(!uid){
            history.push('/passport/login');
        } else {
            this.toKanjia(getParam('id'), 1, 0);
        }
    }

    // 砍价接口
    toKanjia = (id, type, uid) => {
        let data = {
            course_id: id,
            type: type,  // 1 用户自己砍价 2 使用砍价神器 3 好友助力砍价 4 好友第二次助力
            parent_uid: uid // 被助力人id 【自己本人操作传0】
        };
        const { history } = this.props;
        http.post(`${API.home}/m/bargain/toBargain`, data).then((res) => {
            const { data: { data, code } } = res;
            if (code === 200) {

                // user_status 用户状态 1-关注公众号，2-绑定手机号 3-再砍一刀 （是发起人没有这个字段）
                if(data.user_status === 2) {
                    this.setState({
                        isShowOverlay: true,
                        status: 3,
                    });
                }else {
                    if(type === 2) {
                        this.setState({
                            isShowOverlay: true,
                            status: 2,
                            price: data.amount,
                            sum: data.bargain_price
                        });
                        this.getBargainInfo(false);
                        this.getBargainRankList({
                            type: 0,
                            bargain_code: data.bargain_code
                        });
                    }else {
                        history.push(`/bargain-middle-page?id=${getParam('id')}&bargaincode=${data.bargain_code}&is_originator=1`)
                    }
                }
                // if (type === 2) {
                //     this.setState({
                //         isShowOverlay: true,
                //         status: 2,
                //     })
                // } else {
                //     // user_status 用户状态 1-关注公众号，2-绑定手机号 3-再砍一刀 （是发起人没有这个字段）
                //     if (data.user_status === 2) {
                //         this.setState({
                //             isShowOverlay: true,
                //             status: 3,
                //         })
                //     } else {
                //         history.push(`/bargain-middle-page?id=${getParam('id')}&bargaincode=${data.bargain_code}&is_originator=1`)
                //     }
                // }
            } else {
                Toast.info(res.data.msg, 2)
            }
        })
    }


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

    render() {
        const { list, outList, barInfo, country, price, sum } = this.state;
        const {user} = this.props
        const uid = user && user.data && user.data.uid
        return (
            <div className={'bargain-func'}>

                {/*bargain_status 砍价状态 0-砍价中，1砍价结束，待支付，2砍价过期（没有砍价记录没有砍价信息），3已购买*/}
                {
                    (barInfo.bargain_status === 2 || (getParam('id') === '139' && barInfo.bargain_status === 3) || !uid) &&
                    <BargainIntro limitPeople={barInfo.limit_people} iWantBargain={this.iWantBargain}/>
                }
                {
                    (barInfo.bargain_status === 0 || barInfo.bargain_status === 1) && uid &&
                    <BargainStatus
                        info={barInfo}
                        outList={outList}
                        getMore={this.getMore}
                        toArtifact={this.toArtifact}
                        useArtifact={this.useArtifact}
                        continueBargain={this.continueBargain}
                    />
                }


                {
                    this.state.isShowOverlay &&
                    <Overlay>
                        {/*绑定手机号*/}
                        {
                            this.state.status === 3 &&
                            <BargainInfo country={country} iWantBargain={this.iWantBargain} toClose={this.close} />
                        }


                        {/*领取砍价神器*/}
                        {
                            this.state.status === 1 &&
                            <Artifact useArtifact={this.useArtifact}/>
                        }
                        {/*使用砍价神器*/}
                        {
                            this.state.status === 2 &&
                            <UseArtifact 
                                price={price}
                                sum={sum}
                                toCart={this.toCart}
                            />
                        }

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

                    </Overlay>

                }


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

            </div>
        )
    }
}

function BargainIntro(props) {
    return (
        <div className="intro-outer">
            <div className="intro-inner">
                <Flex direction={'column'} justify={'center'} className={'intro-wrapper'}>
                    <p>
                        邀请
                        <span className={'indicator'}>{props.limitPeople}位</span>
                        好友帮忙砍价可获得
                        <span className={'indicator'}>【砍价神器】</span>
                    </p>
                    <p>一刀绝杀，砍爆底价</p>
                    <Flex.Item>
                        <button onClick={props.iWantBargain}>我要砍价</button>
                    </Flex.Item>
                </Flex>
            </div>
        </div>
    )
}

function BargainStatus(props) {

    const [day, setDay] = useState(0)
    const [hour, setHour] = useState(0)
    const [min, setMin] = useState(0)
    const [sec, setSec] = useState(0)


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


    let date = props.info.end_time * 1000
    let now = Date.now()
    setInterval(() => {
        date -= 1000
        setSec(differenceInSeconds(new Date(date), now) % 60)
        setMin(differenceInMinutes(new Date(date), now) % 60)
        setHour(differenceInHours(new Date(date), now) % 24)
        setDay(differenceInDays(new Date(date), now) % 24)

    }, 1000)


    return (
        <div className="status-outer">

            {
                props.info.bargain_status === 0 &&
                <div className="status-inner">

                    <Flex direction={'column'}>
                        <div className={'first-row'}>
                            <div>
                                已砍<span className={'indicator'}>{props.info.bargain_price}元</span>
                                <span className={'time hour'}>{String(hour).padStart(2, 0)}</span> :&nbsp;
                                <span className={'time min'}>{String(min).padStart(2, 0)}</span> :&nbsp;
                                <span className={'time sec'}>{String(sec).padStart(2, 0)}</span>
                                <span className='over'>后砍价结束</span>
                            </div>
                            <div onClick={props.getMore}>{props.info.assist_num}位好友助力></div>
                        </div>

                        <div className="sec-row">
                            <div>
                                <img
                                    src={props.outList.avatar_file}
                                    alt=""/>
                                <span className='name'>{props.outList.user_name}</span>
                            </div>
                            <div>
                                <div>砍掉<span className={'indicator'}>{props.outList.amount}元</span></div>
                                <button onClick={props.continueBargain}>继续砍价</button>
                            </div>
                        </div>
                        <div className="third-row">
                            {thirdRow}
                            {btn}
                        </div>
                    </Flex>
                </div>
            }

            {
                props.info.bargain_status === 1 &&
                <div className="status-inner status-over">

                    <Flex direction={'column'}>
                        <div className={'first-row'}>
                            <div>
                                已砍<span className={'indicator'}>{props.info.bargain_price}元</span>
                                <span className='bargain-over'>
                                    砍价结束
                                </span>
                            </div>
                            <div onClick={props.getMore}>{props.info.assist_num}位好友助力></div>
                        </div>
                        <div className="time-tobuy">
                            砍价金额将于
                            <span className={'time hour'}>{String(day).padStart(2, 0)}</span><span
                            className={'unit'}> 天 </span>
                            <span className={'time min'}>{String(hour).padStart(2, 0)}</span><span
                            className={'unit'}> 时 </span>
                            <span className={'time sec'}>{String(min).padStart(2, 0)}</span><span
                            className={'unit'}>分</span>
                            后清零，请尽快完成支付
                        </div>
                    </Flex>
                </div>
            }
        </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) {
    const { sum, price } = props;
    return (
        <div className='use-artifact-box'>
            <img className='top-img' src={require('./image/kanjia_cg_icon.png')} alt=""/>
            <p className='top-tip'>厉害了，又砍掉了{price}元！</p>
            <p className='middle-tip'>
                你已经砍了
                <span className={'indicator'}>{sum}元</span>
                没见过你这么能砍的人...
            </p>
            <p className='btm-tip'>
                不能再砍了哦~
            </p>
            <button className='tubuy' onClick={props.toCart}>去支付</button>
        </div>
    )
}


export default compose(
    connect(
        state => ({
            user: state.user
        }),
        null
    ),
    withRouter
)(Bargain)
