import { _decorator, Component, instantiate, Node, Sprite, UITransform, Vec2 } from 'cc';
import { resMgr } from '../../Frames/ResourcesMgr';
import { RoleCard } from './RoleCard';
import { RoleData } from '../../DataItem/ItemData';
import { dataMgr } from '../../Frames/DataManager';
const { ccclass, property } = _decorator;

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

    _content: Node = null;
    private _roleData: RoleData[] = null;
    private _characterSlot: Node = null;
    roleImgName: string = null;
    roleCardState: boolean = null;
    protected onLoad() {
        this._roleData = dataMgr.getAllDataByName("RoleCardData");
        this._content = this.node.getChildByPath("view/content");
        this._characterSlot = this.node.parent.getChildByPath('SelectTroops_Bottom/CharacterSlot');
    }

    protected start(): void {
        this._roleData.forEach((values, index) => {
            this._createRoleCard(index);
        })
    }

    //创建角色卡
    private _createRoleCard(id: number) {
        const roleCard: Node = instantiate(resMgr.getPrefab("RoleCard-Big"));
        roleCard.parent = this._content;
        roleCard.getComponent(RoleCard).init(id, this._roleData);
    }

    //打开阴影遮罩
    openShadow(pos: Vec2) {
        for (const roleCard of this._content.children) {
            const box = roleCard.getComponent(UITransform).getBoundingBoxToWorld();
            if (box.contains(pos)) {
                //获取 RoleList 节点下的子节点 content 的子节点的脚本
                const roleCardTS = roleCard.getComponent(RoleCard);
                //如果Shadow（阴影遮罩）是关闭的
                if (!roleCardTS.getShadowState()) {
                    //遍历角色卡槽的子节点
                    for (const card of this._characterSlot.children) {
                        let sprite = card.getChildByName("Sprite").getComponent(Sprite);
                        let label = card.getChildByName("Label");
                        if(label.active){
                            return;
                        }
                        //如果角色卡槽没有角色图片 以及 "解锁卡槽" 节点的关闭的
                        if (!sprite.spriteFrame && !label.active) {
                            //打开Shadow
                            roleCardTS.isOpenShadow(true);
                            sprite.spriteFrame = resMgr.getSpriteFrame(roleCardTS.getRoleImgName());
                            return;
                        }
                    }
                }
            }
        }
    }
}


