import React, { Component } from 'react'
import './index.scss'
import { getParam } from "@/utils"
import { connect } from "react-redux"
import { Flex } from 'antd-mobile'
import {browser} from "@/utils"
import {Toast} from 'antd-mobile'


class Group extends Component {
    constructor(props) {
        super(props)
        this.state = {
            isShowMore: false,
            alreadyIn: false,
            pdd_price: 0,
            number: 0,
            data: {},
            countdown: props.countdown,
            now_groupon_list: [],
        }
    }

    // 查看更多
    getMore = () => {
        this.setState({
            isShowMore: true
        })
    }

    // 关闭更多窗口
    closeMore = () => {
        this.setState({
            isShowMore: false
        })
    }

    toPay = (pdd_order_id) => {
        const courseInfo = this.props.courseInfo.courseInfo.course_info;
        if (courseInfo.group_status === 3) {
            this.props.history.push(`/order?id=${getParam('id')}`, {group: 1})

        } else {
            this.setState({
                isShowMore: false,
                alreadyIn: true
            });
        }
    }

    invitedFriends = () => {
        this.setState({
            isShowMore: false,
            alreadyIn: false,
        });
        const { pdd_price, number, data } = this.state;
        if (browser.isWeixin) {
            let share = this.state.share;
            this.setState({
                share: !share,
            });
            let shareData = {
                title: `【仅剩${number}个名额】我${pdd_price}元拼了《${data.course_title}》`,
                desc: data.course_title,                               //  分享描述
                link: location.origin + `/detail??id=${data.course_id}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl: data.image_name, // 分享图标
            };

            http.post(`${API['base-api']}/m/sale/signature`).then(res => {
                const {nonce_str, signature, timestamp} = res.data;
                wx.config({
                    "debug": false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    "appId": 'wx23dac6775ac82877', // 必填，公众号的唯一标识
                    "timestamp": timestamp, // 必填，生成签名的时间戳
                    "nonceStr": nonce_str, // 必填，生成签名的随机串
                    "signature": signature, // 必填，签名
                    jsApiList: [
                        'hideMenuItems',
                        'showMenuItems',
                        'updateAppMessageShareData',
                        'updateTimelineShareData',
                        'onMenuShareWeibo',
                        'onMenuShareAppMessage',
                    ], // 必填，需要使用的JS接口列表
                });
            });
            wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
                wx.hideAllNonBaseMenuItem();
                wx.showMenuItems({
                    menuList: ['menuItem:share:appMessage', 'menuItem:share:timeline'] // 要显示的菜单项，所有menu项见附录3
                });
                wx.updateAppMessageShareData({
                    ...shareData,
                    success: function () {
                        // 设置成功
                    }
                })
                wx.updateTimelineShareData({
                    ...shareData,
                    success: function () {
                        // 设置成功
                    }
                })
            });
        } else {
            Toast.info('请在微信中使用分享功能！', 2);
        }
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            countdown: nextProps.countdown,
        })
    }

    componentDidMount() {
        if (this.props.courseInfo && this.props.courseInfo.courseInfo && this.props.courseInfo.courseInfo.course_info && this.props.courseInfo.courseInfo.course_info.pdd_group_info) {
            let now_groupon_list = this.props.courseInfo.courseInfo.course_info.pdd_group_info.now_groupon_list;
            if (now_groupon_list && now_groupon_list.length > 0) {
                setInterval(() => {
                    now_groupon_list.map(item => {
                        item.end_time -= 1;
                        return item;
                    });
                    this.setState({
                        now_groupon_list,
                    })
                }, 1000);
            }
        }
    }

    hideMbc = () => {
        this.setState({
            alreadyIn: false
        });
    }

    formatTimeByMillisecond = (millisecond) => {
        let date = millisecond * 1000,
            hours = 0,
            minutes = 0,
            seconds = 0;
        date -= 1000;
        hours = `${parseInt(date / (60 * 60 * 1000))}`.padStart(2, 0);
        minutes = `${parseInt((date - hours * 3600000) / 60000)}`.padStart(2, 0);
        seconds = `${parseInt((date - hours * 3600000 - minutes * 60000) / 1000)}`.padStart(2, 0);
        return `${hours}:${minutes}:${seconds}`;
    }

    render() {
        const { alreadyIn, countdown, now_groupon_list } = this.state;
        let groupInfo = '', groupon_member = '', group_status = -1, groupSuccessMbc = null;
        if (this.props.courseInfo && this.props.courseInfo.courseInfo && this.props.courseInfo.courseInfo.course_info) {
            groupInfo = this.props.courseInfo.courseInfo.course_info.pdd_group_info;
            groupon_member = groupInfo.groupon_member;
            group_status = this.props.courseInfo.courseInfo.course_info.group_status;
        }
        if (group_status === 4) {
            if (groupon_member.member) {
                const { number } = groupon_member;
                let ary = [], num = number;
                while (num != 0) {
                    ary.push(num);
                    num--;
                }
                let groupTip = (<div className='group-user-list'>
                    <Flex justify='center' className='imgList'>
                        {
                            groupon_member.member.map(item => {
                                return (
                                    <div className='imgContainer' key={Math.random()}>
                                        <img className='imgname' src={item.avatar} alt='' />
                                        {
                                            item.user_type === 1 ? (
                                                <div className='leaderFlag'>
                                                    <span>团长</span>
                                                </div>
                                            ) : null
                                        }
                                    </div>);
                            })
                        }
                        {
                            ary.map(item => {
                                return (<div className='imgContainer' key={Math.random()}>
                                    <div className='imgname'>
                                        <i className='iconfont iconwode-xianxing no-body'></i>
                                    </div>
                                </div>)
                            })
                        }
                    </Flex>
                </div>);
                groupSuccessMbc = <div className='groupSuccessMbc' onClick={this.hideMbc}>
                    <div className='content'>
                        <p>你已参团</p>
                        {groupTip}
                        <div className='group-btn' onClick={this.invitedFriends}>邀请好友参团 {countdown} 后结束</div>
                        <p className='dec'>分享到3个群后，成团率高达98%</p>
                    </div>
                </div>;
            }

        }

        return (
            <div className='group-box'>
                <div className="group-title">
                    <span>{groupInfo.now_groupon_total}人正在开团，可直接参与</span>
                    <span className='more' onClick={this.getMore}>
                        查看更多
                        <i className='iconfont iconiconfront-70'></i>
                    </span>

                </div>
                <ul className="group-list">
                    {
                        groupInfo.now_groupon_list && groupInfo.now_groupon_list.length > 0 && groupInfo.now_groupon_list.map((item, index) => {
                            return (
                                <li key={index} className='group-item'>
                                    <img className='avatar' src={item.avatar} alt="" />
                                    <div className='user-name text-overflow-one'>
                                        {item.user_name}
                                    </div>
                                    <div className='group-status'>
                                        <p>还差<span className='red'>{item.number}人</span>拼成</p>
                                        <p>剩余 {this.formatTimeByMillisecond(item.end_time)}</p>
                                    </div>
                                    <span onClick={() => { this.toPay(item.pdd_order_id) }} className='topay'>去参团</span>
                                </li>
                            )
                        })
                    }
                </ul>
                <div className="group-dec">
                    <span>
                        <i className='iconfont iconiconfront-1'></i>
                        ·好友参团  ·人满成交  ·人不满退款
                    </span>
                    <span className='allNum'>{`累计${groupInfo.person_num}人成团`}</span>
                </div>
                {
                    (alreadyIn && group_status === 4) && (
                        <>
                            {groupSuccessMbc}
                        </>
                    )

                }
                {/*更多*/}
                {
                    this.state.isShowMore &&
                    <div className="moreMbc">
                        <div className="content">
                            <div className="title-box">
                                正在拼团
                            </div>
                            <ul className='more-group-list'>
                                {
                                    groupInfo.now_groupon_list && groupInfo.now_groupon_list.length > 0 && groupInfo.now_groupon_list.map((item, index) => {
                                        return (
                                            <li key={index} className='group-item'>
                                                <img className='avatar' src={item.avatar} alt="" />
                                                <div className='user-name'>
                                                    <p className='name text-overflow-one'>{item.user_name}</p>
                                                    <p className='time'>剩余 {this.formatTimeByMillisecond(item.end_time)}</p>
                                                </div>
                                                <p className='group-status'>还差{item.number}人</p>
                                                <span onClick={() => { this.toPay(item.pdd_order_id) }} className='topay'>去参团</span>
                                            </li>
                                        )
                                    })
                                }
                            </ul>
                            <div className='more-group-dec'>
                                仅显示10个正在开团的人
                            </div>
                            <i onClick={this.closeMore} className={'iconfont iconiconfront-2 close'}></i>
                        </div>

                    </div>
                }

            </div>
        )
    }
}

export default connect(
    state => ({ courseInfo: state }),
    null
)(Group)
