import { props } from "../props";
import Conveyor from "./Conveyor";
import GarbageConfig from "./datas/GarbageConfig";
import { GarbageTypes } from "./datas/GarbageTypes";
import transStores from "./datas/transStores";
import GameView from "./GameView";
import { getTextureByName, playSound } from "./utils";
import checkHit from "./utils/checkHit";
import removeChild from "./utils/removeChild";
import removeEle from "./utils/removeEle";
import shuffle from "./utils/shuffle";
import { getTargetRect } from "./views/WrongTips";

export default class Conveyors extends engine.Sprite {

    conveyor0: Conveyor;
    conveyor1: Conveyor;

    private conveyorsPool: Conveyor[] = [];

    private GarbageConfig: any[] = GarbageConfig.config;

    private datas: { name, type, isOnStage, width, height, source, isRight }[] = [];

    score: number;
    wrapper: GameView
    stores: any[];

    constructor(p) {
        super();
        this.wrapper = p;
    }

    initData(conveyor0, conveyor1) {
        this.conveyor0 = conveyor0;
        this.conveyor1 = conveyor1;
    }

    private setDefault() {

        this.score = 0;

        this.conveyorsPool.push(this.conveyor0);
        this.conveyorsPool.push(this.conveyor1);

        // 本局游戏的20种垃圾
        const allConfigs = shuffle(this.GarbageConfig.concat([]));

        for (let i = 0; i < GarbageConfig.config.length; i++) {
            allConfigs[i].idx = i;
            allConfigs[i].isRight = false;
            allConfigs[i].isMistake = false;
            allConfigs[i].isOnStage = false;
            this.datas.push(allConfigs[i]);
        }

        for (let i = 0; i < 5; i++) {
            let data = this.datas[i];
            let view: any = new engine.Sprite(getTextureByName(data.source));
            view.isWrong = false;
            view.isRight = false;

            data.isOnStage = true;
            view.data=data;
            view.type = data.type;
            view.name = data.name;
            view.anchorX = data.width / 2;
            view.anchorY = data.height;
            view.x = -data.width / 2;
            view.y = -data.height + 40;
            this.conveyor1[`idx${i}`].addChild(view)
            view.addEventListener(engine.MouseEvent.MOUSE_DOWN, this.onDown_garbage, this);
        }
    }

    startConveyors() {
        this.setDefault();
        engine.gameStage.addEventListener(engine.Event.ENTER_FRAME, this.onEnterFrame, this)

    }
    onEnterFrame(ENTER_FRAME: string, onEnterFrame: any, arg2: this) {
        if (this.score == (props.maxScore || 100)) {
            this.gameOver();
            this.wrapper.stop();
            if (props.sound) playSound("gameOverMp3")
            
        }

        // console.log('this.conveyorsPool.length', this.conveyorsPool.length)

        this.conveyorsPool.forEach(conveyor => {
            conveyor.x -= props.speed || 3;
        });

        // if (this.conveyorsPool.length > 1) {
        if (this.conveyorsPool[this.conveyorsPool.length - 1].x <= 764) {
            // 最后一个传送带完全进入屏幕时  往后添加一个传送带
            const conveyor = new Conveyor();
            conveyor.x = this.conveyorsPool[this.conveyorsPool.length - 1].x + 764;
            this.wrapper.addChild(conveyor);
            this.conveyorsPool.push(conveyor);
        } else {
            //筛选出currGamePool里还未正确和添加在舞台上的
            let dataList = []
            for (var n = 0; n < this.datas.length; n++) {
                let dataItem = this.datas[n];
                if (!dataItem.isRight && !dataItem.isOnStage) {
                    dataList.push(dataItem);
                }
            }
            //最后一个传送带
            let lastConveyor = this.conveyorsPool[this.conveyorsPool.length - 1]
            for (var m = 0; m < 5; m++) {
                if (!lastConveyor[`idx${m}`].children[0]) {
                    let data = dataList.shift();
                    if (data) {
                        data.isOnStage = true;
                        let view: any = new engine.Sprite(getTextureByName(data.source));
                        view.data = data;
                        view.isWrong = false;
                        view.isRight = false;
                        view.type = data.type;
                        view.name = data.name;
                        view.anchorX = data.width / 2;
                        view.anchorY = data.height;
                        view.x = -data.width / 2;
                        view.y = -data.height + 40;
                        lastConveyor[`idx${m}`].addChild(view);
                        view.addEventListener(engine.MouseEvent.MOUSE_DOWN, this.onDown_garbage, this);

                    } else {
                        break
                    }
                }
            }
        }

        // 从场景移除
        if (this.conveyorsPool[0].x < -750) {
            for (var k = 0; k < this.datas.length; k++) {
                let dataItem = this.datas[k]
                let idx4 = this.conveyorsPool[0][`idx${4}`]
                if (idx4.children[0]) {
                    if (dataItem.name == idx4.children[0].name) {
                        dataItem.isOnStage = false;
                        removeEle(dataItem, this.datas);
                        this.datas.push(dataItem);
                        idx4.removeChild(idx4.children[0])
                        break
                    }
                }

            }
            this.conveyorsPool.shift();
        }
        else if (this.conveyorsPool[0].x < -600) {
            for (var k = 0; k < this.datas.length; k++) {
                let dataItem = this.datas[k]
                let idx3 = this.conveyorsPool[0][`idx${3}`]
                if (idx3.children[0]) {
                    if (dataItem.name == idx3.children[0].name) {
                        dataItem.isOnStage = false;
                        removeEle(dataItem, this.datas);
                        this.datas.push(dataItem);
                        idx3.removeChild(idx3.children[0])
                        break
                    }
                }

            }
        }
        else if (this.conveyorsPool[0].x < -450) {
            for (var k = 0; k < this.datas.length; k++) {
                let dataItem = this.datas[k]
                let idx2 = this.conveyorsPool[0][`idx${2}`]
                if (idx2.children[0]) {
                    if (dataItem.name == idx2.children[0].name) {
                        dataItem.isOnStage = false;
                        removeEle(dataItem, this.datas);
                        this.datas.push(dataItem);
                        idx2.removeChild(idx2.children[0])
                        break
                    }
                }

            }
        }
        else if (this.conveyorsPool[0].x < -300) {
            for (var k = 0; k < this.datas.length; k++) {
                let dataItem = this.datas[k]
                let idx1 = this.conveyorsPool[0][`idx${1}`]
                if (idx1.children[0]) {
                    if (dataItem.name == idx1.children[0].name) {
                        dataItem.isOnStage = false;
                        removeEle(dataItem, this.datas);
                        this.datas.push(dataItem);
                        idx1.removeChild(idx1.children[0])
                        break
                    }
                }

            }
        }
        else if (this.conveyorsPool[0].x < -150) {
            for (var k = 0; k < this.datas.length; k++) {
                let dataItem = this.datas[k]
                let idx0 = this.conveyorsPool[0][`idx${0}`]
                if (idx0.children[0]) {
                    if (dataItem.name == idx0.children[0].name) {
                        dataItem.isOnStage = false;
                        removeEle(dataItem, this.datas);
                        this.datas.push(dataItem);
                        idx0.removeChild(idx0.children[0])
                        break
                    }
                }

            }
        }

        // }
    }

    addscore() {
        this.score += (props.onceScore || 2);
        engine.globalEvent.dispatchEvent('recycling-score-update', {
            score: this.score
        });
    }

    gameOver() {
        engine.gameStage.removeEventListener(engine.Event.ENTER_FRAME, this.onEnterFrame, this);
        engine.globalEvent.dispatchEvent('recycling-game-end', transStores(this.stores));
    }

    private _currentDragView: engine.Sprite;
    private _currentTarget;
    onDown_garbage(e: engine.MouseEvent) {
        if (this._currentDragView) {
            removeChild(this._currentDragView)
        }
        const target: engine.Sprite = e.target;
        let view: any = new engine.Sprite(target.texture);
        this._currentDragView = view;
        this._currentTarget = target;
        target.scaleX = target.scaleY = 0;
        this.wrapper.addChild(view);
        view.x = e.stageX - target.texture.width / 2;
        view.y = e.stageY - target.texture.height / 2;
        view.type = target['type'];
        view.name = target['name'];
        this.wrapper.addEventListener(engine.MouseEvent.MOUSE_UP, this.onStageMouseUp, this)
        this.wrapper.addEventListener(engine.MouseEvent.MOUSE_MOVE, this.onStageMouseMove, this)
    }

    onStageMouseMove(e: engine.MouseEvent) {
        // console.log('onStageMouseMove')
        const view = this._currentDragView;
        view.x = e.stageX - view.texture.width / 2;
        view.y = e.stageY - view.texture.height / 2;
    }

    onStageMouseUp(e: engine.MouseEvent) {
        // console.log('onStageMouseUp')
        this.wrapper.removeEventListener(engine.MouseEvent.MOUSE_UP, this.onStageMouseUp, this)
        this.wrapper.removeEventListener(engine.MouseEvent.MOUSE_MOVE, this.onStageMouseMove, this)
        if (!this._currentDragView) return;
        const result: GarbageTypes = this.checkHitRect();
        if (result) {//落入
            if (result == this._currentDragView['type']) {//匹配
                this.addscore();
                this.wrapper.rightTips.play(getTargetRect(result,this.wrapper));
                this._currentTarget.data.isRight=true;
            } else {//不匹配
                engine.Tween.get(this._currentTarget).to({ scaleX: 1, scaleY: 1 }, 300).call(() => { });
                this.wrapper.wrongTips.play(getTargetRect(result,this.wrapper));
            }
            this.stores.push({ targetType: result, itemType: this._currentDragView['type'], itemName: this._currentDragView['name'] });

        } else { //没有落入
            engine.Tween.get(this._currentTarget).to({ scaleX: 1, scaleY: 1 }, 300).call(() => { });
        }
        this._currentDragView.anchorX = this._currentDragView.texture.width / 2;
        this._currentDragView.anchorY = this._currentDragView.texture.height / 2;
        engine.Tween.get(this._currentDragView).to({ scaleX: 0, scaleY: 0 }, 300).call(() => {
            removeChild(this._currentDragView);

            // this._currentDragView = null;
            // this._currentTarget = null;
        });
    }

    clear() {
        this.conveyor0.x = 0;
        this.conveyor1.x = 764;
        this.conveyorsPool.forEach(i => {
            i.clear();
        });
        this.conveyorsPool = [];
        this.datas = [];
        this.stores = [];
    }

    timeout() {
        if (this._currentDragView) {
            removeChild(this._currentDragView)
        }
        this.wrapper.removeEventListener(engine.MouseEvent.MOUSE_UP, this.onStageMouseUp, this)
        this.wrapper.removeEventListener(engine.MouseEvent.MOUSE_MOVE, this.onStageMouseMove, this)
        this.gameOver();
    }

    checkHitRect() {
        if (checkHit(this._currentDragView, this.wrapper.wetWaste)) {
            return GarbageTypes.wetWaste
        }
        if (checkHit(this._currentDragView, this.wrapper.harmfulWaste)) {
            return GarbageTypes.harmfulWaste
        }
        if (checkHit(this._currentDragView, this.wrapper.dryWaste)) {
            return GarbageTypes.dryWaste
        }
        if (checkHit(this._currentDragView, this.wrapper.recoverableWaste)) {
            return GarbageTypes.recoverableWaste
        }
        return null;
    }
}