import React, { Component } from 'react'
import './togroup.scss'
import { HeaderBar, VList } from '../../../common'

import { api, getParam, http, browser} from "@/utils";
import { connect } from "react-redux"
import { Link } from "react-router-dom"
import { WingBlank, WhiteSpace, Flex, Toast } from 'antd-mobile'


class ToGroup extends Component {
    constructor(props) {
        super(props)
        this.state = {
            data: {},
            share: false,
            pdd_price: 0,
            groupon_member: [],
            person_num: 0, // 共多少人成团
            is_success: false, // 是否拼团成功
            userInfo: {},
            number: 0, // 差几人成团
        }
    }

    invitedFriends = () => {
        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['pay-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);
        }
    }

    componentDidMount() {
        Promise.all([http.get(`${api['pay-api']}/pdd/goupon_pay_page/15610158875449306780`), http.get(`${api.home}/m/user_info`)]).then(resultList => {
            console.log(resultList);
            let res = resultList[0],
            userInfo = resultList[1];

            this.setState({
                data: res.data.data.course_info,
                pdd_price: res.data.data.pdd_price,
                groupon_member: res.data.data.groupon_member,
                is_success: res.data.data.is_success,
                person_num: res.data.data.person_num,
                course_list: res.data.data.course_list,
                userInfo,
                number: res.data.data.number,
            });
        });

        http.post(`${api['pay-api']}/m/sale/signature`).then(res => {
                console.log(res);
        });
    }

    render() {
        const { data: { course_id, course_title, simpledescription, price0, price1 }, pdd_price, is_success, person_num, groupon_member, course_list } = this.state;
        const Info = (
            <div className="info">
                <p className='title'>
                    <Link to={`/detail?id=${course_id}`}>
                        {course_title}
                    </Link>
                </p>
                <p className='contact text-overflow-2'>{simpledescription}</p>
                <div className='des'>
                    <p className="course-price">
                        <span className="new">¥{price1}</span>
                        <span className="old">¥{price0}</span>
                    </p>
                </div>
            </div>
        )
        return (
            <div className='to-group-box'>
                <HeaderBar title='拼团' arrow={true} cart={false}></HeaderBar>
                {
                    !is_success && <VList img={this.state.data.image_name} id={this.state.data.course_id} info={Info}></VList>
                }

                <GorupContent data={this.state} invitedFriends={this.invitedFriends} />

                <WhiteSpace></WhiteSpace>
                <div className="group-course">
                    <div className="top-title">
                        <span>本周特惠</span>
                        <Link to={`/preferential`} className='more'>更多<i className='iconfont iconiconfront-70'></i></Link>
                    </div>
                    {
                        (course_list && course_list.length > 0) && (course_list[0].course && course_list[0].course.length > 0) && course_list[0].course.slice(0, 4).map(item => {

                            let weekInfo = <div className="info">
                            <p className='title'>
                                <Link to={`/detail?id=${item.course_id}`}>
                                    {item.course_title}
                                </Link>
                            </p>
                            <p className='contact text-overflow-2'>{item.simpledescription}</p>
                            <div className='des'>
                                <p className="course-price">
                                    <span className="new">¥{item.price1}</span>
                                    <span className="old">¥{item.price0}</span>
                                </p>
                            </div>
                            </div>
                            return (<VList img={item.image_name} key={item.uid} id={item.course_id} info={weekInfo}></VList>)
                        })
                    }

                </div>
            </div>
        )
    }
}

function GorupContent(props) {
    let tip, btn, dec, groupTip, shareTip, groupSuccessMbc;
    const { pdd_price, data, groupon_member, is_success, person_num, userInfo, share, number } = props.data;
    let ary=[],num = number;
    while(num != 0) {
        ary.push(num);
        num--;
    }
    groupTip = (<div className='group-user-list'>
        <Flex justify='center' className='imgList'>
            {
                groupon_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>);

    if (groupon_member && groupon_member.length > 0) {
        let uid = '';
        groupon_member.map(item=>{
            if(item.user_type === 1) {
                uid = `${item.uid}`;
            }
        })

        if(uid === userInfo.data.data.uid) {
            tip = <p className='tip'>{`拼团省￥${pdd_price}元`}</p>
            btn = <span className='group-btn' onClick={props.invitedFriends}>邀请好友参团 23：23：23 后结束</span>
            dec = <p className='dec'>分享到3个群后，成团率高达98%</p>
        } else {
            tip = <p className='tip'>{`拼团省￥${pdd_price}元`}</p>
            btn = <Link to={`/order?id=${data.course_id}`} className='group-btn'>一键参团</Link>
        }
    }

    if (is_success === 1) {
        tip = <p className='success'>拼团成功</p>
        btn = <Link to={`/play`} className='tostudy'>去学习</Link>
    }
    return (
        <div className='gorup-content'>
            {
                share ? (
                    <div className='groupSuccessMbc' onClick={props.invitedFriends}>
                        <div className='tipContent'>
                            
                            {`还差${number}人，分享到3个群，成团率高达98%`}
                        </div>
                        <div className='tipArrow'>
                            <i className='iconfont iconyindao'></i>
                        </div>
                    </div>
                ) : null
            }

            {tip}
            <WingBlank>
                {groupTip}
            </WingBlank>
            <WingBlank>
                {btn}
            </WingBlank>
            {dec}
            {
                !is_success &&
                <div className="group-dec">
                    <span>
                        <i className='iconfont iconiconfront-1'></i>
                        ·好友参团  ·人满成交  ·人不满退款
                        </span>
                    <span className='allNum'>{`累计${person_num}人成团`}</span>
                </div>
            }
        </div>
    )
}

export default ToGroup
