import NumberToImage from "../../Script/NumberToImage";

const { ccclass, property } = cc._decorator;

@ccclass
export default class PassCheckItem extends cc.Component {
    @property(cc.Prefab)
    passCheckItemLvPrefab: cc.Prefab = null;

    @property(cc.Sprite)
    leftReward: cc.Sprite = null;
    @property(cc.Sprite)
    rightReward: cc.Sprite = null;
    @property(cc.Node)
    leftNum: cc.Node = null;
    @property(cc.Node)
    rightNum: cc.Node = null;

    @property(cc.SpriteAtlas)
    texture_atlas: cc.SpriteAtlas = null;

    // 添加更多图集属性
    @property(cc.SpriteAtlas)
    newUserAtlas: cc.SpriteAtlas = null;

    // @property(cc.SpriteAtlas)
    // textureAtlas1: cc.SpriteAtlas = null;

    @property(cc.SpriteAtlas)
    uiAtlas: cc.SpriteAtlas = null;

    // 数据
    private data: any = null;
    private itemIndex: number = 0;
    private isUIInitialized: boolean = false;
    // 1001 金币  2001 锤子  2003 魔棒  3001 15分钟无限体力 3002 30分钟  3003 1小时  3004 2小时 3005 3小时 
    // 添加物品ID到图片名称的映射
    private itemImageMap: { [key: number]: { imageName: string, atlas: string } } = {
        1001: { imageName: "coins4", atlas: "texture_atlas" },     // shop/img/texture_atlas-1
        2001: { imageName: "iceb", atlas: "newUserAtlas" },        // action_bundle/img/newUser
        2002: { imageName: "chuizi", atlas: "newUserAtlas" },      // action_bundle/img/newUser 
        2003: { imageName: "starb", atlas: "newUserAtlas" },       // action_bundle/img/newUser
        3001: { imageName: "skylineHealth", atlas: "uiAtlas" },   // UI/UI/
        3002: { imageName: "skylineHealth", atlas: "uiAtlas" },   // UI/UI/
        3003: { imageName: "skylineHealth", atlas: "uiAtlas" },   // UI/UI/   skylineHealth
        // 可以继续添加更多物品ID和对应图片的映射
    };
    private numImgmap: { [key: number]: { imageName: string, atlas: string } } = {
        3001: { imageName: "15", atlas: "uiAtlas" },
        3002: { imageName: "30min", atlas: "texture_atlas" },
        3003: { imageName: "1h", atlas: "texture_atlas" },
    }

    init(data: any, index: number) {
        this.data = data;
        this.itemIndex = index;
        this.updateUI();
    }
    initUI() {
        if (!this.data) {
            return;
        }

        // 防止重复初始化
        if (this.isUIInitialized) {
            return;
        }

        // 处理passCheckItemLv prefab的实例化
        if (this.passCheckItemLvPrefab) {
            // 实例化并添加新的prefab
            const itemLvNode = cc.instantiate(this.passCheckItemLvPrefab);
            itemLvNode.parent = this.node.parent;
            itemLvNode.setPosition(this.node.x, this.node.y);
            itemLvNode.zIndex = 2;
            let bright_bg = itemLvNode.getChildByName("bright_bg").getComponent(cc.Sprite);

            let levelNum = itemLvNode.getChildByName("levelNum");
            let lvNum = this.itemIndex + 1
            // NumberToImage.numberToImageNodes(lvNum, 43, 15, "tili_", levelNum, true);
            NumberToImage.numberToImageNodes(lvNum, 45, 48, "half_black_", levelNum, true);
            if (lvNum >= 10 && lvNum <= 19) {
                levelNum.x -= 3;
            }
            if (lvNum >= 20 && lvNum <= 29) {
                levelNum.x += 3;
            }

            if (this.data.free === -1) {
                // 未激活状态
                if (this.uiAtlas) {
                    const spriteFrame = this.uiAtlas.getSpriteFrame("no_bright_bg");
                    if (spriteFrame) {
                        bright_bg.spriteFrame = spriteFrame;
                    }
                    // cc.fx.GameTool.setGray(levelNum, true)
                    NumberToImage.numberToImageNodes(lvNum, 45, 48, "all_black_", levelNum, true);
                }
            } else {
                // 已激活状态
                if (this.uiAtlas) {
                    const spriteFrame = this.uiAtlas.getSpriteFrame("bright_bg");
                    if (spriteFrame) {
                        bright_bg.spriteFrame = spriteFrame;
                    }
                }
            }
        }

        // 初始化按钮点击事件（只执行一次）
        this.setupButtonEvents();

        // 标记UI已初始化
        this.isUIInitialized = true;

        // 首次更新UI
        this.updateUI();
    }

    // 专门用于设置按钮事件的方法
    private setupButtonEvents() {
        let node1 = this.node.getChildByName("leftNode");
        let node2 = this.node.getChildByName("rightNode");

        if (node1) {
            let getBtn = node1.getChildByName("getBtn");
            if (getBtn) {
                getBtn.on('click', () => {
                    this.onGetRewardClicked(node1);
                }, this);
            }
        }

        if (node2) {
            let getBtn = node2.getChildByName("getBtn");
            if (getBtn) {
                getBtn.on('click', () => {
                    this.onGetRewardClicked(node2);
                }, this);
            }
        }
    }

    updateUI() {
        if (!this.data) {
            return;
        }

        // 根据数据更新界面元素
        let node1 = this.node.getChildByName("leftNode");
        let node2 = this.node.getChildByName("rightNode");

        if (this.data.ItemID1 !== undefined && this.data.ItemNum1 !== undefined) {
            this.updateItemInfo(this.data.ItemID1, this.data.ItemNum1, node1, this.data.free);
        }
        if (this.data.ItemID2 !== undefined && this.data.ItemNum2 !== undefined) {
            this.updateItemInfo(this.data.ItemID2, this.data.ItemNum2, node2, this.data.passCheck);
        }
        if (this.data.free !== undefined) {
            this.updateRewardState(this.data.free, node1);
        }
        if (this.data.passCheck !== undefined) {
            this.updateRewardState(this.data.passCheck, node2);
        }
    }
    updateRewardState(itemData: any, targetNode: cc.Node) {
        // 更新免费状态的UI 0已领 1 未领
        let getSpr = targetNode.getChildByName("get")
        let getBtn = targetNode.getChildByName("getBtn")
        let lock = targetNode.getChildByName("lock")
        let activate = cc.fx.GameConfig.GM_INFO.passCheckActivate

        if (lock) {
            lock.active = false;
        }

        if (itemData === 1) {
            getSpr.active = false;
            getBtn.active = true;

            if (lock && activate == false) {
                lock.active = true;
                getBtn.active = false;
            }
        } else if (itemData === 0) {
            getSpr.active = true;
            getBtn.active = false;
            this.setNodeGray(targetNode)
        } else {
            if (lock && activate == false) {
                lock.active = true;
            }
            getSpr.active = false;
            getBtn.active = false;
        }
    }


    updateItemInfo(itemID: number, itemNum: number, node: cc.Node, itemData: any) {
        // 更新物品信息的UI
        const imageInfo = this.itemImageMap[itemID];
        let freeRewardNode = node.getChildByName("freeReward");
        let freeReward: cc.Sprite = null;

        if (freeRewardNode) {
            freeReward = freeRewardNode.getComponent(cc.Sprite);
        }

        if (imageInfo) {
            // 根据图集名称获取对应的图集
            let targetAtlas: cc.SpriteAtlas = null;
            switch (imageInfo.atlas) {
                case "texture_atlas":
                    targetAtlas = this.texture_atlas;
                    break;
                case "newUserAtlas":
                    targetAtlas = this.newUserAtlas;
                    break;
                case "uiAtlas":
                    targetAtlas = this.uiAtlas;
                    break;
                default:
                    console.warn(`Unknown atlas: ${imageInfo.atlas}`);
                    break;
            }

            // 加载对应的图片资源
            if (targetAtlas && freeReward) {
                const spriteFrame = targetAtlas.getSpriteFrame(imageInfo.imageName);
                if (spriteFrame) {
                    freeReward.spriteFrame = spriteFrame;
                    let imgScale = 1;
                    switch (itemID) {
                        case 1001:
                            imgScale = 1;
                            break;
                        case 2001:
                            imgScale = 0.7;
                            break;
                        case 2002:
                            imgScale = 0.6;
                            break;
                        case 2003:
                            imgScale = 0.6;
                            break;
                        default:
                            imgScale = 1.1;
                            break;
                    }
                    freeRewardNode.scale = imgScale;
                } else {
                    console.warn(`Sprite frame ${imageInfo.imageName} not found in atlas ${imageInfo.atlas}`);
                }
            } else {

            }
        } else {
            console.warn(`No image found for item ID: ${itemID}`);
            // 使用默认图片
        }

        let addTiem = node.getChildByName("addTiem");
        addTiem.active = false;
        let num1 = node.getChildByName("num_1");
        let num_x = node.getChildByName("num_x");
        num1.active = false;
        num_x.active = false;
        if ([3001, 3002, 3003].includes(itemID) && addTiem) {
            addTiem.active = true;
            const numImageInfo = this.numImgmap[itemID];
            if (numImageInfo) {
                let targetAtlas: cc.SpriteAtlas = null;
                switch (numImageInfo.atlas) {
                    case "texture_atlas":
                        targetAtlas = this.texture_atlas;
                        break;
                    case "uiAtlas":
                        targetAtlas = this.uiAtlas;
                        break;
                    default:
                        console.warn(`Unknown atlas for num image: ${numImageInfo.atlas}`);
                        break;
                }

                if (targetAtlas) {
                    const spriteFrame = targetAtlas.getSpriteFrame(numImageInfo.imageName);
                    if (spriteFrame) {
                        let numSprite = addTiem.getComponent(cc.Sprite);
                        if (numSprite) {
                            numSprite.spriteFrame = spriteFrame;
                        }
                    } else {
                        console.warn(`Sprite frame ${numImageInfo.imageName} not found in atlas ${numImageInfo.atlas}`);
                    }
                }
            }
        } else {
            num1.active = true;
            num_x.active = true;
            // NumberToImage.numberToImageNodes(itemNum, 50, 25, "pc_num_", num1, true);
            // NumberToImage.numberToImageNodes(itemNum, 45, 48, "Black", num1, true);
            NumberToImage.numberToImageNodes(itemNum, 48, 50, "half_black_", num1, true);
            if (itemData === 0) {
                this.setNodeGray(num1)
                this.setNodeGray(num_x)
            }
            // num1.scale = 0.8;
            if (num_x && num1) {
                // 计算数值的位数
                const digitCount = itemNum.toString().length;
                const offset = Math.max(0, digitCount);
                const num_xWidth = num_x.width;
                if (digitCount == 4) {
                    num1.x = num1.x - 75;
                    num_x.x = num1.x - (offset - 1) * num_xWidth - 25;
                } else if (digitCount == 3) {
                    num1.x = num1.x - 45;
                    num_x.x = num1.x - offset * num_xWidth - 15;
                } else if (digitCount == 1) {
                    num_x.x = num1.x - 55;
                }

            }
        }
    }


    updateItem(data: any, index: number) {
        // 在这里处理数据更新
        this.data = data;
        this.itemIndex = index;
        this.initUI();
    }

    // 数据改变时调用
    public dataChanged() {
        this.updateUI();
    }

    // 组件生命周期函数
    protected onLoad() {
        this.isUIInitialized = false;
    }

    protected start() {
        // console.log("PassCheckItem component started");
    }
    private onGetRewardClicked(targetNode: cc.Node) {
        // 确定是左侧还是右侧的奖励
        let isLeftReward = targetNode.name === "leftNode";

        // 获取对应的物品ID和数量
        let itemId = isLeftReward ? this.data.ItemID1 : this.data.ItemID2;
        let itemNum = isLeftReward ? this.data.ItemNum1 : this.data.ItemNum2;

        console.log("领取物品:", itemId, "数量:", itemNum);

        // 调用领取奖励方法
        this.claimReward(itemId, itemNum, isLeftReward);
    }

    private claimReward(itemId: number, itemNum: number, isLeftReward: boolean) {
        let passCheckMgr = this.node.parent.parent.parent.parent.getComponent('passCheckMgr');
        if (passCheckMgr && typeof passCheckMgr.claimReward === 'function') {
            console.log("更新奖励状态到服务器:", itemId, itemNum, isLeftReward);
            passCheckMgr.claimReward(this.itemIndex, itemId, itemNum, isLeftReward);
        }
    }

    private claimInfiniteHealth(amount: number, itemId: number) {

    }

    public updateRewardUIAfterClaim(isLeftReward: boolean) {
        let targetNode = isLeftReward ?
            this.node.getChildByName("leftNode") :
            this.node.getChildByName("rightNode");

        let num1 = targetNode.getChildByName("num_1");
        let num_x = targetNode.getChildByName("num_x");
        console.log("更新奖励UI:", isLeftReward);
        if (targetNode) {
            let getSpr = targetNode.getChildByName("get");
            let getBtn = targetNode.getChildByName("getBtn");

            if (getSpr && getBtn) {
                getSpr.active = true;
                getBtn.active = false;
                this.setNodeGray(targetNode);
                this.setNodeGray(num1);
            }
        }
    }



    private setNodeGray(node: cc.Node, color?: cc.Color) {
        let setColor = color || cc.color(190, 190, 190, 255);
        if (node) {
            for (let i = 0; i < node.children.length; i++) {
                // console.log("设置子节点颜色", node.children[i]);
                node.children[i].color = setColor;
            }
        }

    }
}