index.js 11.9 KB
import React, {PureComponent} from 'react';
import './index.scss'
import {conf, start} from '../../api'
import yaSDK from 'yoho-activity-sdk';
import config from '../../../../config';
import cookie from 'react-cookies';
import LazyLoad from 'react-lazy-load'
import {
    Link
} from 'react-router-dom'

import Resource from '../components/resource';
import BottomButton from '../components/bottom-button';
import TipModal from '../components/tip-modal';

export default class wheelSurf extends PureComponent {
    constructor(props) {
        document.title ='大转盘';
        super(props);
        this.state = {
            uid: 0,
            expIdx: 1,
            query: {},
            canStart: true,    // 可以抽奖
            slowEnding: false, // 减速结束
            startEnded: false, // 已结束

            startType: true,
            isLogin: false,
            dayLeftTimesTip: '',

            conf: {
                loading: ''
            },
            totalParts: '',
            remainCount: '',
            
            showTipModal: false,
            modalTip: '',
            modalBtnText: '',

            gotDesc: '',
            angle: 0,          // 当前旋转角度
            speed: 0,          // 旋转速度
            stopAngle: 0,      // 停止的角度
            startSlowAngle: 0  // 起始减速的角度
        };
        
        this.init();
    }

    init = async () => {

        // 登录状态
        this.state.query = yaSDK.getQueryObj() || {};
        this.state.uid = +(this.state.query.uid  || cookie.load('uid') || 0);
        
        yaSDK.getUid().then(async (uid) => {
            if (uid && uid === this.state.uid) {
                this.setState({
                    uid,
                    isLogin: !!uid
                });
                
                switch (yaSDK.env) {
                    case 'h5':
                        if (!cookie.load('uid')) {
                            cookie.save('uid', this.state.uid);
                            cookie.save('app_session_key', this.state.query.session_key, { path: '/' });
                            cookie.save('app_client_type', this.state.query.app_client_type, { path: '/' });
                            cookie.save('app_version', this.state.query.app_version, { path: '/' });
                        }
                        break;
                        
                    case 'miniprogram':
                        cookie.save('uid', this.state.uid);
                        cookie.save('app_session_key', this.state.query.session_key, { path: '/' });
                        cookie.save('app_client_type', this.state.query.client_type, { path: '/' });
                        cookie.save('app_version', '6.6.0', { path: '/' });
                        break;
                        
                    case 'app':
                        cookie.save('uid', this.state.uid);
                        cookie.save('app_session_key', this.state.query.session_key, { path: '/' });
                        cookie.save('app_client_type', this.state.query.client_type, { path: '/' });
                        cookie.save('app_version', this.state.query.app_version, { path: '/' });
                        break;
                        
                    default:
                        break;
                    
                }
            } else {
                cookie.remove('uid');
                cookie.remove('app_session_key');
                cookie.remove('app_client_type');
                cookie.remove('app_version');
            }
            
            let params = {act_id: +this.state.query.actId};
            
            if (this.state.uid) {
                params.uid = this.state.uid;
            }

            let result = await conf(params);

            if (result.code === 200) {
                this.setState({
                    conf: result.data.conf,
                    expIdx: result.data.prize_idx,
                    totalParts: result.data.prize,
                    remainCount: result.data.residueCount,
                    dayLeftTimesTip: result.data.conf.btm_tip_one,
                    startType: result.data.startType !== false,
                    startErrorMsg: result.data.errorMsg || ''
                });
                this.setWxShare();
            } else {
                console.log(result.message)
            }
        });
    };

    setWxShare = () => {
        const {conf} = this.state;

        yaSDK.wxShare({
            title: conf.share_title,
            imgUrl: `${conf.share_img}?imageView2/1/w/200/h/200`,
            desc: conf.share_desc,
            link: conf.share_url
        });
    };

    begin = async () => {
        console.log('开始抽奖');
        
        this.state.canStart = false;
        this.setState({
            remainCount: this.state.remainCount - 1
        });
        
        let result = await start({
            act_id: +this.state.query.actId,
            uid: cookie.load('uid'),
            sessionKey: cookie.load('app_session_key'),
            sessionType: cookie.load('app_client_type'),
            appVersion: cookie.load('app_version')
        });
        
        if (result.code !== 200) {
            result = {
              data: {
                prize_idx: this.state.expIdx
              }
            }
        }
        
        let timer = setTimeout(() => {
            clearTimeout(timer);
            this.state.stopAngle = this.calcStopAngle(result.data.prize_idx);
            this.state.gotDesc = result.data.desc;
            this.setState({
                slowEnding: true
            });
            this.state.angle = this.state.stopAngle;
            this.stop(this.state.stopAngle);
        }, 4000);
    };

    calcStopAngle = idx => {
        return parseInt(360 / this.state.totalParts) * (this.state.totalParts - idx + 1) || 359; 
    };

    start = async () => {
        const {isLogin, canStart} = this.state;
        
        if (!isLogin) {
            return yaSDK.goLogin();
        }

        // 抽奖前验证是否可以抽奖
        if (!this.state.startType) {
            return this.setState({
                showTipModal: true,
                modalTip: '活动尚未开始',
                modalBtnText: '确定'
            });
        }

        // 抽奖前验证是否可以抽奖
        if (!this.state.remainCount) {
            return this.setState({
                showTipModal: true,
                modalTip: '您今天的抽奖次数已经用完<br/>请明天再来',
                modalBtnText: '确定'
            });
        }
        
        if (!canStart) {
            return;
        }
        
        this.begin();
        this.rotate();
    };
    
    stop = angle => {
        let rotateDeg = angle + 360 * 5;
        let randCssName = 'stop_' + (new Date()).getTime();
        let randCssContent = '{' +
            'transform: rotateZ(' + rotateDeg + 'deg) !important;' +
            '-webkit-transform: rotateZ(' + rotateDeg + 'deg) !important;' +
            '-webkit-transition: transform 4s ease-out;' +
            '}';
        
        document.getElementsByTagName('style')[0].innerHTML += ('.' + randCssName + ' ' + randCssContent);
        document.getElementById('rotateWheel').className = 'wheel-bg ' + randCssName;
        document.getElementById('rotateWheel').style.webkitTransform = 'rotateZ(' + angle + 'deg)';


        let timer = setTimeout(() => {
            this.setState({
                startEnded: true
            });
            clearTimeout(timer);
        }, 4000);
    };

    rotate = () => {
        let {slowEnding, startEnded} = this.state;

        if (startEnded) {
            return;
        }

        if (!slowEnding) {
            if (this.state.speed < 16) {
                this.state.speed += 0.2;
            }

            this.state.angle += this.state.speed;
            if (this.state.angle >= 360) {
                this.state.angle -= 360;
            }
        }

        if (!this.state.slowEnding) {
            document.getElementById('rotateWheel').style.webkitTransform = 'rotateZ(' + this.state.angle + 'deg)';
            requestAnimationFrame(this.rotate)
        }
    };
    
    links = conf => {
        let links = [];
        
        if (conf.jump_btn_left_url) {
            links.push({
                url: conf.jump_btn_left_url,
                bg: conf.jump_btn_left_bg
            });
        }
        
        if (conf.jump_btn_middle_url) {
            links.push({
                url: conf.jump_btn_middle_url,
                bg: conf.jump_btn_middle_bg
            });
        }
        
        if (conf.jump_btn_right_url) {
            links.push({
                url: conf.jump_btn_right_url,
                bg: conf.jump_btn_right_bg
            });
        }
        return links;
    };
    
    setCanStart = () => {
        this.setState({
            canStart: true,
            slowEnding: false,
            startEnded: false,
            speed: 0
        });
        document.getElementById('rotateWheel').className = 'wheel-bg';
    };
    
    shareInApp = () => {
        const {conf} = this.state;
        
        let shareData = {
            title: conf.share_title,
            link: conf.share_url,
            desc: conf.share_desc,
            imgUrl: conf.share_img,
            hideType: ['7', '8', '9']
        };
        
        yaSDK.invokeMethod({method: 'go.showshareaction', args: shareData});
    };

    confirm = () => {
        this.setState({
            showTipModal: false
        });
    };

    jump = e => {
        let $el = e.currentTarget;
        let url = $el.getAttribute('data-url');

        if (!url) {
            return;
        }
        yaSDK.link(e)
    };

    render() {
        let {conf, slowEnding, isLogin, startEnded, remainCount, dayLeftTimesTip} = this.state;
        
        if (dayLeftTimesTip) {
            dayLeftTimesTip = dayLeftTimesTip.replace(/\{\$1\}/ig, remainCount);
        }

        if (!conf.id) {
            return (
                <div className="home-wrap">
                    <img className="main-bg" src={this.state.conf.loading}/>
                </div>
            )
        }

        let links = this.links(conf);

        return (
            <div className="home-wrap">
                <img className="main-bg" src={conf.main_bg}/>
                {conf.rule_btn_bg ? (<a data-type="other" data-url={conf.rule_url} onClick={this.jump}>
                    <img className="rule-btn" src={conf.rule_btn_bg}/>
                </a>) : ''}
                {conf.share_btn_bg && yaSDK.env === 'app' ? (<img onClick={this.shareInApp} className="share-btn" src={conf.share_btn_bg}/>): ''}
                <img className="wheel-bg" id="rotateWheel" src={conf.wheel_bg}/>
                <img onClick={()=>{this.start()}} className="start-btn-bg" src={conf.prize_btn_bg}/>
                {
                    isLogin ?
                        (<div className="tips">
                            <p className="tip-1">{dayLeftTimesTip}</p>
                        </div>) : ''
                }
    
                <BottomButton links={links} login={isLogin}/>
                <Resource code={conf.bottomContentCode}/>

                {slowEnding ? (<img className="prize-hit-bg transition" src={conf.win_prize_bg}/>) : ''}
                {startEnded ? (
                    <div className="got-tip">
                        <div className="prize-tip">{this.state.gotDesc}</div>
                        <span onClick={this.setCanStart} className="try-again">确定</span>
                    </div>
                ) : ''}
                {startEnded ? (<span onClick={this.setCanStart} className="close-prize-hit-bg">关闭</span>) : ''}
                {slowEnding ? (<img className="prize-hit-start-bg" src={conf.prize_btn_bg}/>) : ''}
                {
                    this.state.showTipModal ? <TipModal tip={this.state.modalTip} btnText={this.state.modalBtnText} confirm={() => {this.confirm()}} /> : ''
                }
            </div>
        )
    }
}