'use strict';

import React, { Component } from 'react';
import resList from '../../resconfig/resList';
import API from '../../api';

import './PageIndex.less';
import ViewCtrl from '../../util/viewCtrl';
import Enum from '../../util/enum';
import config from '../../util/config';
import { GTool } from '../../util/GTool';
import dataCenter from '../../util/dataCenter';
import util from '../../util/util';

// import {Route} from 'react-router-dom'


class PageIndex extends Component {
    constructor(props) {
        super(props);
        this.state = this.state ||
        {
            resList: resList,
            myGameCountText: "",
        };
    }

    //组件加载
    componentDidMount() {
        var that = this;
        that.initData();
    }

    //初始化数据
    async initData() {
        var that = this;
        const ajaxElement = await API.ajaxElement({
            duibaId: window.CFG.hdToolId,
            activityId: window.CFG.actId
        });
        if (ajaxElement && ajaxElement.success) {
            dataCenter.setData("ajaxElement", ajaxElement.data);
            that.judgeCount(ajaxElement.data.element);
        } else {
            ViewCtrl.showToast(ajaxElement.desc || config.netError);
        }
    }

    //判断游戏次数是否充足
    judgeCount(data) {
        var that = this;
        var text;
        const { freeLimit, status, needCreditsLong } = data;
        if (freeLimit > 0) {
            text = "剩余免费挑战次数：" + freeLimit;
        } else if (status == 4 || status == 3) {
            text = "挑战次数已达上限";
        } else {
            text = needCreditsLong + window.CFG.unitName + "/每次";
        }
        that.setState({
            myGameCountText: text
        })
    }

    //打开规则弹窗
    openRule() {
        ViewCtrl.showWin(Enum.Com.ComRule);
    }

    //跳转到奖品页
    openRecordPage() {
        window.location.href = getRecordUrl('00');

        function getRecordUrl(type, ids) {
            let recordUrl;
            let oaId;

            oaId = window.CFG.oaId;
            recordUrl = window.CFG.recordUrl;

            if (!ids) {
                ids = [oaId];
            }

            let i = 0;
            const len = ids.length;
            for (i; i < len; i++) {
                if (window.location.href.indexOf("?") == -1) {
                    recordUrl += '?origins=' + ids[i] + type;
                } else {
                    recordUrl += '&origins=' + ids[i] + type;
                }

            }
            return recordUrl;
        }
    }

    //判断是否可以开始游戏
    judgeCanStartGame() {
        var that = this;
        util.clickDelay("kai_shi_you_xib")
        if (CFG.isNotLoginUser == true) {
            ViewCtrl.showWin(Enum.Com.Comdeng_lu);
            return;
        }
        const { freeLimit, status } = dataCenter.getData("ajaxElement").element
        if (freeLimit >= 1) {
            that.startGame();
        } else if (status == 4 || status == 3) {
            ViewCtrl.showWin(Enum.Com.ComnoChance);
            // ViewCtrl.showToast("参与次数已达上限")
        } else {
            ViewCtrl.showWin(Enum.Com.ComspendPoints,{},that.startGame.bind(that));
            return;
        }
    }

    //参与游戏进行轮询检查
    async startGame() {
        var that = this;
        console.log("Wefew")
        ViewCtrl.showWaiting();

        const token = await util.getDuibaToken();
        if (token) {
            that.enterGame(token);
        } else {
            ViewCtrl.hideWaiting();
            ViewCtrl.showToast();
        }
    }

    pollingCount;
    //准备进入游戏
    async enterGame(token) {
        var that = this;
        let params = {
            activityId: window.CFG.actId,
            token: token,
            activityType: 'hdtool',
            consumerId: window.CFG.consumerId
        }

        const doJoin = await API.doJoin(params)
        if (!doJoin || !doJoin.success) {
            ViewCtrl.hideWaiting();
            that.startGameFailed(doJoin.code);
            return;
        }
        dataCenter.setData("doJoin",doJoin)
        // 开始轮询
        that.pollingCount = 0;
        await that.getNewGameStartStatus(doJoin.data);
        //   await this.pollingOrderStatusForThrough({
        //     orderId: doJoin.data
        //   })
    }

    // //新游戏状态查询
    // async getNewGameStartStatus(data) {
    //     var that = this;
    //     return new Promise(async resolve => {
    //         that.pollingCount++;
    //         var gameStartStatus = await API.gameStartStatus({ orderId: data });
    //         if (gameStartStatus.success) {
    //             if (gameStartStatus.code == "0000000000" && that.pollingCount <= 10) {
    //                 //轮询成功
    //                 ViewCtrl.hideWaiting();
    //                 ViewCtrl.changePage(Enum.Page.PageCanvas);
    //             } else if (that.pollingCount > 10) {
    //                 ViewCtrl.hideWaiting();
    //                 that.startGameFailed(gameStartStatus.code);
    //                 resolve();
    //             } else {
    //                 setTimeout(async () => {
    //                     await that.getNewGameStartStatus(data);
    //                 }, 500);
    //             }

    //         } else {
    //             ViewCtrl.hideWaiting();
    //             that.startGameFailed(gameStartStatus.code);
    //             resolve();
    //         }
    //     })
    // }

    //新游戏状态查询
    async getNewGameStartStatus(data) {
        var that = this;
        var gameStartStatus =  await util.getApiStatus(API.gameStartStatus,"code","0000000000",{orderId:data});
        var a = 1;
        console.log(gameStartStatus)
        if(gameStartStatus&&gameStartStatus.success){
            //轮询成功
            dataCenter.setData("gameStartStatus",gameStartStatus)
            ViewCtrl.hideWaiting();
            ViewCtrl.changePage(Enum.Page.PageCanvas);
        }else{
            console.log("轮询失败啦")
            ViewCtrl.hideWaiting();
            that.startGameFailed();
        }
    }

    startGameFailed(code) {
        if (code == "E100201001" || code == "E100201002") {
            ViewCtrl.showWin(Enum.Com.Comdeng_lu);
        }
        else if (code == "E100201007") {
            ViewCtrl.showWin(Enum.Com.ComgetPoints);
        } else if (code == "E100202007" || code == "E100202008" || code == "E100202009" || code == "E100202010") {
            ViewCtrl.showWin(Enum.Com.ComnoChance);
            // ViewCtrl.showToast("参与次数已达上限")
        } else {
            ViewCtrl.showToast("活动异常火爆，请稍后再试")
        }
    }

    render() {
        return (
            <div className="ming_yue_zhi_zi_huo_dong_shou_yespark">
                <div className="huo_dong_shou_ye1">
                    <img className="bei_jing" src={this.state.resList['47d9b481-e72a-47a9-85d3-0c2e5e79c1e7'].url} />
                    <img className="xing_xing3tp xingxing3" src={this.state.resList['91f34179-5b71-418e-9af8-2a7fbf8c5d7c'].url} />
                    <img className="xing_xing2tp xingxing2" src={this.state.resList['a62d357a-2543-4c1a-99f2-17020fe2d825'].url} />
                    <img className="xing_xing1tp xingxing1" src={this.state.resList['6af4ed5f-ba65-4885-a33c-9db536be69f7'].url} />
                    <img className="zhu_ti_cha_huatp" src={this.state.resList['fee2936e-83ca-4f7b-ab2a-96263f626235'].url} />
                    <img className="huo_dong_biao_titp" src={this.state.resList['afd120b3-b377-433b-98ac-4c3fdbbd758b'].url} />
                    <div className="sheng_yu_tiao_zhan_ci_shu">
                        <label className="jin_ri_sheng_yu_tiao_zhan_ci_shux">{this.state.myGameCountText}</label>
                    </div>
                    {/* 开始游戏按钮 */}
                    <img className="kai_shi_you_xib breath1" src={this.state.resList['68f767ba-bd39-4146-9f4f-e3a7966e4644'].url} onClick={this.judgeCanStartGame.bind(this)} />
                    {/* 活动规则按钮 */}
                    <img className="huo_dong_gui_zet btn" src={this.state.resList['48441ab3-bed0-4626-80da-629ebd473bac'].url} onClick={this.openRule.bind(this)} />
                    <img className="jiang_pinicont btn" src={this.state.resList['1dd88b37-5ccb-4a28-a3de-4250933a6826'].url} onClick={this.openRecordPage.bind(this)}/>
                </div>
            </div>
        );
    }
}

export default PageIndex;
