import { _decorator, assetManager, Button, Component, ImageAsset, Node, PageView, resources, Sprite, SpriteAtlas, SpriteFrame, Toggle } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Help')
export class Help extends Component {
    @property(Node)
    img:any = null;
    pageViewCom:PageView = null;
    totalPages:number = null;
    currentPageIndex:number = null;

    test:number=null;
    protected onLoad(): void {

    }
    start() {
        // this.pageViewCom = this.node.getChildByName("HelpPageView").getComponent(PageView);
        // this.currentPageIndex = this.pageViewCom.getCurrentPageIndex();
        // this.totalPages = this.pageViewCom.getPages().length;
        // this.pageViewCom.node.on(PageView.EventType.PAGE_TURNING,this.onPageTurn,this);
        //this.onScrollPage('HelpPageView');
        const btnHome = this.node.getChildByName("Button");
        btnHome.on(Button.EventType.CLICK,()=>{
            if(this.node.active){
                this.node.active = false;
            }
        },this)
    }

    bottomCurrentIndex(pageViewName:string){
        this.pageViewCom = this.node.getChildByName(pageViewName).getComponent(PageView);
        this.currentPageIndex = this.pageViewCom.getCurrentPageIndex();
        this.loadRes();
        this.pageViewCom.node.on(PageView.EventType.PAGE_TURNING,this.onPageTurn,this);
    }
    onTotalPages(pageViewName:string){
        if(!pageViewName){
            pageViewName = 'HelpPageView';
        }
        const pageViewCom = this.node.getChildByName(pageViewName).getComponent(PageView);
        const totalPagesLength = pageViewCom.getPages().length;
        
        // 加载 SpriteAtlas（图集），并且获取其中的一个 SpriteFrame
        // 注意 atlas 资源文件（plist）通常会和一个同名的图片文件（png）放在一个目录下, 所以需要在第二个参数指定资源类型
        resources.load("Res/number", SpriteAtlas, (err, atlas) => {
            const totalPages = this.node.getChildByPath('Bottom/totalPages');
            const totalPagesSprite = totalPages.getComponent(Sprite);
            const count:number = totalPagesLength + 48;
            const numTotalSprite = count.toString();
            totalPagesSprite.spriteFrame = atlas.getSpriteFrame('font_0' + numTotalSprite);
        });
    }

    onPageTurn(){
        this.currentPageIndex = this.pageViewCom.getCurrentPageIndex(); 
        this.loadRes();
    }
    // onPageTurn() {  
    //     // Load the sprite atlas and update the current index  
    //     this.loadSpriteAtlas("number").then(atlas => {  
    //         const currentIndex = this.node.getChildByPath('Bottom/currentIndex');  
    //         const currentIndexSprite = currentIndex.getComponent(Sprite);  
    //         const countIndex: number = this.currentPageIndex + 49;  
    //         const numIndex = countIndex.toString();  
    //         currentIndexSprite.spriteFrame = atlas.getSpriteFrame('font_0' + numIndex);  
    //     }).catch(err => {  
    //         console.error("Error loading sprite atlas:", err);  
    //     });  
    // }  
    
    //Helper function to load the sprite atlas  
    // loadSpriteAtlas(atlasName: string): Promise<SpriteAtlas> {  
    //     return new Promise((resolve, reject) => {  
    //         resources.load(atlasName, SpriteAtlas, (err: Error, atlas) => {  
    //             if (err) {  
    //                 reject(err);  
    //             } else {  
    //                 resolve(atlas);  
    //             }  
    //         });  
    //     });  
    // }
    loadRes(){
        resources.load("Res/number",SpriteAtlas,(err:Error,atlas)=>{
            const currentIndex = this.node.getChildByPath('Bottom/currentIndex');
            const currentIndexSprite = currentIndex.getComponent(Sprite);
            const countIndex:number = this.currentPageIndex + 49;
            const numIndex = countIndex.toString();
            currentIndexSprite.spriteFrame = atlas.getSpriteFrame('font_0' + numIndex);
        })
    }
    isChecked(){
        const toggleGroup = this.node.getChildByName("ToggleGroup");
        const toggleNames:string[] = ['Help','Monster','Tower'];
        const pageViews:string[] = ['HelpPageView','HelpMonster','TowerPageView'];
        //const nodeToggleGroupChild:Node[] = [];
        
        toggleNames.forEach((name,index)=>{
            const toggle = toggleGroup.getChildByName(name).getComponent(Toggle);
            const pageView = this.node.getChildByName(pageViews[index]);
            pageView.active = toggle.isChecked;
            if(toggle.isChecked && pageView.name != "HelpMonster"){
                this.onTotalPages(pageView.name);
                this.bottomCurrentIndex(pageView.name);
            }
        })

        // for(let i = 0 ; i < arrToggle.length ; i++){
        //     const nodeTG = toggleGroup.getChildByName(arrToggle[i])
        //     nodeToggleGroupChild.push(nodeTG);
        // }
        
        // for(let i = 0; i < nodeToggleGroupChild.length; i++){
        //     //let isActive:boolean = this.node.getChildByName(node[i]).active;
        //     if(nodeToggleGroupChild[i].getComponent(Toggle).isChecked){
        //         this.node.getChildByName(node[i]).active = true;
        //     } else {
        //         this.node.getChildByName(node[i]).active = false;
        //     }
        // }

    //     const help = toggleGroup.getChildByName("Help");
    //     const monster = toggleGroup.getChildByName("Monster");
    //     const tower = toggleGroup.getChildByName("Tower");

    //     if(help.getComponent(Toggle).isChecked === true){
    //         this.node.getChildByName('HelpPageView').active = true;
    //     } else {
    //         this.node.getChildByName('HelpPageView').active = false;
    //     }
    //     if(monster.getComponent(Toggle).isChecked === true){
    //         this.node.getChildByName('Monster').active = true;
    //     } else {
    //         this.node.getChildByName("Monster").active = false;
    //     }
    //     if(tower.getComponent(Toggle).isChecked === true){
    //         this.node.getChildByName('TowerPageView').active = true;
    //     } else {
    //         this.node.getChildByName('TowerPageView').active = false;
    //     }
    }

    isNeedBottom(){
        if(this.node.getChildByName("HelpMonster").active){
            this.node.getChildByName('Bottom').active = false;
        } else {
            this.node.getChildByName('Bottom').active = true;
        }
    }

    update(deltaTime: number) {
        this.isNeedBottom();
        this.isChecked();
        this.currentPageIndex = this.pageViewCom.getCurrentPageIndex();  
    }
}


