import { _decorator, Node, Camera, Rect, UITransform, UIOpacity, view, Component } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('DynamicRefresh')
export class DynamicRefresh extends Component {
	@property({ type: Camera, displayName: "渲染该节点的摄像机", visible: true })
	private _cur_camera: Camera = null;
	@property({ displayName: "裁剪时间间隔(秒)", visible() { return this._cur_camera ? true : false; } })
	private _cut_time = 0.1;
	@property({ displayName: "是否启用层级排序", visible: true })
	private _update_index = false;
	@property({ displayName: "层级排序间隔(秒)", visible() { return this._update_index ? true : false; } })
	private _update_time = 0.1;

	private _design_size = view.getDesignResolutionSize();
	private _cut_time_dt = 0;
	private _update_time_dt = 0;

	protected update(dt: number) {
		//节点排序
		if (this._update_index) {
			++this._update_time_dt;
			if (this._update_time_dt >= this._update_time) {
				let children: Node[] = [];
				for (let child of this.node.children) {
					children.push(child);
				}
				children.sort((a: Node, b: Node) => {
					return b.position.y - a.position.y;
				});
				//如果将设置层级放到和角色是否在可视返回中有可能是角色范围判断错误
				let idx = 0
				for (let child of children) {
					child.setSiblingIndex(++idx);
				}
				this._update_time_dt = 0;
			}
		}

		//摄像机裁剪
		if (this._cur_camera) {
			this._cut_time_dt += dt;
			if (this._cut_time_dt >= this._cut_time) {
				let camera_rect = new Rect(this._cur_camera.node.position.x, this._cur_camera.node.position.y, this._design_size.width, this._design_size.height);
				for (let child of this.node.children) {
					let box = child.getComponent(UITransform).getBoundingBoxToWorld();
					(child.getComponent(UIOpacity) || child.addComponent(UIOpacity)).opacity = ((camera_rect.intersects(box) ? 255 : 0));
				}
				this._cut_time_dt = 0;
			}
		}
	}
}