import { DataManager } from './../../libs/tw/manager/DataManager';
import { ModuleTypes } from './../types/sceneTypes';

import Scene from "../views/Scene";
import PanelCtrl from "../ctrls/panelCtrl";
import SceneCtrl from '../ctrls/sceneCtrl';
import { NetManager } from '../../libs/tw/manager/NetManager';
import Loading from '../loading/Loading';
import { Buried } from '../../libs/tw/util/Buried';
import { GCache } from '../../libs/tc/util/GCache';
import TopLayerCtrl from '../ctrls/topLayerCtrl';
export default class StartScene1 extends Scene {
    public mainbg:eui.Image;
    public titleGroup:eui.Group;
    public startBtn:eui.Button;
    public inputGroup:eui.Group;
    



    public get skinKey() { return 'StartScene' }
    public get groupName() { return 'start_scene' }


    myEditableText: eui.EditableText = new eui.EditableText();

    constructor(data?) {
        super(data);//95fcf3
    }

    initEvents() {
        super.initEvents();
        // this.ruleBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ruleBtn, this);
        this.startBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_startBtn, this);
        // this.prizeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeBtn, this);
        // this.musicBtn.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTap_musicBtn, this);
    }

    removeEvents() {
        super.removeEvents();

        // this.ruleBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ruleBtn, this);
        this.startBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_startBtn, this);
        // this.prizeBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeBtn, this);
        // this.musicBtn.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTap_musicBtn, this);
    }

    start(data?) {
        super.start(data);
        this.percentHeight = 100;
    }

    exposure=[]
    dpm=[]
    dcm=[]
    private doBuried(){
        //初始化埋点数据
        Buried.init();
        var appId=DataManager.ins.customCfgData.appId;
        var oaId=DataManager.ins.customCfgData.oaId;
        this.dpm["1"]=appId+'.110.1.1';
        this.dcm["1"]=`202.${oaId}.0.0`;
        this.exposure["1"] = Buried.createExposure(this.dpm["1"], this.dcm["1"]);
        NetManager.ins.showLog(this.exposure["1"]);

        this.dpm["2"]=appId+'.110.2.1';
        this.dcm["2"]=`202.${oaId}.0.0`;
        this.exposure["2"] = Buried.createExposure(this.dpm["2"], this.dcm["2"]);
        NetManager.ins.showLog(this.exposure["2"]);
    }

    private bgtexture: egret.Texture;
    protected async preLoadRes() {
        //加载背景并设置背景图片
        this.bgtexture = await RES.getResAsync('startBg_jpg');
        // console.log('载背景并设置背景图片mainscene');

        return new Promise(function (resolve, reject) {
            resolve();
        });
    }

    protected onSkinComplete(): void {
        super.onSkinComplete();

        this.mainbg.texture = this.bgtexture;



        this.once(egret.Event.ADDED_TO_STAGE, this.onLoad, this);
        if (this.stage) {
            this.onLoad();
        }

        this.initInput()
    }

    initInput() {
        this.myEditableText.text = "";
        //指定文本的颜色。
        this.myEditableText.textColor = 0x999595;
        //指定我们的文本输入框的宽和高    
        this.myEditableText.width = this.inputGroup.width;
        this.myEditableText.height = this.inputGroup.height;
        this.myEditableText.x = 0;
        this.myEditableText.y = 0;
        this.myEditableText.size = 32;
        this.myEditableText.lineSpacing = 68;
        this.myEditableText.textAlign = "center";
        this.myEditableText.verticalAlign = "middle";
        this.myEditableText.maxChars = 6
        this.myEditableText.prompt = "请输入你的昵称"
        this.inputGroup.addChild(this.myEditableText);
        this.myEditableText.addEventListener(egret.Event.CHANGE,this.onFocusOut_myEditableText,this)
        this.onFocusOut_myEditableText()
    }

    onFocusOut_myEditableText(){
        this.myEditableText.text=this.myEditableText.text.replace(/^\s*|\s*$/g,"")
        if(this.myEditableText.text==""){
            this.startBtn.enabled=false;
        }else{
            this.startBtn.enabled=true;
        }
    }

    private onLoad(): void {
        this.doBuried()
        this.initUI();
    }

    private initUI():void{
        // egret.Tween.get(this.startBtn, {loop:true})
        //     .to({scaleX:1.05, scaleY:1.05}, 150)
        //     .to({scaleX:0.9, scaleY:0.9}, 150)
        //     .to({scaleX:1.05, scaleY:1.05}, 150)
        //     .to({scaleX:0.9, scaleY:0.9}, 150).wait(500);
    }

    private onTap_ruleBtn():void{
        console.log('点击rule');
        // PanelCtrl.instance.btnDelay(this.ruleBtn);
        PanelCtrl.instance.show(ModuleTypes.RULE_PANEL); 
    }

    private onTap_startBtn():void{
        PanelCtrl.instance.btnDelay(this.startBtn);
        NetManager.ins.clickLog(this.exposure["2"]);
        if(this.myEditableText.text==""){
            TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: "昵称不能为空" });
            return;
        }

        this.enabled=false;
        NetManager.ins.uploadNickName((succuss) => {
			if (!succuss) {
                this.enabled=true;
				return;
            }
            if (this.getQueryString("shareCode")) {
                NetManager.ins.getIndex((success) => {
                    if (!success) {
                        return
                    }
                    this.showMainScene();
                }, DataManager.ins.customCfgData.actId, true, this.getQueryString("shareCode"))
            } else {
                NetManager.ins.getIndex((success) => {
                    if (!success) {
                        return
                    }
                    this.showMainScene();
                }, DataManager.ins.customCfgData.actId, true)
            }
		}, DataManager.ins.customCfgData.actId,this.myEditableText.text)

       
    }

    private async showMainScene(){
        await RES.loadGroup('msg_panel');
        await RES.getResAsync('msgBg0_png');
        await RES.getResAsync('msgBg1_png');
        await RES.getResAsync('msgBg2_png');
        await RES.getResAsync('msgBg3_png');
        NetManager.ins.getGameZone((success)=>{
            if(!success){
                return
            }
            SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE);
        },DataManager.ins.customCfgData.actId)
    }

    getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };



    private onTap_prizeBtn():void{
        console.log('点击prizeBtn'); 
        // PanelCtrl.instance.btnDelay(this.prizeBtn);
        window.location.href = this.gotoRecord();//window["recordUrl"];
    }

    //获取我的奖品
    private gotoRecord():string{
        let recordUrl: string;
        let oaId: number;
        if (DataManager.ins.customCfgData) {
            oaId = DataManager.ins.customCfgData.oaId;
            recordUrl = DataManager.ins.customCfgData.recordUrl;
        } else {
            oaId = DataManager.ins.gameCfgData.gameInfo.oaId;
            recordUrl = window['recordUrl'];
        }

        if(recordUrl.indexOf('?') != -1){
            recordUrl += '&origins=' + oaId + '00';
        }else{
            recordUrl += '?origins=' + oaId + '00';
        } 
        // recordUrl += ',' + (window['plugId'] ? window['plugId'] : 4500) + '01';

        // for(let i = 0; i < window['plugIdArr'].length; i++){
        //     recordUrl += ',' + window['plugIdArr'][i] + '01';
        // }

        return recordUrl;
    }

    //循环播放动画
	private playAnimation(target: egret.tween.TweenGroup, isLoop: boolean = true): void {
		if (isLoop) {
			for (var key in target.items) {
				target.items[key].props = { loop: true };
			}
		}
		target.play();
    }
    

}
