import { asyncDelay, onHomeworkFinish } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import pg from "./tool/pg";
import { GameNGT14 } from "./tool/Game";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
        this._imageResList.push({ url: this.data.pic_url });
        this._imageResList.push({ url: this.data.pic_url_2 });
    }

    addPreloadAudio() {
        // TODO 根据自己的配置预加载音频资源
        this._audioResList.push({ url: this.data.audio_url });
    }

    addPreloadAnima() {

    }

    onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initListener();
        this.gameStart();
    }

    _cantouch = null;
    initData() {
        // 所有全局变量 默认都是null 
        this._cantouch = true;
        GameNGT14.getIns().initData(this.data);
        GameNGT14.getIns().reset();
        let data = GameNGT14.getIns().getCurrent();
        console.log('gamestart', data)
    }

    initView() {
        this.initBlocks();
    }

    initListener() {

    }
    private layout_blocks: cc.Node;
    private layout_words: cc.Node;
    initBlocks() {
        this.layout_blocks = pg.view.find(this, 'layout_blocks');
        this.layout_blocks.removeAllChildren()
        let block = pg.view.find(this, 'block');
        //动态创建，并给每一个打上编号
        let space = { x: 9 + 80, y: 10 + 80 }
        for (let y = 0; y < 9; y++) {
            for (let x = 0; x < 12; x++) {
                let node = cc.instantiate(block);
                let data = { x, y };
                node.data = data;
                node.x = -495 + space.x * x;
                node.y = 365 - space.y * y;
                node.active = !!GameNGT14.getIns().getBlockVal(x, y);
                this.layout_blocks.addChild(node);
            }
        }
    }
    gameStart() {
        let word = pg.view.find(this, 'word');
        this.layout_words = pg.view.find(this, 'layout_words');
        this.layout_words.removeAllChildren()
        let words = GameNGT14.getIns().getCurrent().getWords();
        let space = { x: 150, y: 150 }
        words.forEach((w, index) => {
            let node = cc.instantiate(word);
            let data = w;
            if (index < 5) {
                node.x = 280 + space.x * index
                node.y = -110
            } else if (index < 9) {
                node.x = 355 + space.x * (index - 5)
                node.y = -110 - space.y;
            } else {
                node.x = 280 + space.x * (index - 9)
                node.y = -110 - space.y * 2;
            }
            this.layout_words.addChild(node);
            this.updateWord(node, data);
        });
    }
    updateWord(node, data) {
        node.data = data;
        pg.view.setString(pg.view.find(node, 'label'), data);

        node.on(cc.Node.EventType.TOUCH_START, this.onItemTouchStart, this);
        node.on(cc.Node.EventType.TOUCH_MOVE, this.onItemTouchMove, this);
        node.on(cc.Node.EventType.TOUCH_END, this.onItemTouchEnd, this);
        node.on(cc.Node.EventType.TOUCH_CANCEL, this.onItemTouchCancel, this);
    }
    private setTouchPos(e) {
        let item = e.target;
        let location = e.getLocation();
        cc.Tween.stopAllByTarget(item);
        let pos = location.sub(cc.v2(1920 / 2, 1080 / 2));
        item.x = pos.x;
        item.y = pos.y;
    }
    private touching: any;
    onItemTouchStart(e) {
        if (this.touching) return;
        let target: cc.Node = e.target;
        let data: string = target.data;
        this.setTouchPos(e);
        this.touching = data;
    }
    onItemTouchMove(e) {
        let target: cc.Node = e.target;
        let data = target.data;
        if (!this.touching) return;
        if (this.touching != data) return;
        this.setTouchPos(e);
    }
    onItemTouchEnd(e) {
        let target: cc.Node = e.target;
        let data = target.data;
        if (!this.touching) return;
        if (this.touching != data) return;
        // let rect = cc.rect(target.x, target.y, target.width, target.height);
        let rect = cc.rect(target.x, target.y, 50, 50);
        //坐标转换
        console.log("1123123123")
        return;


        let boat_left = pg.view.find(this, 'layout_bottom/boat_left')
        let boat_right = pg.view.find(this, 'layout_bottom/boat_right')
        let leftRect = cc.rect(boat_left.x - boat_left.width / 2, boat_left.y - boat_left.height / 2, boat_left.width, boat_left.height);
        let rightRect = cc.rect(boat_right.x - boat_right.width / 2, boat_right.y - boat_right.height / 2, boat_right.width, boat_right.height);

        let isRight = false;
        let currentRect = null;
        // if (rect.intersects(leftRect)) {
        //     isRight = !!Game.getIns().boatLeft.isChild(data);
        //     Game.getIns().boatLeft.setRight(data);
        //     currentRect = leftRect;
        // } else if (rect.intersects(rightRect)) {
        //     isRight = !!Game.getIns().boatRight.isChild(data);
        //     Game.getIns().boatRight.setRight(data);
        //     currentRect = rightRect;
        // }
        if (!currentRect) {
            this.touching = null;
            this.playLocalAudio('error').then(() => {
                this.touching = null;
                // this.updateItem(target, data);
            })
            return;
        }
        if (isRight) {
            let item = target;
            let lastArea = 100;
            // this.playLocalAudio('right').then(() => {
            //     if (data.audioUrl) {
            //         pg.audio.playAudioByUrlThen(data.audioUrl).then(() => {
            //             this.touching = null;
            //         })
            //     } else {
            //         this.touching = null;
            //     }
            // })

            if (item.scaleX == -1) {
                // 计算当前坐标距离最左侧的距离
                let space = currentRect.width - ((rect.x + rect.width) - currentRect.x) - lastArea / 5;
                let time = space / 10;
                cc.tween(item).by(time, { x: space }).start();
            } else {
                // 计算当前坐标距离最左侧的距离
                let space = rect.x - currentRect.x - lastArea;
                let time = space / 10;
                cc.tween(item).by(time, { x: -space }).start();
            }
            item.off(cc.Node.EventType.TOUCH_START, this.onItemTouchStart, this);
            item.off(cc.Node.EventType.TOUCH_MOVE, this.onItemTouchMove, this);
            item.off(cc.Node.EventType.TOUCH_END, this.onItemTouchEnd, this);
            item.off(cc.Node.EventType.TOUCH_CANCEL, this.onItemTouchCancel, this);
            pg.event.emit('mouse_05_add')
        } else {
            this.playLocalAudio('error').then(() => {
                this.touching = null;
                // this.updateItem(target, data);
            })
        }
        //判断是否结束了
        // if (Game.getIns().boatLeft.isAllRight() && Game.getIns().boatRight.isAllRight()) {
        //     this.showGameOver();
        // }
    }
    onItemTouchCancel() {

    }

    playLocalAudio(audioName) {
        const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
        return new Promise((resolve, reject) => {
            const id = cc.audioEngine.playEffect(audio.clip, false);
            cc.audioEngine.setFinishCallback(id, () => {
                resolve(id);
            });
        })
    }
}
