import { FoodItem } from './FoodItem';

import { DataManager } from './../../libs/tw/manager/DataManager';
import { NetManager } from './../../libs/tw/manager/NetManager';
import MainScene from "./MainScene";
import PanelCtrl from '../ctrls/panelCtrl';
import { ModuleTypes } from '../types/sceneTypes';
import Loading from '../loading/Loading';
//喂食按钮动画运动时间间隔
const F_TIME_SPACE: number = 600;
//喂食按钮初始角度
const F_ANGLE: number = 7;
export class ExMainScene extends MainScene {
    constructor(data?) {
        super(data);

        //正常进页面为null 领养成功传过来一个true 如果是true 则开始引导
        this.isGuide = data;
    }

    initEvents() {
        super.initEvents();
        this.boatGroup.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_boat, this);
    }

    removeEvents() {
        super.removeEvents();
        this.boatGroup.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_boat, this)
    }

    onLoad() {
        super.onLoad();

        NetManager.ins.getPrizeInfo(() => { }, window['extraPlugId'])
        if (this.isGuide) {
            // 引导
            this.startGuide()
        } else {
            // 不引导 正常签到
            const todaySigned: boolean = DataManager.ins.signInfoData.signInfoVO.todaySigned;
            if (!todaySigned) {
                this.preLoadCoin();
                let data = { scene: this, isGuide: false }
                PanelCtrl.instance.show(ModuleTypes.SIGN_IN_PANEL, data);
            }

        }
    }

    startGuide() {
        //暂时禁用其他按钮
        this.myCoinGroup.touchEnabled = false;
        this.myCoinGroup.touchChildren = false;
        this.feedBtnNew.touchEnabled = false;
        this.boatGroup.touchEnabled = false;
        this.boatGroup.touchChildren = false;
        this.getCoinBtn.touchEnabled = false;
        this.mijiBtn.touchEnabled = false;
        for (var i: number = 0; i < 7; i++) {
            this['foodCtner' + i].touchEnabled = false;
            this['foodCtner' + i].touchChildren = false;
        }

        // 开始引导
        this.step1()
    }

    private guideComponent: eui.Component;
    step1() {
        this.guideComponent = new eui.Component();
        this.guideComponent.skinName = "GuideComponentSkin";
        this.guideComponent.height = 1624;
        this.guideComponent.width = 750;
        this.addChild(this.guideComponent);
        console.log(this.guideComponent);

        this.guideComponent['skipBtn'].addEventListener(egret.TouchEvent.TOUCH_TAP, this.step2, this);
        egret.Tween.get(this.guideComponent['guideTxt'])
            .to({ alpha: 1 }, 500)
            .wait(5000)
            .call(() => {
                this.step2();
            })
    }

    isSkip: boolean = false;
    step2() {
        if (this.isSkip) {
            return
        }
        this.isSkip = true;
        this.guideComponent.visible = false;
        const todaySigned: boolean = DataManager.ins.signInfoData.signInfoVO.todaySigned;
        if (!todaySigned) {
            this.preLoadCoin();
            egret.Tween.get(this.guideComponent)
                .to({ alpha: 0 }, 500)
                .call(() => {
                    let data = { scene: this, isGuide: true }
                    PanelCtrl.instance.show(ModuleTypes.SIGN_IN_PANEL, data);
                })
        }
    }

    public mcCoin: any;
    public mcCoinPool: any[] = [];
    public async preLoadCoin() {
        let mcCoinJson = await RES.getResAsync("rotateCoin_json");
        let mcCoinPng = await RES.getResAsync("rotateCoin_png");
        this.mcCoin = new egret.MovieClipDataFactory(mcCoinJson, mcCoinPng);

        return new Promise((resolve, reject) => {
            resolve();
        })
    }
    // 签到成功后的金币动效
    public signSucAni(coinNum: number = 10) {
        console.log('金币动效');
        if (this.mcCoin) {
            for (let i = 0; i < coinNum; i++) {

                let coin = new egret.MovieClip(this.mcCoin.generateMovieClipData())
                coin.anchorOffsetX = 25;
                coin.anchorOffsetY = 25;
                coin.x = this.stage.stageWidth / 2;
                coin.y = this.stage.stageHeight / 2;
                this.mcCoinPool.push(coin);
                this.addChild(coin)

            }

            let light = new eui.Image();
            light.source = `coinLight_png`;
            light.anchorOffsetX = 131;
            light.anchorOffsetY = 131;
            light.x = this.stage.stageWidth / 2;
            light.y = this.stage.stageHeight / 2;
            light.scaleX = 0;
            light.scaleY = 0;
            this.addChild(light);
            egret.Tween.get(light)
                .to({ scaleX: 1, scaleY: 1 }, 300)
                .to({ alpha: 0 }, 100)
                .call(() => {
                    this.removeChild(light);
                    this.mcCoinPool.forEach((coin, idx) => {
                        coin.gotoAndPlay(-1)
                        if (idx % 2 == 0) {
                            let data = { t: 0 }
                            egret.Tween.get(data, {
                                onChange: () => {
                                    coin.x = this.bezier(data.t, this.stage.stageWidth / 2, 430, 655);
                                    coin.y = this.bezier(data.t, this.stage.stageHeight / 2, 200, 87);
                                }
                            })
                                .wait(idx * 50)
                                .to({ t: 1 }, 500)
                                .call(() => {
                                    if (coin.parent == this) {
                                        this.removeChild(coin)
                                    }

                                })
                        } else {
                            let data = { t: 0 }
                            egret.Tween.get(data, {
                                onChange: () => {
                                    coin.x = this.bezier(data.t, this.stage.stageWidth / 2, 650, 655);
                                    coin.y = this.bezier(data.t, this.stage.stageHeight / 2, 431, 87);
                                }
                            })
                                .wait(idx * 50)
                                .to({ t: 1 }, 500)
                                .call(() => {
                                    if (coin.parent == this) {
                                        this.removeChild(coin)
                                    }

                                })
                        }
                    })

                })

            let addLabel = new eui.Label();
            let addCredits;
            if (DataManager.ins.signInfoData && DataManager.ins.signInfoData.signInfoVO && DataManager.ins.signInfoData.signInfoVO.rewardMap && DataManager.ins.signInfoData.signInfoVO.rewardMap.CIRCLE && DataManager.ins.signInfoData.signInfoVO.rewardMap.CIRCLE.credits) {
                addCredits = DataManager.ins.signInfoData.signInfoVO.rewardMap.CIRCLE.credits;
            } else {
                let cd = DataManager.ins.signInfoData.signInfoVO.continueDay;
                switch (cd) {
                    case 1:
                        addCredits = 5;
                        break;
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                    case 6:
                        addCredits = 10;
                        break;
                    case 7:
                        return
                        break;

                }
            }

            addLabel.text = `+${addCredits}`;
            addLabel.size = 30;
            addLabel.x = 655;
            addLabel.y = 87;
            addLabel.alpha = 0;
            addLabel.anchorOffsetX = addLabel.width / 2;
            addLabel.anchorOffsetY = addLabel.height / 2;
            addLabel.textColor = 0xffffff;
            this.addChild(addLabel)
            console.log(addLabel);

            egret.Tween.get(addLabel)
                .wait(1500)
                .to({ y: 50, alpha: 1 }, 500)
                .to({ y: 30, alpha: 0 }, 200)
                .call(() => {
                    this.removeChild(addLabel);
                    DataManager.ins.petIndexData.credits += addCredits;
                    this.myCoin.text = '' + DataManager.ins.petIndexData.credits;
                    for (var i: number = 0; i < 7; i++) {
                        this['foodCtner' + i].touchEnabled = true;
                        this['foodCtner' + i].touchChildren = true;
                    }
                    if (this.isGuide) {
                        this.step3()
                    }

                })
        }

    }

    // 第三步引导
    step3Group: any;
    step3Mask: any;
    fingerUp: any;
    // fingerDown: any;
    step3() {
        this.step3Group = new eui.Group();
        this.step3Group.touchEnabled = false;
        this.step3Group.width = 750;
        this.step3Group.height = 1624;
        this.step3Group.x = 0;
        this.step3Group.y = 0;
        this.addChild(this.step3Group);

        this.step3Mask = this.drawMask(this.fctnPosArr[this.itmePos][0] + this.foodGroup.x, this.fctnPosArr[this.itmePos][1] + this.foodGroup.y)
        this.step3Group.addChild(this.step3Mask);

        let collectTips = new eui.Image();
        collectTips.source = `guideStep3Tips_png`;
        collectTips.horizontalCenter = 0;
        collectTips.y = this.fctnPosArr[this.itmePos][1] + this.foodGroup.y - 180;
        this.step3Group.addChild(collectTips)

        this.fingerUp = new eui.Image();
        this.fingerUp.source = `fingerUp_png`;
        this.fingerUp.x = this.fctnPosArr[this.itmePos][0] + this.foodGroup.x - 60;
        this.fingerUp.y = this.fctnPosArr[this.itmePos][1] + this.foodGroup.y + 50;
        this.fingerUp.anchorOffsetX = 118 / 2;
        this.fingerUp.anchorOffsetY = 100 / 2;
        this.fingerUp.touchEnabled = false;
        this.step3Group.addChild(this.fingerUp);
        this.fingerUp.visible = true;

        egret.Tween.get(this.fingerUp, { loop: true })
            .to({ scaleX: 0.8, scaleY: 0.8 }, 330)
            .to({ scaleX: 1, scaleY: 1 }, 330)

    }

    // 第四步引导
    step4Group: any;
    step4Mask: any;
    step4() {
        this.step4Group = new eui.Group();
        this.step4Group.touchEnabled = false;
        this.step4Group.width = 750;
        this.step4Group.height = 1624;
        this.step4Group.x = 0;
        this.step4Group.y = 0;
        this.addChild(this.step4Group);

        // this.step4Mask = this.drawMask(750 / 2, this.stage.stageHeight - 200 + 141 / 2, 100)
        // this.step4Group.addChild(this.step4Mask);

        // let collectTips = new eui.Image();
        // collectTips.source = `guideStep4Tips_png`;
        // collectTips.horizontalCenter = 0;
        // collectTips.y = this.fctnPosArr[this.itmePos][1] + this.foodGroup.y - 180;
        // this.step4Group.addChild(collectTips)

        this.fingerUp = new eui.Image();
        this.fingerUp.source = `fingerUp_png`;
        this.fingerUp.x = 750 / 2 - 118 / 2;
        this.fingerUp.y = this.stage.stageHeight - 200 + 141;
        this.fingerUp.anchorOffsetX = 118 / 2;
        this.fingerUp.anchorOffsetY = 100 / 2;
        this.step4Group.addChild(this.fingerUp);
        this.fingerUp.visible = true;

        egret.Tween.get(this.fingerUp, { loop: true })
            .to({ scaleX: 0.8, scaleY: 0.8 }, 330)
            .to({ scaleX: 1, scaleY: 1 }, 330)

        // this.fingerDown = new eui.Image();
        // this.fingerDown.source = `fingerDown_png`;
        // this.fingerDown.x = this.fctnPosArr[this.itmePos][0] + this.foodGroup.x - 120;
        // this.fingerDown.y = this.fctnPosArr[this.itmePos][1] + this.foodGroup.y + 14;
        // this.fingerUp.visible = false;
        // this.step3Group.addChild(this.fingerDown);
    }

    // fingerCount: number = 0;
    // onEnterFrame() {
    //     super.onEnterFrame();

    //     if (this.fingerDown && this.fingerUp) {
    //         this.fingerCount++;
    //         if (this.fingerCount % 10 == 0 && (this.fingerCount / 10) % 2 == 0) {
    //             this.fingerDown.visible = true;
    //             this.fingerUp.visible = false;
    //         } else if (this.fingerCount % 10 == 0 && (this.fingerCount / 10) % 2 == 1) {
    //             this.fingerDown.visible = false;
    //             this.fingerUp.visible = true;
    //         }
    //     }
    // }

    // 第五步引导  赚积分
    step5Group: any;
    step5Mask: any;
    step5Circle: any;
    step5() {
        this.step5Group = new eui.Group();
        this.step5Group.touchEnabled = false;
        this.step5Group.width = 750;
        this.step5Group.height = 1624;
        this.step5Group.x = 0;
        this.step5Group.y = 0;
        this.addChild(this.step5Group);


        this.step5Mask = this.drawMask(518.28 + 126 / 2, this.stage.stageHeight - 200 + 70, 100)
        this.step5Group.addChild(this.step5Mask);

        this.step5Circle = this.drawCircle(518.28 + 126 / 2, this.stage.stageHeight - 200 + 70, 100)
        this.step5Group.addChild(this.step5Circle);

        this.step5Circle.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_guidePrize, this);

        let collectTips = new eui.Image();
        collectTips.source = `guideStep5Tips_png`;
        collectTips.horizontalCenter = 0;
        collectTips.y = this.stage.stageHeight - 200 - 100;
        this.step5Group.addChild(collectTips)

        this.fingerUp = new eui.Image();
        this.fingerUp.source = `fingerUp_png`;
        this.fingerUp.x = 518.28 + 126 / 2 - 60;
        this.fingerUp.y = this.stage.stageHeight - 200 + 70 + 50;
        this.fingerUp.anchorOffsetX = 118 / 2;
        this.fingerUp.anchorOffsetY = 100 / 2;
        this.step5Group.addChild(this.fingerUp);
        this.fingerUp.visible = true;

        egret.Tween.get(this.fingerUp, { loop: true })
            .to({ scaleX: 0.8, scaleY: 0.8 }, 330)
            .to({ scaleX: 1, scaleY: 1 }, 330)

    }

    onClick_food(item: FoodItem): void {
        // super.onClick_food(item);

        if (this.step3Group && this.step3Group.visible) {
            this.step3Group.visible = false;
        }




        if (DataManager.ins.petHomeInfoData.foodNum >= DataManager.ins.petHomeInfoData.foodStoreLimit) {
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, ["啊哦...食物储存达到上限啦", "快去喂食吧~"], false);
            return;
        }
        if (this.isActPlay) {
            // PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, ["啊哦...您操作太频繁了", "请休息一下~"], false);
            return;
        }
        this.isActPlay = true;

        NetManager.ins.collectFood(function (success: boolean) {
            if (!success) {
                this.isActPlay = false;
                return;
            }
            DataManager.ins.petHomeInfoData.foodNum += item.fcount;


            var fnum: number = DataManager.ins.petHomeInfoData.foodNum;

            console.log('foodCount=', DataManager.ins.petHomeInfoData.foodNum);

            let endAngle;
            if (fnum % 25 == 0) {
                endAngle = 1;
            } else {
                endAngle = (fnum % 25) / 25;
            }

            var ctn: eui.Group = this['foodCtner' + item.pos];
            this.fPosArr.push(item.pos);
            item.removeEvent();
            item.stopAct();

            var endY: number = this.feedBtn.y - this.foodGroup.y;// this.foodGroup.height - 200;// - this.foodGroup.y;// - item.y;
            var endX: number = this.feedBtn.x;// - ctn.x;
            var a: number = this.foodGroup.height - ctn.y;
            var b: number = ctn.x - this.feedBtn.x;
            var time: number = Math.sqrt((a * a) + (b * b)) /
                Math.sqrt(this.foodGroup.height * this.foodGroup.height + this.foodGroup.width * this.foodGroup.width) * 600;

            egret.Tween.get(ctn).to({ x: endX, y: endY, scaleX: 0.3, scaleY: 0.3 }, Math.floor(time)).call(function (item: FoodItem) {
                var pos: number = item.pos;
                var ctn: eui.Group = this['foodCtner' + pos];
                ctn.x = this.fctnPosArr[pos][0];
                ctn.y = this.fctnPosArr[pos][1];
                ctn.scaleX = 1;
                ctn.scaleY = 1;
                ctn.touchEnabled = false;
                ctn.touchChildren = false;
                //移除食物id记录
                this.fidArr.splice(this.fidArr.indexOf(item.fid), 1);
                ctn.removeChild(item);

                // 引导部分
                console.log(this.fidArr.length);
                if (this.isGuide) {
                    if (endAngle == 1) {//&& DataManager.ins.petHomeInfoData.foodNum / DataManager.ins.petHomeInfoData.foodStoreLimit == 1) {
                        setTimeout(() => {
                            this.feedBtnNew.touchEnabled = true;
                            this.step4();
                        }, 2500);
                    }
                }
                //设置粮食进度条
                this.setFoodBar(endAngle, true);

            }, this, [item]);

        }.bind(this), item.fid, DataManager.ins.petIndexData.activityId, DataManager.ins.petHomeInfoData.petId);
    }

    onClick_feedBtnNew() {
        super.onClick_feedBtnNew();
        if (this.isGuide) {
            if (this.step4Group && this.step4Group.visible) {
                this.step4Group.visible = false;
                this.feedBtnNew.touchEnabled = false;
                setTimeout(() => {
                    this.getCoinBtn.touchEnabled = true;
                    this.step5();
                }, 2000);

            }
        }
    }

    onClick_getCoinBtn(): void {
        console.log('赚金币');
        PanelCtrl.instance.btnDelay(this.getCoinBtn);
        // this.setFoodBar(0.25, true);
        let data = { scene: this }
        PanelCtrl.instance.show(ModuleTypes.EARN_GOLD_COIN_PANEL, data);
    }

    onClick_guidePrize() {
        console.log("出奖");
        if (this.step5Group && this.step5Group.visible) {
            this.step5Group.visible = false;

            // 引导插件id
            let plugId = window['guidePrizePlugId'] ? window['guidePrizePlugId'] : 1309
            Loading.instace.show();
            NetManager.ins.doJoinPlugDraw((s) => {
                this.myCoinGroup.touchEnabled = true;
                this.myCoinGroup.touchChildren = true;
                this.feedBtnNew.touchEnabled = true;
                this.boatGroup.touchEnabled = true;
                this.boatGroup.touchChildren = true;
                this.getCoinBtn.touchEnabled = true;
                this.mijiBtn.touchEnabled = true;
                this.isGuide = false;
                if (!s) {
                    // 失败弹窗
                    Loading.instace.hide();
                    PanelCtrl.instance.show(ModuleTypes.GUIDE_PRIZE_PANEL, false);
                    return
                }
                NetManager.ins.getPlugOrderStatus(
                    (ss) => {
                        Loading.instace.hide();
                        if (ss) {
                            // DataManager.ins.petIndexData.credits += 200;
                            this.onTour();
                            PanelCtrl.instance.show(ModuleTypes.GUIDE_PRIZE_PANEL, true)
                        } else {
                            PanelCtrl.instance.show(ModuleTypes.GUIDE_PRIZE_PANEL, false);
                        }
                    },
                    DataManager.ins.doJoinPlugDrawData.orderId,
                    () => {
                        return DataManager.ins.getPlugOrderStatusData.result == 0
                    }
                )

            }, plugId)
        }
        // PanelCtrl.instance.show()
    }

    // 网鱼网咖额外奖励
    onTap_boat() {
        if (DataManager.ins.getPrizeInfoList[`${window['extraPlugId']}`] && DataManager.ins.getPrizeInfoList[`${window['extraPlugId']}`].limitCount > 0) {
            let plugId = window['extraPlugId'] ? window['extraPlugId'] : 1309
            Loading.instace.show();
            NetManager.ins.doJoinPlugDraw((s) => {
                if (!s) {
                    // 失败弹窗
                    Loading.instace.hide();
                    return
                }
                NetManager.ins.getPlugOrderStatus(
                    (ss) => {
                        Loading.instace.hide();
                        if (ss) {
                            NetManager.ins.getPrizeInfo((sss) => {

                                // DataManager.ins.petIndexData.credits += 100;
                                this.onTour();
                                PanelCtrl.instance.show(ModuleTypes.EXTRA_PRIZE_PANEL, true)

                            }, window['extraPlugId'])
                        } else {
                            PanelCtrl.instance.show(ModuleTypes.EXTRA_PRIZE_PANEL, false)
                        }
                    },
                    DataManager.ins.doJoinPlugDrawData.orderId,
                    () => {
                        return DataManager.ins.getPlugOrderStatusData.result == 0
                    }
                )

            }, plugId)
        } else {
            PanelCtrl.instance.show(ModuleTypes.EXTRA_PRIZE_PANEL, false)
        }

    }

    // 二次贝塞尔,用于做曲线运动
    public bezier(t: number, p0: number, p1: number, p2: number) {
        // (1-t)^2 P0 + 2(1-t)tP1+ t^2P2
        return Math.pow(1 - t, 2) * p0 + 2 * (1 - t) * t * p1 + Math.pow(t, 2) * p2;
    }

    public drawMask(targetX: number, targetY: number, radius: number = 80) {
        const mask = new egret.Shape();
        // 画方形
        mask.graphics.beginFill(0x000000, 0.7);
        mask.graphics.moveTo(0, 0);
        mask.graphics.lineTo(750, 0);
        mask.graphics.lineTo(750, this.stage.stageHeight);
        mask.graphics.lineTo(0, this.stage.stageHeight);
        mask.graphics.lineTo(0, 0);
        // 画圆
        mask.graphics.drawArc(targetX, targetY, radius, 0, Math.PI * 2, true)
        mask.graphics.endFill();
        mask.touchEnabled = true;
        return mask;
    }

    public drawCircle(targetX, targetY, radius: number = 80) {
        const circle: egret.Shape = new egret.Shape();
        circle.graphics.beginFill(0x000000, 0);
        circle.graphics.drawArc(targetX, targetY, radius, 0, Math.PI * 2, true)
        circle.graphics.endFill();
        circle.touchEnabled = true;

        return circle;
    }
}