import Scene from "../views/Scene";
import SceneCtrl from "../ctrls/sceneCtrl";
import { ModuleTypes } from "../types/sceneTypes";
import PanelCtrl from "../ctrls/panelCtrl";
import StartScene from '../startScene/StartScene';
import { NetManager } from "../../libs/tw/manager/NetManager";
import { DataManager } from "../../libs/tw/manager/DataManager";
import Loading from "../loading/Loading";
import { Buried } from "../../libs/tw/util/Buried";

export default class ResultScene extends Scene {
    public prizeIconImg:eui.Image;
    public prizeIconImg1:eui.Image;
    public prizeEffImg:eui.Image;
    public shapeImg:eui.Image;
    public mainImg:eui.Image;
    public tipsImg:eui.Image;
    public frontImg:eui.Image;
    public txtLb0:eui.Label;
    public nameLb0:eui.Label;
    public txtLb1:eui.Label;
    public nameLb1:eui.Label;

    public printGroup:eui.Group;
    public erweimaGroup:eui.Group;

    public againBtn:eui.Button;
    public printBtn:eui.Button;
    public prizeBtn:eui.Button;

    public maskRect:eui.Rect;

    public img:any;
    
    private plugId:number;
    private currentDes:string;
    private resultMsgArr:IResultData[];

    public get skinKey() { return 'ResultScene' }
    public get groupName() { return 'result_scene' }

    constructor(data?) {
        super(data);
    }

    initEvents() {
        super.initEvents();
        this.nameLb0.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_nameLb0, this);
        this.againBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_againBtn, this);
        this.printBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_printBtn, this);
        this.prizeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeBtn, this);
    }

    removeEvents() {
        super.removeEvents();
        this.nameLb0.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_nameLb0, this);
        this.againBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_againBtn, this);
        this.printBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_printBtn, this);
        this.prizeBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeBtn, this);
    }

    private onTap_againBtn():void{
        PanelCtrl.instance.btnDelay(this.againBtn);

        // let startDpmOut = Buried.connectDpm(110, 4, 1); // 点击埋点   
        // let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        // let exposure = Buried.createExposure(startDpmOut, startDcmOut);

        //NetManager.ins.clickLog(exposure);

        //获取游戏信息
        // Loading.instace.show();
        // NetManager.ins.getInfo((success:boolean) => {

        //     if(success){
        //     }else{
        //         //提示用户，返回上一层，重新进入活动？？？？？
        //         PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'网络异常，请刷新重试！', line: 1});
        //     }
        //     Loading.instace.hide();
        // });
        SceneCtrl.instance.change(ModuleTypes.START_SCENE);
    }

    private onTap_printBtn():void{
        PanelCtrl.instance.btnDelay(this.printBtn);

        // let startDpmOut = Buried.connectDpm(110, 5, 1); // 点击埋点   
        // let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        // let exposure = Buried.createExposure(startDpmOut, startDcmOut);

        //NetManager.ins.clickLog(exposure);

        PanelCtrl.instance.show(ModuleTypes.RESULT_PANEL, function(){
            this.frontImg.visible = true;
            this.erweimaGroup.visible = false;

            const txt = this.nameLb0.text;
            this.nameLb0.textFlow = [{text:txt, style:{underline:true}}];
        }.bind(this));

        this.frontImg.visible = false;
        this.erweimaGroup.visible = true;
        
        const txt = this.nameLb0.text;
        this.nameLb0.textFlow = [{text:txt}];
        
        let renderTexture: egret.RenderTexture = new egret.RenderTexture();
        // let height = this.stage.stageHeight > 1206 ? 1206 : this.stage.stageHeight;
        renderTexture.drawToTexture(this.printGroup, new egret.Rectangle(41, 59, 687, 1037));
        let imageData = renderTexture.toDataURL("image/png");

        this.img = document.getElementById('shareImg');
        this.img.style.position = 'absolute';
        let widthP = 80;//Math.floor(600 * 100 / 750 );
        this.img.style.width = "80%";//`${widthP}%`;
        let leftP = 10;//Math.floor(75 * 100 / 750);
        this.img.style.left = "10%";//`${leftP}%`;
        let topP = Math.floor(50 * 100 / 750);
        this.img.style.top = "6.6%";//`${topP}%`;
        this.img['src'] = imageData;

        this.img.style.display = 'none';
    }

    private onTap_prizeBtn():void{
        PanelCtrl.instance.btnDelay(this.prizeBtn);

        // let startDpmOut = Buried.connectDpm(110, 6, 1); // 点击埋点   
        // let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        // let exposure = Buried.createExposure(startDpmOut, startDcmOut);

        //NetManager.ins.clickLog(exposure);
        
        this.prizeBtn.touchEnabled = false;
        this.maskRect.visible = true;
        this.prizeBtn.currentState = 'disabled';

        this.prizeIconImg.visible = true;
        egret.Tween.get(this.prizeIconImg).to({scaleX:1, scaleY:1, y:this.prizeIconImg.y - 200}, 1000, egret.Ease.cubicOut).
        to({rotation:-15}, 150, egret.Ease.cubicOut).
        to({rotation:15}, 150, egret.Ease.cubicOut).
        to({rotation:-15}, 150, egret.Ease.cubicOut).
        to({rotation:15}, 150, egret.Ease.cubicOut).
        to({rotation:0}, 150, egret.Ease.cubicOut).call(function(){
            // this.prizeIconImg.source = 'prizeIcon1_png';
            this.prizeIconImg1.visible = true;
            this.prizeIconImg.x = 390;
            this.prizeIconImg.y = 502;
            this.prizeEffImg.visible = true;
            egret.Tween.get(this.prizeEffImg).to({scaleX:1.3, scaleY:1.3}, 500, egret.Ease.cubicOut).call(function(){

                this.prizeIconImg1.visible = false;
                this.prizeIconImg.visible = false;
                this.prizeEffImg.visible = false;
                this.maskRect.visible = false;
                //抽插件
                this.getPlugPrize(this.plugId);

            }, this);
        },this);
    }

    private onTap_nameLb0():void{
        PanelCtrl.instance.btnDelay(this.nameLb0);
        PanelCtrl.instance.show(ModuleTypes.DESCRIBE_PANEL,[this.currentDes, this.nameLb0.text]);
    }

    protected onSkinComplete(): void {
        super.onSkinComplete();
        this.mainImg.texture = this.bgtexture;

        // let startDpmOut = Buried.connectDpm(110, 4, 1); // 点击埋点   
        // let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        // let exposure = Buried.createExposure(startDpmOut, startDcmOut);

        // NetManager.ins.showLog(exposure);

        // let startDpmOut1 = Buried.connectDpm(110, 5, 1); // 点击埋点   
        // let startDcmOut1 = Buried.connectDcm(202, 0, 0); // 曝光埋点
        // let exposure1 = Buried.createExposure(startDpmOut1, startDcmOut1);

        // NetManager.ins.showLog(exposure1);

        // let startDpmOut2 = Buried.connectDpm(110, 6, 1); // 点击埋点   
        // let startDcmOut2 = Buried.connectDcm(202, 0, 0); // 曝光埋点
        // let exposure2 = Buried.createExposure(startDpmOut2, startDcmOut2);

        // NetManager.ins.showLog(exposure2);

        
        this.plugId = window['plugId'] ? window['plugId'] : 4500;
        this.once(egret.Event.ADDED_TO_STAGE, this.onLoad, this);
        if (this.stage) {
            this.onLoad();
        }
    }

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


        // var mcJson = await RES.getResAsync('lightGameEff_json');
        // var mcImg = await RES.getResAsync('lightGameEff_png');
        // var mcFactory = new egret.MovieClipDataFactory(mcJson, mcImg);

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

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

    private onLoad(): void {
        this.initData();
        this.initUI();
        Loading.instace.show();
        NetManager.ins.getPrizeInfo(function(success){
            Loading.instace.hide();
            if(DataManager.ins.getPrizeInfoList[this.plugId].limitCount > 0){
                this.prizeBtn.touchEnabled = true;
                this.prizeBtn.currentState = 'up';

            }else{
                this.prizeBtn.touchEnabled = false;
                this.prizeBtn.currentState = 'disabled';
            }
        }.bind(this), this.plugId);
    }

    private initData():void{
        this.resultMsgArr = [
            {persona:'阿提克斯·芬奇', author:'哈珀·李', msg:'你不可能真正了解谁，除非你进入他的鞋子，陪他走上一段。', bookName:'《杀死一只知更鸟》', pnaDes:'信念坚定，睿智，行为端正，设身处地为他人着想'},
            {persona:'渡边彻', author:'村上春树', msg:'哪里会有人喜欢孤独，不过是不喜欢失望罢了。', bookName:'《挪威的森林》', pnaDes:'孤僻略带忧郁气质，内心世界丰富，勇于承担责任，不随波逐流'},
            {persona:'圣地亚哥', author:'保罗·柯艾略', msg:'没有一颗心，会因为追求梦想而受伤。', bookName:'《牧羊少年奇幻之旅》', pnaDes:'遵循内心生活，勇敢且坚强，活在当下，永远是一个有意思的人'},
            {persona:'白瑞德', author:'玛格丽特·米切尔', msg:'从此，各自飘零，各自悲哀。', bookName:'《飘》', pnaDes:'性格的复杂体，是痞子，也是绅士，看似玩世不恭，实则爱得深沉，对爱人具有强大的包容心。精明干练，对待生活富于勇气和挑战性。'},
            {persona:'孙少平', author:'路遥', msg:'我认为，每个人都有一个觉醒期，但觉醒的早晚决定个人的命运。', bookName:'《平凡的世界》', pnaDes:'积极进取，敢于拼搏。有年轻而敏感的自尊心，有积极而远大的梦想，在艰苦的环境中，始终不放弃，反而更加勤奋。'},
            {persona:'胡八一', author:'天下霸唱', msg:'发丘印，摸金符，搬山卸岭寻龙诀。', bookName:'《鬼吹灯》', pnaDes:'敢想、敢说、敢做、敢闯，总能找到理由说服自己和别人，身边有一群患难与共的真心兄弟。'},
            {persona:'安迪·杜佛兰', author:'斯蒂芬·金', msg:'坚强的人只能救赎自己，伟大的人才能拯救他人。', bookName:'《肖申克的救赎》', pnaDes:'学识丰富，智慧过人，异于常人的理性。在残酷吞噬肉体和灵魂的炼狱里自始至终没有丧失善良的人性，始终对自由怀着希望和想象，像一只火后重生的凤凰，健康自信地飞出黑暗。'},
            {persona:'小包总', author:'阿耐', msg:'既为生活而工作，岂能为工作而放弃生活。', bookName:'《欢乐颂》', pnaDes:'天生的统帅者。有眼光，有行动力，风流倜傥的外表下，却是踏踏实实做事的心。精通社会规则，而不失明朗赤，对人也好、对事也罢，一旦认准了，就不会轻易放弃。'},
            {persona:'令狐冲', author:'金庸', msg:'只要有人的地方就有恩怨,有恩怨就会有江湖,人就是江湖。', bookName:'《笑傲江湖》', pnaDes:'生性不羁，爽朗豁达，豪迈潇洒，不拘小节，喜欢开小玩笑，却有高度的忠义心'},
            {persona:'夜华', author:'唐七公子', msg:'我想要的，自始至终，不过一个你罢了。', bookName:'《三生三世十里桃花》', pnaDes:'充满智慧，稳重，凡事一力承担，打落牙齿和血吞，同时却厚爱深沉。心里九曲十八弯，怎么想别人永远猜不到，什么都能自己做，永远都做得比别人想象的更好。'},
            {persona:'琼恩·雪诺', author:'乔治·马丁', msg:'凛冬将至。', bookName:'《权力的游戏》', pnaDes:'沉默寡言，却善于察言观色、敏锐并极富同情心'},
            {persona:'琼·路易丝·斯各特·芬奇', author:'哈珀·李', msg:'你不可能真正了解谁，除非你进入他的鞋子，陪他走上一段。', bookName:'《杀死一只知更鸟》', pnaDes:'天真顽皮，好胜心强，懂得以客观的眼光发现别人的好与恶'},//女
            {persona:'小林绿子', author:'村上春树', msg:'哪里会有人喜欢孤独，不过是不喜欢失望罢了。', bookName:'《挪威的森林》', pnaDes:'突破传统，大胆且充满活力，偶尔也会赌气撒娇'},
            {persona:'郝思嘉', author:'玛格丽特·米切尔', msg:'从此，各自飘零，各自悲哀。', bookName:'《飘》', pnaDes:'敢于去爱、无怨无悔，在困难的时候敢于承担责任，自由而高贵。有高傲叛逆的一面，也有肆意洒脱的一面，注定不会是个平凡的人。'},
            {persona:'田晓霞', author:'路遥', msg:'我认为，每个人都有一个觉醒期，但觉醒的早晚决定个人的命运。', bookName:'《平凡的世界》', pnaDes:'一个异彩的存在，不仅自己光芒四射，同样感染着在身边的每一个人。活泼、开朗、永远散发正能量，总能给他人带来那么多的美好。'},
            {persona:'Shirley杨', author:'天下霸唱', msg:'发丘印，摸金符，搬山卸岭寻龙诀。', bookName:'《鬼吹灯》', pnaDes:'豪爽大方，胆大心细。长相出众，家中财产丰厚。在工作中是大家的坚实依靠，在众人遭逢困境的时候，能冷静应对，化解危局。'},
            {persona:'曲筱绡', author:'阿耐', msg:'既为生活而工作，岂能为工作而放弃生活。', bookName:'《欢乐颂》', pnaDes:'有刺的玫瑰花，魅力超群的小狐狸。管得了公司、搞得定男人，是人精中的战斗机。清楚知道自己要什么，平庸的生活也能过得妙曼多姿、活色生香。'},
            {persona:'安迪', author:'阿耐', msg:'既为生活而工作，岂能为工作而放弃生活。', bookName:'《欢乐颂》', pnaDes:'高智商、高情商，具有强悍的工作能力。对数字极为敏感，逻辑思维强大。同时，知世故而不世故，是一个气场相当强大的人。'},
            {persona:'任盈盈', author:'金庸', msg:'只要有人的地方就有恩怨,有恩怨就会有江湖,人就是江湖。', bookName:'《笑傲江湖》', pnaDes:'性格温婉如水，坚毅勇敢，冷淡的外表下内心热情，善解人意，冰雪聪明而且足智多谋'},
            {persona:'白浅', author:'唐七公子', msg:'我想要的，自始至终，不过一个你罢了。', bookName:'《三生三世十里桃花》', pnaDes:'气质空灵出尘，善良又不失优雅，与世无争但内心有霸气。不喜欢表面化和肤浅的东西，敢爱敢情，眼里容不得沙子'},
            {persona:'丹妮莉丝·坦格利安', author:'乔治·马丁', msg:'凛冬将至。', bookName:'《权力的游戏》', pnaDes:'胆小，不自信，婚姻是人生的转折点，逐渐变得强硬且自信'}
        ];

    }

    private initUI():void{
        this.erweimaGroup.visible = false;

        let idx = 0;
        // if(!StartScene.male){
        //     idx = Math.floor(Math.random() * 11);

        //     this.shapeImg.source = 'male' + idx + '_png';
        // }else{
        //     idx = Math.floor(Math.random() * 10);
        //     this.shapeImg.source = 'female' + idx + '_png';
        //     idx += 11;
        // }

        var resultData:IResultData = this.resultMsgArr[idx];
        this.txtLb0.text = '根据五值图解析，您更像是' + resultData.author + '笔下';
        this.nameLb0.textFlow = [{text:resultData.persona, style:{underline:true}}];
        this.txtLb1.text = resultData.msg;
        this.nameLb1.text = '一' + resultData.bookName;

        this.currentDes = resultData.pnaDes;

        this.prizeIconImg1.visible = false;
        this.prizeIconImg.visible = false;
        this.prizeEffImg.visible = false;
        this.maskRect.visible = false;

        //起泡动效设置
        if(resultData.persona){
            this.tipsImg.x = 375 + resultData.persona.length * 15;
        }
        this.tipsImg.scaleX = 0;
        this.tipsImg.scaleY = 0;
        egret.Tween.get(this.tipsImg).to({scaleX:1, scaleY:1}, 300, egret.Ease.cubicOut);
        
    }

/**
     * 抽首页插件
     * @param idx 插件id
     */
    private getPlugPrize(idx:number):void{
        let activityId = idx;

        Loading.instace.show();
        NetManager.ins.doJoinPlugDraw((isSuccess: boolean) => {
            if (isSuccess) {
                NetManager.ins.getPlugOrderStatus((data) => {
                    if (data == 'pollingFaild' || !data) {
                        console.log('轮询失败：' + data);
                        Loading.instace.hide();
                        PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL);
                    }else{//出奖
                        Loading.instace.hide();
                        //弹出奖品框待处理
                        if(!DataManager.ins.getPlugOrderStatusData.lottery){    
                            PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL);
                            
                        }else{
                            PanelCtrl.instance.show(ModuleTypes.PRIZE_PANEL, true);
                        }
                    }
                }, DataManager.ins.doJoinPlugDrawData.orderId, () => {
                    return (DataManager.ins.getPlugOrderStatusData.result == 0)
                }, 10)
            } else {
                // 下订单失败
                console.log('抽插件下单失败：' + activityId);
                Loading.instace.hide();
                PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL);
            }
        }, activityId);

    }

    //打乱数组顺序
    private shuffleArray(array) {
        for (var i = array.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
        return array;
    }
}

export interface IResultData{
    persona:string,
    author:string,
    msg:string,
    bookName:string,
    pnaDes:string
}