import { _decorator, BoxCollider2D, Collider2D, Color, Component, Contact2DType, director, Director, EventTouch, instantiate, IPhysics2DContact, Label, log, Node, Prefab, Rect, Sprite, SpriteFrame, Tween, UITransform, Vec2, Vec3 } from 'cc';
import { tools } from '../tools';
import { DirType, model_item_data } from '../data';
import { run_level_item } from './run_level_item';
import { car } from './car';
import Coroutine from '../lib/Coroutine';
import { results } from './results';
import { buff_show } from './buff_show';
import { pool } from './pool';
import { box } from './box';
import { Util } from '../util';
import { wall } from './wall';
import { Joystick } from './joystick';
import { touch } from './touch';
import { config } from '../config';
import { coin } from './coin';
import { audioManager } from '../manager/audioManager';
import { count_time_start } from './count_time_start';
import { weiqi_manager } from './effect/weiqi_manager';
import { cheyin_manager } from './cheyin/cheyin_manager';
import { boom_manager } from './boom/boom_manager';
import { qiyou_manager } from './qiyou_manager';
import { GameManager } from '../GameManager';
const { ccclass, property } = _decorator;

@ccclass('game')
export class game extends Component {
    @property(SpriteFrame) sfList:SpriteFrame[] = [];
    @property(SpriteFrame) sfBuffList:SpriteFrame[] = [];
    @property(Node) collider:Node = null;
    @property(Node) car:Node = null;
    @property(Node) content:Node = null;
    @property(Prefab) prefab_item:Prefab = null;
    @property(Node) results_view:Node = null;
    @property(Node) lab_scores:Node = null;
    @property(buff_show) bf_show:buff_show = null
    @property(pool) game_pool_manager:pool = null
    @property(Node) touch_node:Node = null
    @property(Node) count_time:Node = null
    @property(weiqi_manager) mWeiqiManager:weiqi_manager = null
    @property(cheyin_manager) mCheyinManager:cheyin_manager = null
    @property(boom_manager) mBoomManager:boom_manager = null
    @property(qiyou_manager) mQiYouManager:qiyou_manager = null
    private mCallBackHome = null
    private mIndex:number = 0;
    private mHeight:number = 0;
    private move_pos:Vec3 = Vec3.ZERO;
    public offsetX:number = 0;
    private gameBoxList:Node[] = []
    private gameWallList:Node[] = []
    private gameCoinList:Node[] = []
    private isFristOverGame:boolean = true
    public show(cb,isReLife:boolean = false){
        this.mCallBackHome = cb
        this.removeAll()
        audioManager.Instance().playMusic(config.AUDIO.game_bgm)
        this.count_time.active = true
        this.count_time.getComponent(count_time_start).startGame(3,()=>{
            this.car.getComponent(car).startGame()
        })
        this.gameBoxList = []
        this.gameWallList = []
        this.gameCoinList = []
        this.mHeight = 0
        this.game_pool_manager.init()
        this.bf_show.initView()
        this.content.position = Vec3.ZERO
        this.car.position = new Vec3(0,-300,this.car.position.z)
        this.car.getComponent(car).init(this.content,this.onOver.bind(this),this.updateScores.bind(this),this,isReLife)
        for (let index = 0; index < 3; index++) {
            this.addItem(index)
        }
        this.mBoomManager.init(this.car.getComponent(car))
        this.mWeiqiManager.init(this.car.getComponent(car))
        this.mQiYouManager.init(this.car.getComponent(car))
        this.mWeiqiManager.startEffect()
        this.mCheyinManager.init(this.car.getComponent(car))
        this.touch_node.getComponent(touch).init(this.car.getComponent(car))
        this.mIndex = 2;
        this.schedule(()=>{
            if(this.node.active){
                if(this.content.children.length<=6){
                    this.mIndex++;
                    if(this.mIndex>=tools.levels.length){
                        this.mIndex = 1;
                    }
                    // Coroutine.instance.start(this, this.addItem, 0, 60, this.mIndex);
                    this.addItem(this.mIndex)
                }
            }
        },0.25)
        // this.collider.off(Contact2DType.END_CONTACT)
        // this.collider.on(Contact2DType.END_CONTACT,(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null)=>{
        //     if(otherCollider.node.name.endsWith("run_level_item")){
        //         this.deleteItem(otherCollider.node)
        //     }
        // },this)

        GameManager.gameStart()
    }

    public isOut(pos:Vec3){
        if(pos.y<this.collider.position.y){
            return true
        }
        return false
    }

    public showBoom(box_p:Vec3){
        this.mBoomManager.showBoom(box_p)
    }

    public showQiYouEffect(qiyou_p:Vec3){
        this.mQiYouManager.showQiYou(qiyou_p)
    }
    public getPoolManager(){
        return this.game_pool_manager
    }

    public getBuffShowView(){
        return this.bf_show
    }

    getOldDir(){
        return this.move_pos
    }

    updateScores(scores:number){
        this.lab_scores.getComponent(Label).string = scores.toString()
    }

    onOver(){
        this.unscheduleAllCallbacks()
        this.count_time.active = false
        this.car.getComponent(car).hideEffect()
        director.once(Director.EVENT_AFTER_DRAW,()=>{
            this.removeAll()
            this.results_view.getComponent(results).show(this.car.getComponent(car).getScores(),(()=>{
            }), (isReLife:boolean=false)=>{
                this.show(this.mCallBackHome,isReLife)
            },()=>{
                this.removeSelf()
                this.mCallBackHome()
            },!this.car.getComponent(car).getIsReLife())
        })
        GameManager.gameOver()
    }

    removeSelf(){
        this.node.removeFromParent()
    }

    removeAll(){
        let temp_list = []
        for (let index = 0; index < this.content.children.length; index++) {
            const element = this.content.children[index];
            if(element.name!="car"&&element.name!="weiqi"){
                temp_list.push(element)
            }
        }
        for (let index = 0; index < temp_list.length; index++) {
            const element = temp_list[index];
            element.removeFromParent()
        }

    }
    deleteItem(node:Node){
        director.once(Director.EVENT_AFTER_DRAW,()=>{
            let index = this.content.children.indexOf(node)
            if(index!=-1){
                this.content.children[index].getComponent(run_level_item).removeAll()
            }
        })
    }
    addItem( index:number){
        // yield Coroutine.createWaitForSecond(waitSecond);
        let l:string[] = tools.levels[index].split(",")
        let randomID = this.getRandomInt(0,l.length-1)

        let item = instantiate(this.prefab_item)
        item.parent = this.content
        let id = parseInt(l[randomID])
        // console.log("randomID",id,tools.levels[index],index)
        let m_d:model_item_data = this.getModelDataById(id)
        if(m_d==null){
            console.error("m_d==null",id)
            return 
         }
        item.position = new Vec3(0,this.mHeight)
        this.mHeight+=m_d.height
        this.car.setSiblingIndex(this.content.children.length)
        item.getComponent(run_level_item).initView(m_d,this.sfList,this.sfBuffList,this.car.getComponent(car))
    }

    getRandomInt (min: number, max: number) {
        let r: number= Math.random();
        let rr: number= r * (max - min + 1) + min;
        return Math.floor(rr);
    }

    getModelDataById(id:number){
        for (let index = 0; index < tools.tpl_list.length; index++) {
            const element = tools.tpl_list[index];
            if(element.id===id){
                return element
            }
        }
        return null
    }

    addCoinForList(node:Node){
        this.gameCoinList.push(node)
    }

    removeCoinForList(node:Node){
        let index = this.gameCoinList.indexOf(node)
        if(index!=-1){
            this.gameCoinList.splice(index,1)
        }
    }

    addBoxForList(node:Node){
        this.gameBoxList.push(node)
    }

    removeBoxForList(node:Node){
        let index = this.gameBoxList.indexOf(node)
        if(index!=-1){
            this.gameBoxList.splice(index,1)
        }
    }

    addWallForList(node:Node){
        this.gameWallList.push(node)
    }

    removeWallForList(node:Node){
       let index = this.gameWallList.indexOf(node)
       if(index!=-1){
            this.gameWallList.splice(index,1)
       }
    }
    move(){
        // let info = this.joystick.getJoyInfo()
        // if(info!=null){
        //     this.car.getComponent(car).setDir(info.dir)
        //     this.car.getComponent(car).setDis(info.dis)
        // }
    }

    carCollider(car_rect:Rect){
        let list = []
        let origin_car_pos = this.car.position
        let origin_car_pos_y = origin_car_pos.y+car_rect.height*0.5
        let isColliderBox = false
        for (let index = 0; index < this.gameBoxList.length; index++) {
            const box_node = this.gameBoxList[index];
            let isCanCollider = box_node.getComponent(box).getIsCanCollider()
            if(box_node.parent&&isCanCollider){
                let box_world = box_node.parent.getComponent(UITransform).convertToWorldSpaceAR(box_node.position)
                let p = this.content.getComponent(UITransform).convertToNodeSpaceAR(box_world)
                let width = box_node.getComponent(box).getData().w
                let height = box_node.getComponent(box).getData().h
                let rect = new Rect(p.x-width*0.5,p.y-height*0.5,width,height)
                let dir = -1
                if(car_rect.intersects(rect)){
                    isColliderBox = true
                    // let car_top_rect = new Rect(car_rect.xMin,car_rect.yMax-10,car_rect.width,20)
                    let box_bottom_rect = new Rect(rect.xMin,rect.yMin,rect.width,20)
                    if(origin_car_pos_y<=box_bottom_rect.yMin){
                        // if((car_top_rect.yMin-origin_car_pos_y)>20){

                        // }
                        dir = config.collider_dir.top
                      
                    }
                    // if(car_top_rect.intersects(box_bottom_rect)){
                    //     dir = config.collider_dir.top
                    // }
                    list.push({"node":box_node,"rect":rect,"type":0,"collider_dir":dir,"moveOffset":0})
                }
            }
        }
        let car_top_rect = new Rect(car_rect.xMin,car_rect.yMax-5,car_rect.width,10)
        for (let index = 0; index < this.gameWallList.length; index++) {
            const box_node = this.gameWallList[index];
            let isCanCollider = box_node.getComponent(wall).getIsCanCollider()
            if(box_node.parent&&isCanCollider){
                let box_world = box_node.parent.getComponent(UITransform).convertToWorldSpaceAR(box_node.position)
                let p = this.content.getComponent(UITransform).convertToNodeSpaceAR(box_world)
                let width = box_node.getComponent(wall).getData().w
                let height = box_node.getComponent(wall).getData().h
                let rect = new Rect(p.x-width*0.5,p.y-height*0.5,width,height)
                let dir = -1
                let offset = 0
                if(car_rect.intersects(rect)){
                    let box_bottom_rect = new Rect(rect.xMin,rect.yMin,rect.width,10)
                    // if(car_top_rect.intersects(box_bottom_rect)){
                    //     dir = config.collider_dir.top
                    //         if(box_bottom_rect.xMax>(car_top_rect.xMin+car_top_rect.width*0.5)){ //右边
                    //             offset = (car_top_rect.width*0.5)
                    //         }else{
                    //             offset = (car_top_rect.width*-0.5)
                    //         }
                  
                    // }
                    if(origin_car_pos_y<=box_bottom_rect.yMin){
                            dir = config.collider_dir.top
                            if(box_bottom_rect.xMax>(car_top_rect.xMin+car_top_rect.width*0.5)){ //右边
                                offset = (car_top_rect.width*0.5)
                            }else{
                                offset = (car_top_rect.width*-0.5)
                            }
                    }
                    list.push({"node":box_node,"rect":rect,"type":1,"collider_dir":dir,"moveOffset":offset})
                }
            }
        }

        for (let index = 0; index < this.gameCoinList.length; index++) {
            const box_node = this.gameCoinList[index];
            let isCanCollider = box_node.getComponent(coin).getIsCanCollider()
            if(box_node.parent&&isCanCollider){
                let box_world = box_node.parent.getComponent(UITransform).convertToWorldSpaceAR(box_node.position)
                let p = this.content.getComponent(UITransform).convertToNodeSpaceAR(box_world)
                let width = box_node.getComponent(coin).getData().w
                let height = box_node.getComponent(coin).getData().h
                let rect = new Rect(p.x-width*0.5,p.y-height*0.5,width,height)
                let dir = -1
                let offset = 0
                if(car_rect.intersects(rect)){
                    list.push({"node":box_node,"rect":rect,"type":2,"collider_dir":dir,"moveOffset":offset})
                }
            }
        }
        return list
    }


    getLeftObstacles(car_rect:Rect){
        let list:number[] = []
        for (let index = 0; index < this.gameBoxList.length; index++) {
            const box_node = this.gameBoxList[index];
            let isCanCollider = box_node.getComponent(box).getIsCanCollider()
            if(box_node.parent&&isCanCollider){
                let box_world = box_node.parent.getComponent(UITransform).convertToWorldSpaceAR(box_node.position)
                let p = this.content.getComponent(UITransform).convertToNodeSpaceAR(box_world)
                let width = box_node.getComponent(box).getData().w
                let height = box_node.getComponent(box).getData().h
                let rect = new Rect(p.x-width*0.5,p.y-height*0.5,width,height)
                if(car_rect.xMin>=rect.xMax){
                    if(new Rect(rect.x,car_rect.y,car_rect.width,car_rect.height).intersects(rect)){
                        list.push(rect.xMax+car_rect.width*0.5)
                        // box_node.active = false
                    }
                }
             
            }
        }


        for (let index = 0; index < this.gameWallList.length; index++) {
            const box_node = this.gameWallList[index];
            let isCanCollider = box_node.getComponent(wall).getIsCanCollider()
            if(box_node.parent&&isCanCollider){
                let box_world = box_node.parent.getComponent(UITransform).convertToWorldSpaceAR(box_node.position)
                let p = this.content.getComponent(UITransform).convertToNodeSpaceAR(box_world)
                let width = box_node.getComponent(wall).getData().w
                let height = box_node.getComponent(wall).getData().h
                let rect = new Rect(p.x-width*0.5,p.y-height*0.5,width,height)
                if(car_rect.xMin>=rect.xMax){
                    if(new Rect(rect.x,car_rect.y,car_rect.width,car_rect.height).intersects(rect)){
                        list.push(rect.xMax+car_rect.width*0.5)
                        // box_node.active = false
                    }
                }
             
            }
        }
        if(list.length<=0){
            return null
        }
        list.sort((a,b)=>{
            return b-a
        })
        // console.log("list",list)
        return list[0]
    }

    getRightObstacles(car_rect:Rect){
        let list:number[] = []
        for (let index = 0; index < this.gameBoxList.length; index++) {
            const box_node = this.gameBoxList[index];
            if(box_node.parent){
                let box_world = box_node.parent.getComponent(UITransform).convertToWorldSpaceAR(box_node.position)
                let p = this.content.getComponent(UITransform).convertToNodeSpaceAR(box_world)
                let width = box_node.getComponent(box).getData().w
                let height = box_node.getComponent(box).getData().h
                let rect = new Rect(p.x-width*0.5,p.y-height*0.5,width,height)
                if(car_rect.xMax<=rect.xMin){
                    if(new Rect(rect.x,car_rect.y,car_rect.width,car_rect.height).intersects(rect)){
                        list.push(rect.xMin-car_rect.width*0.5)
                    }
                }
             
            }
        }


        for (let index = 0; index < this.gameWallList.length; index++) {
            const box_node = this.gameWallList[index];
            if(box_node.parent){
                let box_world = box_node.parent.getComponent(UITransform).convertToWorldSpaceAR(box_node.position)
                let p = this.content.getComponent(UITransform).convertToNodeSpaceAR(box_world)
                let width = box_node.getComponent(wall).getData().w
                let height = box_node.getComponent(wall).getData().h
                let rect = new Rect(p.x-width*0.5,p.y-height*0.5,width,height)
                if(car_rect.xMax<=rect.xMin){
                    if(new Rect(rect.x,car_rect.y,car_rect.width,car_rect.height).intersects(rect)){
                        list.push(rect.xMin-car_rect.width*0.5)
                        //    box_node.active = false
                    }
                }
             
            }
        }
        if(list.length<=0){
            return null
        }
        list.sort((a,b)=>{
            return a-b
        })
        return list[0]
    }
    changeMovePos(){
   
    }

}


