import { getTexture, createSvga } from "./utils";

import Human from "./Human";
import Moist from "./Moist";
import TimeCounter from "./TimeCounter";
import CloudRain from "./CloudRain";
import gameStage = engine.gameStage;

export default class GameTest extends engine.Container {
    constructor() {
        super();
        this.once(engine.Event.ADDED_TO_STAGE, this.setup, this);
    }

    rightHand: engine.Sprite;
    // ambrella: engine.Sprite;
    playBtn: engine.Sprite;
    human: engine.Sprite;

    humanbeing: Human;
    moists: Moist;
    contain: any;
    timeCounter: TimeCounter;
    cloudRain: CloudRain;
    cloud: CloudRain;
    winds
    rainEffect
    timeArray: any[] = []
    container: engine.Container = new engine.Container()

    setup() {
        let playBg = new engine.Sprite(
            getTexture("5ab43bdc-a6ce-46fb-99c2-a806f57f7484")
        );
        this.addChild(playBg);

        // this.human = new engine.Sprite(
        //     getTexture("487c1ca7-dea5-4732-b4b6-acb5406ee3a4")
        // );
        // this.human.x = 290;
        // this.human.y = 900;
        // 人
        this.humanbeing = new Human();
        this.humanbeing.x = 290;
        // this.humanbeing.y = 900;
        this.humanbeing.y = 750;
        this.addChild(this.humanbeing);

        // this.contain = new engine.Sprite()
        console.log(
            "xxxxxx",
            this.stage.width,
            this.stage.height,
            this.width,
            this.height
        );

        // 手和伞为一个整体
        this.rightHand = new engine.Sprite(
            getTexture("c7129f77-92a6-479e-9994-7d4b39040a15")
        );
        this.rightHand.x = -70;
        this.rightHand.y = -65;
        this.rightHand.anchorX = 196;
        this.rightHand.anchorY = 253;

        this.humanbeing.addChild(this.rightHand);

        // this.addChild(this.human);
        // this.human.addChild(this.rightHand);

        this.playBtn = new engine.Sprite(
            getTexture("9e347bef-6e91-4c92-ba5f-f9a52e656207")
        );
        this.playBtn.x = 138;
        this.playBtn.y = 1150;
        this.playBtn.anchorX = this.playBtn.x + this.playBtn.width / 2;
        this.playBtn.anchorY = this.playBtn.y + this.playBtn.height / 2;
        this.addChild(this.playBtn);
        // 湿润度
        this.moists = new Moist();
        this.moists.x = 20;
        this.moists.y = 450;
        this.addChild(this.moists);

        // 云
        this.cloud = new CloudRain();
        this.addChild(this.cloud);

        this.timeArray.push(this.t3, this.t2, this.t1);
    }

    dripArray: any[] = [];
    clicknum: number = 0;
    R: number = 250;
    D: number = 340;
    angle: number;

    con: engine.Sprite = new engine.Sprite();

    // 游戏开始前倒计时三张图
    t1 = new engine.Sprite(getTexture('a163b74f-32bc-43d2-8015-7cf1eac71501'));
    t2 = new engine.Sprite(getTexture('22de82d1-97ec-4195-a32c-f4fc1656e2de'));
    t3 = new engine.Sprite(getTexture('cc952365-a990-4912-98af-50905559b9d5'));


    start() {
        const middleX = this.humanbeing.x + this.humanbeing.width / 2;
        const validX1 = this.humanbeing.x;
        const validX2 = this.humanbeing.x + this.humanbeing.width;

        let point1 = new engine.Graphics();
        point1.beginFill(0xff0000);
        point1.drawRect(0, 0, 10, 10);
        point1.x = 0;
        point1.y = 100;
        point1.endFill();
        // this.addChild(point1)
        this.rightHand.addChild(point1);

        let point2 = new engine.Graphics();
        point2.beginFill(0xff0000);
        point2.drawRect(0, 0, 10, 10);
        point2.x = 170;
        point2.y = 0;
        point2.endFill();
        // this.addChild(point2)
        this.rightHand.addChild(point2);

        let point3 = new engine.Graphics();
        point3.beginFill(0xff0000);
        point3.drawRect(0, 0, 10, 10);
        point3.x = 330;
        point3.y = 100;
        point3.endFill();
        // this.addChild(point3)
        this.rightHand.addChild(point3);

        window['p1'] = point1;
        // @ts-ignore
        window['p2'] = point2;
        window['p3'] = point3;

        //计时器
        this.timeCounter = new TimeCounter();
        this.addChild(this.timeCounter);

        let ld = Date.now();

        let a = 0;
        let b = 0;

        let timer = 0;

        let succeedFlag = false;
        let failFlag = false;


        // 倒计时
        for (let i = 0; i < this.timeArray.length; i++) {
            let t = this.timeArray[i]
            t.anchorTexture.set(0.5, 0.5);
            t.x = 750 / 2;
            t.y = 1624 / 2;
            t.alpha = 0;
            this.container.addChild(t);
            this.addChild(this.container)
        }
        for (let i = 0; i < this.timeArray.length; i++) {
            let img = this.timeArray[i];
            let delta = i * 1000;
            let t = engine.Tween.get(img);
            t.wait(delta).set({alpha: 0.2, scaleX: 2, scaleY: 2})
                .to({alpha: 1, scaleX: 1, scaleY: 1}, 300)
                .to({alpha: 0}, 200)
                .wait(500);
            if (i === this.timeArray.length - 1) {
                t.call(() => {
                    engine.Tween.get(this.container).to({alpha: 0}, 200).call(() => {
                        this.removeChild(this.container)
                    })

                    // 风吹动效
                    this.winds = createSvga("wind");
                    this.addChild(this.winds);
                    this.winds.visible = true;
                    this.winds.play(true, true)
                    this.winds.once(engine.Event.END_FRAME, () => {
                        this.removeChild(this.winds);
                    }, this)
                })

            }
        }

        // 雨滴动效
        this.rainEffect = createSvga("雨滴动效");

        this.addEventListener(engine.Event.ENTER_FRAME, function addFrame() {
            let dt = Date.now() - ld;

            b += dt;
            timer += dt;

            // 延迟三秒执行
            if (timer >= 3000) {
                a += dt;
                if (a > 10) {
                    a = 0;
                    if (this.moists.percent < 1 && this.timeCounter.time > 0) {
                        let drip = new engine.Sprite(getTexture("07f74bf6-416f-445e-98d5-021efe4c9fdc"));
                        drip.x = Math.random() * (this.humanbeing.x + 160) + (this.humanbeing.x - 160);
                        drip.y = Math.random() * 100 + 300;
                        this.dripArray.push(drip);
                        this.addChild(drip);
                    }

                }

                // 雨滴下落
                for (let drip of this.dripArray) {
                    drip.y += (300 * dt) / 1000;
                    if (drip.y > this.stage.height) {
                        let index = this.dripArray.indexOf(drip);
                        this.removeChild(drip);
                        this.dripArray = this.dripArray.filter(
                            (ele, i) => i != index
                        );
                    }
                }


                //计时器
                if (b >= 1000) {
                    b = 0;
                    if (this.moists.percent < 1) {
                        this.timeCounter.time -= 1;
                        if (this.timeCounter.time <= 0) {
                            this.timeCounter.time = 0;
                        }
                        this.timeCounter.updateTime(this.timeCounter.time);
                    }

                    if (this.timeCounter.time <= 0 && !succeedFlag) {
                        this.timeCounter.time = 0;
                        succeedFlag = true;
                        console.log("游戏成功！");
                        // 云动画
                        // 雨水结束
                        // 太阳出来
                        this.success();
                        // this.removeEventListener(engine.Event.END_FRAME,()=>{})
                        // if(succeedFlag){
                        // }
                    }
                }

                // 伞的旋转
                let wind = -40;
                this.rightHand.rotation += wind / 60;

                if (this.rightHand.rotation <= -90) {
                    this.rightHand.rotation = -90;
                } else if (this.rightHand.rotation >= 90) {
                    this.rightHand.rotation = 90;
                }

                // 吃力表情
                if (this.rightHand.rotation <= -60) {
                    let face = this.humanbeing.facialChange(1);
                    face.x = 7;
                    face.y = 22;
                    setTimeout(() => {
                        this.humanbeing.removeFace(face);
                    }, 100);
                }

                // ld = Date.now();

                // return;
                // 扇形的角度
                this.angle = Math.asin(this.D / 2 / this.R) * 57.18;

                // 伞的偏移角度距离水平位置
                let validMaxX;
                let validMinX;
                // 伞的圆函数
                let ambrellaFuncY;

                this.rightHand.name = "aaa";

                // a.worldMatrix.tx

                // point1,2线性方程斜率

                const sa = this.worldMatrix.a;
                const sd = this.worldMatrix.d;

                const p1x = point1.worldMatrix.tx / sa;
                const p2x = point2.worldMatrix.tx / sa;
                const p3x = point3.worldMatrix.tx / sa;
                const p1y = point1.worldMatrix.ty / sd;
                const p2y = point2.worldMatrix.ty / sd;
                const p3y = point3.worldMatrix.ty / sd;

                let k12 = (p1y - p2y) / (p1x - p2x);
                let k23 = (p2y - p3y) / (p2x - p3x);

                let px1 = p1x;
                let px2 = p2x;
                let px3 = p3x;

                let maxX = px1 >= px2 ? (px1 >= px3 ? px1 : px3) : px2 >= px3 ? px2 : px3;
                let minX = px1 >= px2 ? (px2 >= px3 ? px3 : px2) : px1 >= px3 ? px3 : px1;

                let x2 = (middleX + this.R) < maxX ? (middleX + this.R) : maxX;

                for (let drip of this.dripArray) {

                    const dx = drip.worldMatrix.tx / sa;
                    const dy = drip.worldMatrix.ty / sd;

                    // point1,2线性方程
                    let b12 = p1y - p1x * k12 - 50;
                    let b23 = p2y - p2x * k23 - 50;
                    let y12 = k12 * dx + b12;
                    let y23 = k23 * dx + b23;
                    if (dx >= minX && dx < maxX) {
                        // 伞碰撞12
                        if (dx < px2) {
                            // if (Math.abs(y12 -drip.worldMatrix.ty) <= 20) {
                            if (dy >= y12) {
                                let index = this.dripArray.indexOf(drip);
                                this.removeChild(drip);
                                this.dripArray = this.dripArray.filter(
                                    (ele, i) => i != index
                                );
                            }
                            // }
                        }
                        // 23
                        if (dx >= px2) {
                            // if (Math.abs(y23 -drip.worldMatrix.ty) <= 20) {
                            if (dy >= y23) {
                                let index = this.dripArray.indexOf(drip);
                                this.removeChild(drip);
                                this.dripArray = this.dripArray.filter(
                                    (ele, i) => i != index
                                );
                            }
                            // }
                        }
                    }

                    // 碰人
                    if (drip.x > this.humanbeing.x &&
                        drip.x < this.humanbeing.x + this.humanbeing.width) {
                        if (drip.y >= this.humanbeing.y) {
                            // 湿润度增加
                            this.moists.percent += 0.1;
                            this.moists.cover(this.moists.percent);
                            this.moists.updateText(this.moists.percent);
                            // this.moists.updatePercent(this.moists.percent);


                            // 雨滴动效
                            this.addChild(this.rainEffect);
                            this.rainEffect.visible = true;
                            this.rainEffect.play(true, true);
                            this.rainEffect.x = drip.x - drip.width * 2;
                            this.rainEffect.y = drip.y;
                            this.rainEffect.once(engine.Event.END_FRAME, () => {
                                this.rainEffect.visible = false;
                            })

                            if (this.moists.percent >= 1 && !failFlag) {
                                // 游戏结束
                                this.moists.stopScale();
                                failFlag = true;
                                console.log("游戏结束！");
                                // 清除事件
                                this.stop();
                                // this.timeCounter.updateTime(this.timeCounter.time);
                            }

                            this.removeChild(drip);
                            // 表情改变
                            let face = this.humanbeing.facialChange(2);
                            face.x = 7;
                            face.y = 22;
                            setTimeout(() => {
                                this.humanbeing.removeFace(face);
                            }, 500);
                            console.log("人");

                            let index = this.dripArray.indexOf(drip);
                            this.dripArray = this.dripArray.filter(
                                (ele, i) => i != index
                            );

                            // 动效
                            this.humanbeing.scaleEffect();
                        }
                    }
                }
            }


            ld = Date.now();
        });

        this.playBtn.addEventListener(
            engine.MouseEvent.CLICK,
            this.onClick,
            this
        );
        this.rightHand.rotation = 0;
    }

    onClick() {
        this.clicknum += 1;
        this.rightHand.rotation += 10 * this.clicknum;
        this.clicknum = 0;
        // engine.Tween.get(this.playBtn)
        //     .set({scaleX:1,scaleY:1})
        //     .to({scaleX:1.1,scaleY:1.1},100)
        //     .to({scaleX:1,scaleY:1},100)


    }

    stop() {
        // this.removeAllEventListener();
        // this.playBtn.removeAllEventListener();
        engine.globalEvent.dispatchEvent("cloud-game-fail", {reason: 1});

    }

    success() {
        this.cloud.succeed();
        engine.globalEvent.dispatchEvent("cloud-game-success", {
            moist: this.moists.percent,
        });
    }
}
// }

