// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;
import middleLayer from "../../script/middleLayer_testzg001";
import GameCard from "./gamecard_testzg001";

interface GameData {
    id: number;
    uuid: string;
    template_name: string;
    template_description: string;
    cover: string;
    cw_cover?: string;
    data: string;
    seq: number;
}

@ccclass
export default class GameCenter extends cc.Component {
    @property(cc.Node)
    gameListContainer: cc.Node = null;

    @property(cc.Prefab)
    gameCardPrefab: cc.Prefab = null;

    @property(cc.ScrollView)
    scrollView: cc.ScrollView = null;

    // 进度条相关属性
    @property(cc.Node)
    progressBarContainer: cc.Node = null;

    @property(cc.ProgressBar)
    progressBar: cc.ProgressBar = null;

    @property(cc.Label)
    progressLabel: cc.Label = null;

    private gameDataList: GameData[] = [];

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        // 初始化组件引用
        this.initComponents();

        // 获取屏幕宽度
    }

    start() {
        this.getGameList();

        let screen_size = cc.view.getFrameSize().width / cc.view.getFrameSize().height
        let design_size = cc.Canvas.instance.designResolution.width / cc.Canvas.instance.designResolution.height
        let f = screen_size >= design_size
        cc.Canvas.instance.fitHeight = f
        cc.Canvas.instance.fitWidth = !f
    
        const frameSize = cc.view.getFrameSize();
        // this._frameSize = frameSize;
    
        const designSize = cc.view.getDesignResolutionSize();
    
        let sx = cc.winSize.width / frameSize.width;
        let sy = cc.winSize.height / frameSize.height;
        // const cocosScale = Math.min(sx, sy);
    
        sx = frameSize.width / designSize.width;
        sy = frameSize.height / designSize.height;
        // this._mapScaleMin = Math.min(sx, sy) * cocosScale;
        // this._mapScaleMax = Math.max(sx, sy) * cocosScale;
    
        cc.director['_scene'].width = frameSize.width;
        cc.director['_scene'].height = frameSize.height;
    }

    private initComponents() {
        console.log('=== 初始化组件开始 ===');
        
        // 获取游戏列表容器
        if (!this.gameListContainer) {
            this.gameListContainer = this.node.getChildByName('game_list_container');
            console.log('gameListContainer:', this.gameListContainer);
        }
        
        // 获取滚动视图
        if (!this.scrollView) {
            const scrollViewNode = this.node.getChildByName('game_list_container')?.getChildByName('scroll_view');
            console.log('scrollViewNode:', scrollViewNode);
            
            if (scrollViewNode) {
                this.scrollView = scrollViewNode.getComponent(cc.ScrollView);
                console.log('scrollView组件:', this.scrollView);
            } else {
                console.error('找不到scroll_view节点');
            }
        }

        // 初始化进度条组件
        this.initProgressBar();
        
        console.log('=== 初始化组件完成 ===');
        console.log('gameListContainer:', this.gameListContainer);
        console.log('scrollView:', this.scrollView);
    }

    private initProgressBar() {
        // 如果没有通过属性面板设置，则通过代码查找
        if (!this.progressBarContainer) {
            this.progressBarContainer = this.node.getChildByName('progress_bar_container');
        }
        
        if (!this.progressBar) {
            const progressBarNode = this.progressBarContainer?.getChildByName('progress_bar');
            if (progressBarNode) {
                this.progressBar = progressBarNode.getComponent(cc.ProgressBar);
            }
        }
        
        if (!this.progressLabel) {
            const progressLabelNode = this.progressBarContainer?.getChildByName('progress_label');
            if (progressLabelNode) {
                this.progressLabel = progressLabelNode.getComponent(cc.Label);
            }
        }

        // 如果进度条容器不存在，则创建一个
        if (!this.progressBarContainer) {
            this.createProgressBar();
        }

        // 初始时隐藏进度条
        this.hideProgressBar();
    }

    private createProgressBar() {
        // 创建进度条容器
        this.progressBarContainer = new cc.Node('progress_bar_container');
        this.node.addChild(this.progressBarContainer);
        
        // 设置进度条容器位置和大小
        this.progressBarContainer.setPosition(0, 0);
        this.progressBarContainer.width = 400;
        this.progressBarContainer.height = 120;
        
        // 创建背景遮罩
        const bgMask = new cc.Node('bg_mask');
        this.progressBarContainer.addChild(bgMask);
        const bgSprite = bgMask.addComponent(cc.Sprite);
        bgMask.color = cc.Color.BLACK;
        bgMask.opacity = 150;
        bgMask.width = 400;
        bgMask.height = 120;
        
        // 创建加载提示文本
        const loadingLabel = new cc.Node('loading_label');
        this.progressBarContainer.addChild(loadingLabel);
        const loadingLabelComp = loadingLabel.addComponent(cc.Label);
        loadingLabelComp.string = '正在加载游戏资源...';
        loadingLabelComp.fontSize = 18;
        loadingLabelComp.node.color = cc.Color.WHITE;
        loadingLabel.setPosition(0, 40);
        
        // 创建进度条背景
        const progressBg = new cc.Node('progress_bg');
        this.progressBarContainer.addChild(progressBg);
        const progressBgSprite = progressBg.addComponent(cc.Sprite);
        progressBg.color = cc.Color.GRAY;
        progressBg.width = 300;
        progressBg.height = 20;
        progressBg.setPosition(0, 0);
        
        // 创建进度条
        const progressBarNode = new cc.Node('progress_bar');
        this.progressBarContainer.addChild(progressBarNode);
        this.progressBar = progressBarNode.addComponent(cc.ProgressBar);
        progressBarNode.color = cc.Color.BLUE;
        progressBarNode.width = 300;
        progressBarNode.height = 20;
        progressBarNode.setPosition(0, 0);
        
        // 设置进度条属性
        this.progressBar.progress = 0;
        this.progressBar.barSprite = progressBarNode.getComponent(cc.Sprite);
        
        // 创建进度文本
        const progressLabelNode = new cc.Node('progress_label');
        this.progressBarContainer.addChild(progressLabelNode);
        this.progressLabel = progressLabelNode.addComponent(cc.Label);
        this.progressLabel.string = '0%';
        this.progressLabel.fontSize = 16;
        this.progressLabel.node.color = cc.Color.WHITE;
        progressLabelNode.setPosition(0, -30);
        
        console.log('进度条组件创建完成');
    }

    // 显示进度条
    private showProgressBar() {

        const loadingBg = cc.find("Canvas/loadingBg");
        if(loadingBg) {
            loadingBg.active = true;
        }
        if (this.progressBarContainer) {
            this.progressBarContainer.active = true;
            console.log('进度条已显示');
        }
    }

    // 隐藏进度条
    private hideProgressBar() {
        const loadingBg = cc.find("Canvas/laodingBg");
        if(loadingBg) {
            loadingBg.active = false;
        }
        if (this.progressBarContainer) {
            this.progressBarContainer.active = false;
            console.log('进度条已隐藏');
        }
    }

    // 更新进度条
    private updateProgressBar(progress: number) {
        if (this.progressBar && this.progressLabel) {
            this.progressBar.progress = progress / 100;
            this.progressLabel.string = `${Math.floor(progress)}%`;
            console.log(`进度条更新: ${progress}%`);
        }
    }

    // 模拟进度更新（作为备用方案）
    private simulatedProgressInterval: number = null;
    private currentSimulatedProgress: number = 0;

    private startSimulatedProgress() {
        this.currentSimulatedProgress = 0;
        this.simulatedProgressInterval = setInterval(() => {
            if (this.currentSimulatedProgress < 90) { // 最多到90%，留10%给实际加载完成
                this.currentSimulatedProgress += Math.random() * 10;
                this.updateProgressBar(this.currentSimulatedProgress);
            }
        }, 200);
        console.log('模拟进度更新已启动');
    }

    private stopSimulatedProgress() {
        if (this.simulatedProgressInterval) {
            clearInterval(this.simulatedProgressInterval);
            this.simulatedProgressInterval = null;
            console.log('模拟进度更新已停止');
        }
    }

    getGameList() {
        console.log('=== 开始获取游戏列表 ===');
        // const course_id = 39657;
        // const course_id = 39662;
        const course_id = 39663;

        
        const uri = `api/courseware/v2/${course_id}/list`;
        
        console.log('请求URI:', uri);
        console.log('课程ID:', course_id);
        
        const middleLayerNode = cc.director.getScene().getChildByName('middleLayer');
        console.log('middleLayer节点:', middleLayerNode);
        
        if (middleLayerNode) {
            const middleLayerComp = middleLayerNode.getComponent(middleLayer);
            console.log('middleLayer组件:', middleLayerComp);
            
            if (middleLayerComp && typeof middleLayerComp.callNetworkApiGet === 'function') {
                console.log('开始调用网络API...');
                middleLayerComp.callNetworkApiGet(uri, {}, (data) => {
                    console.log('=== 网络API回调数据 ===');
                    console.log('原始数据:', data);
                    console.log('数据类型:', typeof data);
                    console.log('是否有rows属性:', data && data.hasOwnProperty('rows'));
                    
                    if (data && data.rows) {
                        console.log('rows数组长度:', data.rows.length);
                        console.log('rows数据:', data.rows);
                        
                        const nameMap = {
                            "229602" : "火力小炮台",
                            "229604" : "钓鱼大作战",
                            "229606" : "急速滑雪",
                            "229593" : "单词泡泡",
                            "229594" : "疯狂拍苍蝇",
                            "229595" : "魔法福袋",
                            "229596" : "发音闪卡",
                            "229597" : "看图选词",
                            "229598" : "视频",
                            "229599" : "情景连线",
                            "229600" : "听音选择",
                            "229605" : "弹珠大作战",
                            "229603" : "欢乐卡牌机",
                            "229601" : "热气球大战",
                            "229580" : "翻卡",
                            "229579" : "打企鹅"
                        }

                        this.gameDataList = [];
                        const notClickableGameIds = [
                            229603, 229605, 229601, 229580, 229579,
                            229595, 229605, 229601, 229580, 229579,
                            229645, 229666, 229670, 229674, 229650,
                            229603, 229651,
                        ];
                        const notClickData = []
                        data.rows.forEach(item => {
                            // console.log('item:', item);
                            if(item.cover) {
                                item.cover = item.cover.replace('http://', 'https://');
                                if(item.cw_cover) {
                                    item.cw_cover = item.cw_cover.replace('http://', 'https://');
                                }
                            }
                            if(item.data) {
                                item.data = item.data.replace('http://', 'https://');
                            }
                            if(notClickableGameIds.includes(item.id)) {
                                notClickData.push(item);
                            } else {
                                this.gameDataList.push(item);
                            }

                            if(nameMap[item.id]) {
                                item.template_description = nameMap[item.id];
                            }

                            // console.log('item:', item);
                            return item;
                        });
                        this.gameDataList = this.gameDataList.concat(notClickData);

                        console.log('保存到gameDataList:', this.gameDataList);
                        
                        this.createGameList();
                    } else {
                        console.error('数据格式不正确或没有rows属性');
                        console.log('完整数据对象:', JSON.stringify(data, null, 2));
                    }
                });
            } else {
                console.error('middleLayer 组件未找到或 callNetworkApiGet 方法不存在');
                console.log('middleLayerComp类型:', typeof middleLayerComp);
                if (middleLayerComp) {
                    console.log('middleLayerComp方法:', Object.getOwnPropertyNames(middleLayerComp));
                }
            }
        } else {
            console.error('middleLayer 节点未找到');
            console.log('场景中的所有节点:', cc.director.getScene().children.map(child => child.name));
        }
    }

    private createGameList() {
        console.log('=== 开始创建游戏列表 ===');
        console.log('gameListContainer:', this.gameListContainer);
        console.log('scrollView:', this.scrollView);
        console.log('gameDataList长度:', this.gameDataList.length);
        
        if (!this.gameListContainer || !this.scrollView) {
            console.error('游戏列表容器或滚动视图未找到');
            return;
        }

        const content = this.scrollView.content;
        console.log('scrollView content:', content);
        
        if (!content) {
            console.error('滚动视图内容节点未找到');
            return;
        }

        // 清空现有内容
        console.log('清空现有内容，当前子节点数量:', content.childrenCount);
        const line1 = content.getChildByName('line1');
        line1.removeAllChildren();
        const line2 = content.getChildByName('line2');
        line2.removeAllChildren();
        console.log('清空后子节点数量:', content.childrenCount);

        // 创建游戏卡片
        console.log('开始创建游戏卡片...');
        this.gameDataList.forEach((gameData, index) => {
            // console.log(`创建第${index + 1}个游戏卡片:`, gameData);
            this.createGameCard(gameData, index, index % 2 === 0 ? line1 : line2);
        });

        // 设置内容节点大小 - 以(0,0)为中心
        const cardWidth = 410; // 卡片宽度
        const cardHeight = 269; // 卡片高度
        const spacing = 24; // 卡片间距
        const totalCards = Math.ceil(this.gameDataList.length/2);

        const maxWidth = line1.width > line2.width ? line1.width : line2.width;
        content.width = maxWidth + 80;
        content.height = cardHeight;

        console.log('line1.width:', line1.width);
        console.log('line2.width:', line2.width);
        console.log('maxWidth:', maxWidth);
        console.log('content.width:', content.width);
        // console.log('content.height:', content.height);
        
        console.log('卡片尺寸信息:', { cardWidth, cardHeight, spacing, totalCards });
        
        if (totalCards > 0) {
            // const totalWidth = totalCards * cardWidth + totalCards * spacing;
            // content.width = totalWidth;
            // content.height = cardHeight;
            
            console.log('设置content节点大小:', { width: content.width, heigsht: content.height });
            console.log('设置content节点锚点:', { anchorX: content.anchorX, anchorY: content.anchorY });
        } else {
            console.warn('没有游戏数据，无法设置内容节点大小');
        }
        
        console.log('=== 游戏列表创建完成 ===');
        console.log('最终content子节点数量:', content.childrenCount);
    }

    private createGameCard(gameData: GameData, index: number, parent: cc.Node) {
        // console.log(`=== 创建第${index + 1}个游戏卡片 ===`);
        // console.log('游戏数据:', gameData);
        // console.log('父节点:', parent);
        // console.log('gameCardPrefab:', this.gameCardPrefab);
        
        if (this.gameCardPrefab) {
            // console.log('使用预制体创建卡片');
            // 使用预制体创建卡片
            const cardNode = cc.instantiate(this.gameCardPrefab);
            parent.addChild(cardNode);

            const disW = 20;
            cardNode.x = parent.width + cardNode.width/2;
            cardNode.y = 0;
            parent.width = cardNode.x + cardNode.width/2 + disW;
            // console.log('parent.width:', parent.width);
            // console.log('预制体卡片创建成功:', cardNode);

            // 初始化卡片数据
            const gameCardComp = cardNode.getComponent(GameCard) || cardNode.addComponent(GameCard);
            // console.log('GameCard组件:', gameCardComp);
            
            if (gameCardComp && typeof gameCardComp.init === 'function') {
                // console.log('调用GameCard组件的init方法');
                const cardData = Object.assign({}, gameData, { cw_cover: (gameData as any).cw_cover || gameData.cover || '' });
                gameCardComp.init(cardData as any);
            } else {
                console.warn('GameCard组件未找到或init方法不存在');
            }

            // 监听卡片点击事件
            cardNode.on('onGameCardClick', this.onGameCardClick, this);
            // console.log('卡片点击事件监听器已添加');
        } else {
            // console.log('没有预制体，使用代码创建卡片');
            // 如果没有预制体，使用代码创建
            this.createGameCardByCode(gameData, index, parent);
        }
    }

    private createGameCardByCode(gameData: GameData, index: number, parent: cc.Node) {
        // 创建卡片节点
        const cardNode = new cc.Node('game_card');
        parent.addChild(cardNode);

        // 设置卡片位置 - 以(0,0)为中心计算
        const cardWidth = 300;
        const cardHeight = 400;
        const spacing = 30;
        const totalCards = this.gameDataList.length;
        
        // 计算起始位置，使卡片列表居中
        const totalWidth = totalCards * cardWidth + (totalCards - 1) * spacing;
        const startX = -totalWidth / 2 + cardWidth / 2;
        
        const x = startX + index * (cardWidth + spacing);
        const y = 0;
        cardNode.setPosition(x, y);

        // 创建卡片背景
        const cardBg = new cc.Node('card_bg');
        cardNode.addChild(cardBg);
        
        const bgSprite = cardBg.addComponent(cc.Sprite);
        // 设置白色背景，可以通过代码创建或使用图片资源
        cardBg.color = cc.Color.WHITE;
        cardBg.width = cardWidth;
        cardBg.height = cardHeight;
        
        // 添加圆角效果（如果有圆角图片资源）
        // bgSprite.spriteFrame = this.getRoundedRectSprite();

        // 创建游戏缩略图
        const thumbnailNode = new cc.Node('game_thumbnail');
        cardNode.addChild(thumbnailNode);
        
        const thumbnailSprite = thumbnailNode.addComponent(cc.Sprite);
        thumbnailNode.width = cardWidth - 40;
        thumbnailNode.height = cardHeight - 120;
        thumbnailNode.setPosition(0, 60);
        
        // 加载游戏封面图片
        if (gameData.cover) {
            cc.loader.load(gameData.cover, (err, texture) => {
                if (!err && texture) {
                    const spriteFrame = new cc.SpriteFrame(texture);
                    thumbnailSprite.spriteFrame = spriteFrame;
                }
            });
        }

        // 创建游戏标题
        const titleNode = new cc.Node('game_title');
        cardNode.addChild(titleNode);
        
        const titleLabel = titleNode.addComponent(cc.Label);
        titleLabel.string = gameData.template_description || '未知游戏';
        titleLabel.fontSize = 24;
        titleLabel.lineHeight = 30;
        titleLabel.horizontalAlign = cc.Label.HorizontalAlign.CENTER;
        titleLabel.verticalAlign = cc.Label.VerticalAlign.CENTER;
        titleLabel.node.color = cc.Color.BLACK;
        titleNode.width = cardWidth - 20;
        titleNode.height = 60;
        titleNode.setPosition(0, -cardHeight / 2 + 40);

        // 添加点击事件
        const button = cardNode.addComponent(cc.Button);
        button.node.on('click', () => {
            this.onGameCardClick(gameData);
        });
    }

    private onGameCardClick(gameData: GameData) {
        console.log('点击游戏卡片:', gameData.template_description);
        // 这里可以添加跳转到游戏页面的逻辑
        // 例如：this.node.emit('onGameSelected', gameData);
        // if([
        //     229603, 229605, 229601, 229580, 229579,
        //     229595, 229605, 229601, 229580, 229579,
        //     229645, 229666, 229670, 229674, 229650,
        //     229603, 229651,
        // ].includes(gameData.id)) {
        //     return;
        // }
        const middleLayerNode = cc.director.getScene().getChildByName('middleLayer');
        if (middleLayerNode) {
            const middleLayerComp = middleLayerNode.getComponent(middleLayer);
            if (middleLayerComp && typeof middleLayerComp.loadPageBundle === 'function') {
                console.log("loadPageBundle");
                console.log(gameData);
                
                // 显示进度条
                this.showProgressBar();
                this.updateProgressBar(0);
                
                // 重写middleLayer的进度更新方法，以便监听进度
                this.overrideProgressUpdate(middleLayerComp);
                
                // 启动模拟进度更新（作为备用方案）
                this.startSimulatedProgress();
                

                middleLayerComp.setCourseData(JSON.parse(gameData.data));
                middleLayerComp.loadPageBundle(gameData, () => {
                    console.log('loadPageBundle success');
                    // 加载完成，隐藏进度条
                    this.stopSimulatedProgress();
                    this.hideProgressBar();
                });
            } else {
                console.error('middleLayer 组件未找到或 handleSubSceneEvent 方法不存在');
            }
        } else {
            console.error('middleLayer 节点未找到');
        }
    }

    // 重写middleLayer的进度更新方法
    private overrideProgressUpdate(middleLayerComp: any) {
        // 保存原始的setLoadingProgressBar方法
        const originalSetLoadingProgressBar = middleLayerComp.setLoadingProgressBar;
        
        // 重写setLoadingProgressBar方法
        middleLayerComp.setLoadingProgressBar = (progress: number) => {
            console.log('进度更新:', progress);
            // 更新我们的进度条
            this.updateProgressBar(progress);
            
            // 调用原始方法（如果存在）
            if (originalSetLoadingProgressBar) {
                originalSetLoadingProgressBar.call(middleLayerComp, progress);
            }
        };
        
        console.log('进度更新方法已重写');
    }

    onClickBack() {
        // 当按钮点击或其他逻辑触发时，派发全局事件
        // 第一个参数：事件名，必须和主场景监听的名字一致
        // 第二个参数：可变长参数，可以传递任意数量、任意类型的参数给监听方
        console.log('onClickBack');
        // this.node.emit('onEventFromSubScene', "Hello Main Scene!", 100);
        // 获取主场景的 middleLayer 节点并调用 handleSubSceneEvent 方法
        const middleLayerNode = cc.director.getScene().getChildByName('middleLayer');
        if (middleLayerNode) {
            const middleLayerComp = middleLayerNode.getComponent(middleLayer);
            if (middleLayerComp && typeof middleLayerComp.closeGameCenter === 'function') {
                middleLayerComp.closeGameCenter();
            } else {
                console.error('middleLayer 组件未找到或 handleSubSceneEvent 方法不存在');
            }
        } else {
            console.error('middleLayer 节点未找到');
        }
    }

    // update (dt) {}
}
