import { _decorator, Component, Node, EventTouch, EventHandler } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('OnHolding')
export class OnHolding extends Component {

    @property({ type: [EventHandler] }) public onHoldEvent: EventHandler[] = []; // 配置事件的数组

    private isHolding: boolean = false;
    private holdDuration: number = 0;
    private holdThreshold: number = 0.5; // 长按的阈值时间，单位秒

    start() {
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }

    update(deltaTime: number) {
        if (this.isHolding) {
            this.holdDuration += deltaTime;
            if (this.holdDuration >= this.holdThreshold) {
                this.emitHoldSignal();
                this.isHolding = false; // 触发长按信号后停止计时
            }
        }
    }

    onTouchStart(event: EventTouch) {
        this.isHolding = true;
        this.holdDuration = 0; // 重置计时
    }

    onTouchEnd(event: EventTouch) {
        this.isHolding = false; // 释放时停止计时
        this.holdDuration = 0; // 重置计时
    }

    emitHoldSignal() {
        console.log('节点被长按了！'); // 这里可以替换为实际的信号发出逻辑
        this.node.emit('hold');
    }
}
