import { _decorator, Component, EventMouse, JsonAsset, Layout, math, Node, ScrollView, UITransform } from 'cc';
import { hideToBottom, isBrahmic, updateLang, wrapTextBySpace } from './Tools';
import { getLanguage } from 'db://assets/Loading/scripts/comm';
const { ccclass, property } = _decorator;

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

    @property(JsonAsset)
    langJson: JsonAsset | null = null;

    dict = null
    scrollView: ScrollView = null

    scrollSpeed = 1;

    protected onLoad(): void {
        this.dict = this.langJson.json[getLanguage()] ?? this.langJson.json["en"];

        this.scrollView = this.node.getChildByName("ScrollView").getComponent(ScrollView)

        this.scrollView.node.on('scrolling', this.onScrolling, this);
        this.node.on(Node.EventType.MOUSE_WHEEL, this.onMouseWheel, this);
    }

    start() {
        this.updateLang()

        let lyt = this.scrollView.content.getComponent(Layout)
        lyt.updateLayout();
        lyt.enabled = false;

        this.refreshVisibleZone(this.scrollView.getScrollOffset())
    }

    protected onDisable(): void {
        this.node.off(Node.EventType.MOUSE_WHEEL, this.onMouseWheel, this);
    }

    updateLang() {
        let langText = updateLang(this.node, this.dict, getLanguage())

    }

    clickClosePaytable() {
        const destroyFunc = () => { this.node.destroy() }
        hideToBottom(this.node, destroyFunc)
    }

    // onScrollEnded(scrollView: ScrollView) {
    //     this.refreshVisibleZone(scrollView.getScrollOffset())
    // }

    onScrolling(scrollView: ScrollView) {
        this.refreshVisibleZone(scrollView.getScrollOffset())
    }

    // 只显示上下相邻的区域，远离view 窗口的content内容都隐藏掉
    refreshVisibleZone(offset: math.Vec2) {

        let height = this.scrollView.node.getChildByName("view").getComponent(UITransform).height

        this.scrollView.content.children.forEach(child => {
            let pos = child.position
            if (Math.abs(-offset.y - pos.y) < (height + 300)) {
                child.active = true
            } else {
                child.active = false
            }
        })
    }

    onMouseWheel(event: EventMouse) {

        // console.log("鼠标滚动")

        // deltaY > 0：向下滚；deltaY < 0：向上滚
        const delta = event.getScrollY() * this.scrollSpeed;

        // 获取当前滚动位置
        const offset = this.scrollView.getScrollOffset();

        let vec2 = offset.add2f(0, -delta)
        this.refreshVisibleZone(vec2)
        // 更新纵向滚动
        this.scrollView.scrollToOffset(vec2, 0.1, true);
    }

}

