import { PlayScene } from './playScene/PlayScene';


import Sprite from "../../engine/2d/display/Sprite";
import { Event } from "../../engine/2d/events/Event";

import Graphics from "../../engine/2d/graphics/Graphics";
import { Shape } from "../../engine/2d/graphics/Shape";
import { MouseEvent } from "../../engine/2d/events/MouseEvent";
import Tween from "../../engine/tween/Tween";
import { Button } from "../../engine/2d/ui/Button";
import Texture from "../../engine/2d/texture/Texture";
import { VERTICAL_ALIGN, TEXT_ALIGN, BLEND_MODES, WRAP_MODES } from "../../engine/2d/const";
import { EditableText } from "../../engine/2d/text/EditableText";
import { TextField } from "../../engine/2d/text/TextField";
import { ScrollPage } from "../../engine/2d/ui/ScrollPage";
import Container from "../../engine/2d/display/Container";
import { ScrollList, IScrollListItem } from "../../engine/2d/ui/ScrollList";
import { Loader } from "../../engine/2d/loader/Loader";
import { MovieClip } from "../../engine/2d/svga/MovieClip";
import { Point } from "../../engine/2d/math";
import { BlurFilter, DisplacementFilter, ColorMatrixFilter, NoiseFilter, FXAAFilter } from "../../engine/2d/filter";
import BlurFilterNew from "../../engine/2d/filter/blur/BlurFilterNew";
import { AdjustmentFilter } from "../../engine/2d/filter/adjustment/AdjustmentFilter";
import { AdvancedBloomFilter } from "../../engine/2d/filter/advanced-bloom/AdvancedBloomFilter";
import { Scene } from "../../module/views/Scene";
import { RES } from "../../module/RES";
import { changeScene, showPanel } from "../../module/ctrls";
import { layers } from "../../module/views/layers";
import { NineSlicePlane } from '../../engine/2d/mesh';
import { Rope } from '../../engine/2d/mesh/Rope';
import { GameOverPanel } from '../panels/GameOverPanel';
import { PropOutPanel } from '../panels/PropOutPanel';
import { TaskPanel } from '../panels/TaskPanel';
import { PropPanel } from '../panels/PropPanel';
import { QuitPanel } from '../panels/QuitPanel';
import { UnlockPanel } from '../panels/UnlockPanel';
import { TaskCompletePanel } from '../panels/TaskCompletePanel';


export class StartScene extends Scene {
    get groupNames(): string[] { return ["startScene"] }
    start() {
        super.start();
        showPanel(TaskPanel)
        // showPanel(TaskCompletePanel)
        // showPanel(UnlockPanel,{grade:128})
        // showPanel(PropPanel, {
        //     bombCount: 22,
        //     exchangeCount: 22,
        //     netCount: 33,
        //     score: 22,
        //     grade: 1024,
        // })
        // showPanel(QuitPanel, {
        //     score: 22,
        //     grade: 1024,
        // })
        // showPanel(GameOverPanel, {
        //     score: 4444,
        //     playDuration: 956456,
        //     grade: 1024,
        //     credits: 20,
        //     creditsTimesToday: 1
        // })
        // setTimeout(() => {
        //     // console.log(this.stage)
        //     // this.stage.globalToLocal(new Point(10, 1))
        //     console.log(this.localToGlobal(new Point(375, 10)))

        //     // console.log(this.stage.globalToLocal(this.localToGlobal(new Point(375, 10))))
        // }, 100)

        //圆形遮罩存在锯齿，
        // this.test()
        // this.testText()
        // this.test2();
        // this.testScroll()
        // this.scrach()
        // this.testList();
        // this.testMovieClip()
        // this.testGrapicsLine();
        // this.testDisplaceFilter()
        // this.testEditableText()
        // this.testNine();
        // this.testRope()
    }
    //初始化ui
    initUi() {
        var bg = new Sprite(RES.getRes("startBtn.png"))
        // Tween.get(bg, { loop: true })
        //     .to({ tint: 0 }, 5000)
        // bg.tint=0xff0000
        // bg.addEventListener(MouseEvent.CLICK,()=>{
        //     console.log(555);
        //     bg.removeAllEventListener()
        // })
        // setTimeout(()=>{
        //     bg.addEventListener(MouseEvent.CLICK,()=>{console.log(666)})
        // },5000)
        this.addChild(bg);
        var textureStartBtn: Texture = RES.getRes("startBtn.png")
        var startBtn = new Button(textureStartBtn)
        startBtn.x = 259
        startBtn.y = 773;
        this.addChild(startBtn);
        startBtn.once(MouseEvent.CLICK, this.onClick_startBtn, this)
        // startBtn.blendMode=BLEND_MODES.ERASE
        // startBtn.alpha=0.1
        console.log(this.getLocalBounds())

        //模糊滤镜
        var f = new BlurFilterNew();
        f.blur = 0
        // startBtn.filters = [f]
        // Tween.get(f, { loop: true }).to({ blur: 1 }, 5000).to({ blur: 0 }, 5000)
        // bg.mask=new Sprite(textureStartBtn)
        // this.addChild(bg.mask)
        // bg.mask.x=bg.mask.y=200

        //颜色滤镜
        let colorFilter = new ColorMatrixFilter([
            0.3, 0.6, 0, 0, 0,
            0.3, 0.6, 0, 0, 0,
            0.3, 0.6, 0, 0, 0,
            0, 0, 0, 1, 0
        ]);
        // startBtn.filters = [colorFilter];

        //噪声滤镜
        var noise = new NoiseFilter();
        // startBtn.filters = [noise]

        //FXAA
        // var fxaa=new FXAAFilter()
        // startBtn.filters = [fxaa]

        //色调
        var adjust = new AdjustmentFilter({ saturation: 10, brightness: 1 })
        // startBtn.filters = [adjust]

        //bloom
        var bloom = new AdvancedBloomFilter({ bloomScale: 0.4 })
        // startBtn.filters = [bloom]
    }

    onClick_startBtn() {
        changeScene(PlayScene);
    }


    testText() {
        var textNode = new TextField();
        textNode.size = 50;
        textNode.fillColor = "0xffffff";
        textNode.text = "啊是大\n阿三";
        // textNode.verticalAlign = VERTICAL_ALIGN.MIDDLE;
        textNode.lineSpacing = 20
        // textNode.textHeight = 30;
        textNode.textAlign = TEXT_ALIGN.CENTER;
        // textNode.border = true
        this.addChild(textNode)
        console.log(textNode)
        textNode.x = (layers.stageWidth - textNode.textWidth) / 2;
    }


    testEditableText() {
        var t = new EditableText();
        t.textColor = "#ffffff";
        t.prompt = "请数额u";
        t.promptColor = "#ff0000";
        t.textWidth = 200;
        t.textAlign = TEXT_ALIGN.CENTER;
        t.size = 50;
        this.addChild(t)
        t.x = 50;
        t.y = 100;
    }

    test() {
        var tnum = 8000;
        console.log("同屏数：" + tnum)
        var a = false;
        for (var i = 0; i < tnum; i++) {
            a = !a;
            let sprite = Sprite.fromUrl(a ? "../resource/11.png" : "../resource/黄-1.png", true);
            sprite.alpha = 0.5
            // let sprite = new Sprite(texture)
            sprite.x = Math.random() * 750;
            sprite.y = Math.random() * 1206;
            // sprite.x = 100;
            // sprite.y = 100;
            sprite.anchorTexture.set(0.5, 0.5);
            sprite.scaleX = 0.3;
            sprite.scaleY = 0.3;
            sprite.addEventListener(Event.ENTER_FRAME, () => {
                sprite.rotation += 10
                // if(sprite.mask){
                //     sprite.mask.rotation+=0.05
                // }
            })
            this.addChild(sprite)
        }
    }
    test2() {
        var tnum = 4000;
        console.log(tnum)
        for (var i = 0; i < tnum; i++) {
            let sprite = new Graphics();
            sprite.x = Math.random() * 750;
            sprite.y = Math.random() * 1206;
            // sprite.tint=0x0000ff
            // sprite.alpha=0.5
            sprite.beginFill(0xff0000, 1);
            sprite.drawRect(-30, -30, 60, 60);
            sprite.endFill();
            sprite.addEventListener(Event.ENTER_FRAME, () => {
                sprite.rotation += 10
                // if(sprite.mask){
                //     sprite.mask.rotation+=0.05
                // }
            })
            this.addChild(sprite)
        }
    }

    testScroll() {
        var image = new Sprite(RES.getRes("startBg.jpg"));
        var sPage = new ScrollPage(750, layers.stageHeight, 1624, true, true);
        sPage.view.addChild(image);
        this.addChild(sPage);
        sPage.x = 100;
        sPage.y = 100;

        var delta = 10
        var sc = new ScrollPage(750, 200, 1624, false, false);
        sc.maxDistance = delta * (10 - 1) + 200 * 10;
        sc.y = 900;
        sPage.view.addChild(sc);


        for (var i = 0; i < 10; i++) {
            let image = new Sprite(RES.getRes("startBtn.png"));
            image.width = 200;
            image.height = 200;
            image.x = delta * i + i * 200
            sc.view.addChild(image)
        }
    }

    scrach() {
        var container = new Container();
        this.addChild(container);
        //448 114
        var image = new Sprite(RES.getRes("startBtn.png"))
        container.addChild(image);
        //接收事件的
        var gg = new Graphics();
        gg.beginFill(0xff0000, 0);
        gg.drawRect(0, 0, 500, 500);
        gg.endFill();
        container.addChild(gg)
        var mask = new Graphics();
        container.addChild(mask);
        // image.mask = mask;
        var points: { x: number, y: number }[][] = [];
        var tempPoints: { x: number, y: number }[] = [];
        this.addEventListener(MouseEvent.MOUSE_DOWN, (e: MouseEvent) => {
            points.push(tempPoints);
            tempPoints.push({ x: e.localX, y: e.localY })
        }, this)
        this.addEventListener(MouseEvent.MOUSE_MOVE, (e) => {
            tempPoints.push({ x: e.localX, y: e.localY });
            draw(points)
        }, this)
        this.addEventListener(MouseEvent.MOUSE_UP, (e) => {
            tempPoints = [];
        }, this)
        this.addEventListener(MouseEvent.MOUSE_OUT, (e) => {
            tempPoints = [];
        }, this)
        function draw(points) {
            if (!points.length) return;
            mask.clear();
            //两种图形drawCircle和lineStyle的混用，有问题，待查
            for (var i = 0; i < points.length; i++) {
                var tempPoints = points[i];
                if (tempPoints.length < 2) continue
                mask.beginFill(0xff0000);
                mask.drawCircle(tempPoints[0].x, tempPoints[0].y, 2);
                mask.endFill()
                mask.lineStyle(50, 0xff0000, 1)
                mask.moveTo(tempPoints[0].x, tempPoints[0].y);
                for (var j = 1; j < tempPoints.length - 1; j++) {
                    mask.lineTo(tempPoints[j].x, tempPoints[j].y);
                }
                mask.endFill()
                mask.beginFill(0xff0000);
                mask.drawCircle(tempPoints[tempPoints.length - 1].x, tempPoints[tempPoints.length - 1].y, 2);
                mask.endFill()
            }
        }
        // let renderTexture: egret.RenderTexture = new egret.RenderTexture();
        // renderTexture.drawToTexture(container);
        // var canvas = document.createElement("canvas");
        // canvas.width = 448;
        // canvas.height = 114;
        // var ctx = canvas.getContext("2d");
        // let img=new Image();
        // img.onload=function(){
        //     ctx.clearRect(0,0,canvas.width,canvas.height)
        //     ctx.drawImage(img,0,0)
        // }
        // img.src=renderTexture.toDataURL("image/png");
    }

    testList() {
        var list = new ScrollList(Item1, 100, 60, 100, 200, true)
        list.x = 100;
        list.y = 100;
        list.updateData([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
        this.addChild(list);
        setTimeout(() => {
            list.scrollTo(900, 2000)
        }, 2000)

    }

    testMovieClip() {
        var loader = new Loader();
        loader.loadSvga((s, v) => {
            var m = new MovieClip(v);
            this.addChild(m)
        }, "../resource/card3.svga")
    }

    testGrapicsLine() {
        var g = new Graphics();
        g.beginFill(0xffffff);
        g.drawCircle(100, 100, 50);
        g.endFill()
        this.addChild(g)
        g.lineStyle(10, 0xff0000)
        g.moveTo(100, 100)
        g.lineTo(400, 300)
        g.endFill()
        g.beginFill(0xffffff);
        g.drawCircle(400, 300, 50);
        g.endFill()
    }

    testDisplaceFilter() {
        //滤镜测试
        new Loader().loadImage((s, i) => {
            if (!s) return;
            //注意只能用单图，不能用图集，因为这个纹理需要重复
            var displacementSprite = Sprite.from(i)
            var displacementFilter = new DisplacementFilter(displacementSprite, 50);
            displacementSprite.texture.baseTexture.wrapMode = WRAP_MODES.REPEAT;
            displacementFilter.autoFit = true;
            this.filters = [displacementFilter];
            this.addChild(displacementSprite);
            displacementSprite.scaleX = 2;
            displacementSprite.scaleY = 2;
            let aa = Date.now();
            this.addEventListener(Event.ENTER_FRAME, () => {
                var delta = Date.now() - aa
                displacementSprite.x += 10;
                displacementSprite.y += 3;
            }, this)
        }, "resource/clouds.jpg")

    }
    //九宫格测试
    testNine() {
        var a = new NineSlicePlane(RES.getRes("startBtn.png"), 30, 30, 30, 40)
        this.addChild(a)
        Tween.get(a).to({ width: 750, height: 200 }, 5000)
    }
    //测试Rope
    testRope() {
        let count = 0;
        // build a rope!
        const ropeLength = 918 / 20;
        const points = [];
        for (let i = 0; i < 20; i++) {
            points.push(new Point(i * ropeLength, 0));
        }

        const strip = new Rope(RES.getRes('snake.png'), points);

        strip.x = -459;

        const snakeContainer = new Container();
        snakeContainer.x = 400;
        snakeContainer.y = 300;

        snakeContainer.scale.set(800 / 1100, 800 / 1100);
        this.addChild(snakeContainer);

        snakeContainer.addChild(strip);
        // strip.autoUpdateVertices=true
        this.addEventListener(Event.ENTER_FRAME, () => {
            count += 0.1;
            for (let i = 0; i < points.length; i++) {
                points[i].y = Math.sin((i * 0.5) + count) * 30;
                points[i].x = i * ropeLength + Math.cos((i * 0.3) + count) * 20;
            }
            strip.refreshVertices()
        }, this)
    }

}

class Item1 extends Sprite implements IScrollListItem {
    id: number;
    data: number;

    txt: TextField
    constructor() {
        super()
        this.txt = new TextField();
        this.txt.size = 50;
        this.txt.fillColor = "#ff0000";
        this.addChild(this.txt)
    }
    initData(id, data) {
        this.txt.text = data + ""
    }
}