import { Component, _decorator, Node, EventTouch, systemEvent, input, Input, geometry, Camera, PhysicsSystem, director, v3 } 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";

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”
        if (PhysicsSystem.instance.raycast(this._ray)) {
            const r = PhysicsSystem.instance.raycastResults;
            for (let index = 0; index < r.length; index++) {
                const element = r[index];

                if (element.collider.node.uuid == this.node?.uuid) {
                    console.log('当前点击： ' + element.collider.node.uuid);
                    console.log('是否可达：', this.puppet.PathFind?.canReach)
                    if (this.puppet.PathFind?.canReach&& !this.puppet.get(MoveToPathComp)) {
                        const moveToPath = this.puppet.add(MoveToPathComp)
                        moveToPath.speed = 1
                        moveToPath.paths = this.puppet.PathFind.path.concat([v3(-1, 0, -3)])
                        moveToPath.node = this.node
                        moveToPath.ns = Node.NodeSpace.WORLD
                        moveToPath.onComplete = () => {
                            console.log('移动完成')
                        }
                        const pathGrid = smc.initialize.account.checkpoint.CheckpointModel.path_grid
                        pathGrid[this.puppet.PuppetModel.x][this.puppet.PuppetModel.y].fill = null
                        this.puppet.remove(PathFindComp)
                        console.log('我开始动了')
                    }
                }
            }
        }
    }

}