import { Component, _decorator, Node, EventTouch, systemEvent, input, Input, geometry, Camera, PhysicsSystem, director, v3, Vec3 } from "cc";
import { Puppet } from "../puppet";
import { oops } from "../../../../../extensions/oops-plugin-framework/assets/core/Oops";
import { MoveToPathComp } from "../../common/ecs/path/MoveToPath";
import { PathFindComp } from "../../common/ecs/path/PathFind";
import { smc } from "../../common/SingletonModuleComp";
import { CheckpointCheckFailComp } from "../../checkpoint/bll/CheckpointCheck";
import { VibrationManager } from "../../../platform/vibration/VibrationManager";
import { UIID } from "../../common/config/GameUIConfig";
import { CheckpointPathTriggerComp } from "../../checkpoint/bll/CheckpointPathTrigger";

const { ccclass, property } = _decorator;

/** 角色资源加载 */
@ccclass('PuppetViewController')
export class PuppetViewController extends Component {
    /** 角色对象 */
    puppet: Puppet = null!;

    @property({ type: Camera, tooltip: '主相机' })
    public mainCamera: Camera | null = null;

    // @property({ type: Node, tooltip: '待触摸物体' })
    // public node_touch_1: Node | null = null;

    private _ray: geometry.Ray = new geometry.Ray();

    onLoad() {
        // const cameras = director.getScene().getComponentsInChildren(Camera);
        // this.mainCamera = cameras.find(camera => camera.node.name === 'MainCamera');
        // input.on(Input.EventType.TOUCH_END, this.onTouchStart, this);
    }

    onDestory() {
        // input.off(Input.EventType.TOUCH_END, this.onTouchStart, this);
    }

    onTouchStart(event: EventTouch) {
        // 基于摄像机 画射线
        this.mainCamera?.screenPointToRay(event.getLocation().x, event.getLocation().y, this._ray);
        // 基于物理碰撞器的射线检测
        // 当点击 node_touch_1 时，控制台打印 “node_touch_1”
        // console.log('this.puppet.PuppetModel.x:',this.puppet.PuppetModel.x)
        // console.log('this.puppet.PuppetModel.y',this.puppet.PuppetModel.y)
        if (PhysicsSystem.instance.raycast(this._ray)) {
            const r = PhysicsSystem.instance.raycastResults;
            for (let index = 0; index < r.length; index++) {
                const element = r[0];
                console.log(this.node?.uuid)
                if (element.collider.node.uuid == this.node?.uuid) {
                    oops.audio.playEffect("common/audio/click");
                    console.log('当前点击： ' + element.collider.node.uuid);
                    console.log('是否可达：', this.puppet.PathFind?.canReach)
                    if (this.puppet?.PathFind?.canReach && !this.puppet.get(MoveToPathComp)) {
                        VibrationManager.getInstance().vibrateShort()
                        const checkpoint = smc.initialize.account.checkpoint
                        let end = v3(0, 0, 0)
                        if (checkpoint.CheckpointModel.curVehicle.VehicleModel.color === this.puppet.PuppetModel.color && !checkpoint.CheckpointModel.curVehicle.VehicleModel.isFull) {
                            // end = v3(0, 0, 0)
                            this.puppet.PuppetView.animator.onRunPathComplete = () => {
                                checkpoint.CheckpointModel.curVehicle.VehicleView.createPuppet()
                                checkpoint.removeChild(this.puppet)
                                this.puppet.destroy()
                                checkpoint.CheckpointModel.peopleCount-=1
                            }
                            checkpoint.CheckpointModel.curVehicle.VehicleModel.useSit += 1
                            
                        } else if (checkpoint.CheckpointModel.emptyStation) {
                            if (checkpoint.CheckpointModel.emptyStationCount <= 1) {
                                console.log('游戏结束')
                                oops.gui.open(UIID.Recovery)
                                // checkpoint.add(CheckpointCheckFailComp)
                            }
                            end = checkpoint.CheckpointModel.emptyStation.StationView.node.position.clone()
                            checkpoint.CheckpointModel.emptyStation.StationModel.puppet = this.puppet

                        } else {
                            console.log('游戏结束')
                            return
                        }

                        this.puppet.PuppetView.animator.moveToPath(end)
                        // const moveToPath = this.puppet.add(MoveToPathComp)
                        // moveToPath.speed = 2
                        // moveToPath.paths = this.puppet.PathFind.path.concat([end])
                        // moveToPath.node = this.node
                        // moveToPath.ns = Node.NodeSpace.WORLD
                        // const forwardClone = this.puppet.PuppetView.node.forward.clone()
                        // moveToPath.onComplete = () => {
                        //     console.log('移动完成')
                        //     this.puppet.PuppetView.ske.play('idle')
                        //     this.puppet.PuppetView.node.forward = forwardClone
                        //     needDestory&&this.puppet.destroy()
                        // }
                        // this.puppet.PuppetView.ske.play('run')
                        // checkpoint.CheckpointModel.emptyStation
                        const pathGrid = checkpoint.CheckpointModel.path_grid
                        pathGrid[this.puppet.PuppetModel.x][this.puppet.PuppetModel.y].fill = null
                        const cell = checkpoint.CheckpointModel.cells
                        cell[this.puppet.PuppetModel.x][this.puppet.PuppetModel.y] = null
                        this.puppet.remove(PathFindComp)
                        // console.log('我开始动了')
                        oops.audio.playEffect("common/audio/move");
                    }else{
                        VibrationManager.getInstance().vibrateLong()
                    }
                }
                break
            }
        }
    }

    onPuppetClick(){
        oops.audio.playEffect("common/audio/click");
        // console.log('当前点击： ' + element.collider.node.uuid);
        // console.log('是否可达：', this.puppet.PathFind?.canReach)
        if (this.puppet?.PathFind?.canReach && !this.puppet.get(MoveToPathComp)) {
            VibrationManager.getInstance().vibrateShort()
            const checkpoint = smc.initialize.account.checkpoint
            let end = v3(0, 0, 0)
            if (checkpoint.CheckpointModel.curVehicle.VehicleModel.color === this.puppet.PuppetModel.color && !checkpoint.CheckpointModel.curVehicle.VehicleModel.isFull) {
                // end = v3(0, 0, 0)
                this.puppet.PuppetView.animator.onRunPathComplete = () => {
                    checkpoint.CheckpointModel.curVehicle.VehicleView.createPuppet()
                    checkpoint.removeChild(this.puppet)
                    this.puppet.destroy()
                    checkpoint.CheckpointModel.peopleCount-=1
                }
                checkpoint.CheckpointModel.curVehicle.VehicleModel.useSit += 1
                
            } else if (checkpoint.CheckpointModel.emptyStation) {
                if (checkpoint.CheckpointModel.emptyStationCount <= 1) {
                    console.log('游戏结束')
                    oops.gui.open(UIID.Recovery)
                    // checkpoint.add(CheckpointCheckFailComp)
                }
                end = checkpoint.CheckpointModel.emptyStation.StationView.node.position.clone()
                checkpoint.CheckpointModel.emptyStation.StationModel.puppet = this.puppet

            } else {
                console.log('游戏结束')
                return
            }

            this.puppet.PuppetView.animator.moveToPath(end)
            // const moveToPath = this.puppet.add(MoveToPathComp)
            // moveToPath.speed = 2
            // moveToPath.paths = this.puppet.PathFind.path.concat([end])
            // moveToPath.node = this.node
            // moveToPath.ns = Node.NodeSpace.WORLD
            // const forwardClone = this.puppet.PuppetView.node.forward.clone()
            // moveToPath.onComplete = () => {
            //     console.log('移动完成')
            //     this.puppet.PuppetView.ske.play('idle')
            //     this.puppet.PuppetView.node.forward = forwardClone
            //     needDestory&&this.puppet.destroy()
            // }
            // this.puppet.PuppetView.ske.play('run')
            // checkpoint.CheckpointModel.emptyStation
            const pathGrid = checkpoint.CheckpointModel.path_grid
            pathGrid[this.puppet.PuppetModel.x][this.puppet.PuppetModel.y].fill = null
            const cell = checkpoint.CheckpointModel.cells
            cell[this.puppet.PuppetModel.x][this.puppet.PuppetModel.y] = null
            this.puppet.remove(PathFindComp)
            checkpoint.add(CheckpointPathTriggerComp)
            // console.log('我开始动了')
            oops.audio.playEffect("common/audio/move");
        }else{
            VibrationManager.getInstance().vibrateLong()
        }
    }

}