import { ryw_Event } from "../../FrameWork/Event/EventEnum";
import EventMgr from "../../FrameWork/Event/EventMgr";

const { ccclass, property } = cc._decorator;

@ccclass
export default class DuiBChoosePrefab extends cc.Component {

    @property(cc.Node)
    duiChoose: cc.Node = null;

    @property(cc.Node)
    content: cc.Node = null;

    private hideItemArray: cc.Node[] = [];

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}

    start() {
        this.duiChoose.active = false;
        this.hideItemArray = [];
    }

    setDuiChooseList(answerList: any[]) {
        for (const iterator of this.content.children) {
            iterator.active = false;
        }
        let xuhaoArray = ['A:', 'B:', 'C:', 'D:', 'E:', 'F:'];

        for (let index = 0; index < answerList.length; index++) {
            let duiChoose: cc.Node = null;
            if (index >= this.content.children.length) {
                duiChoose = cc.instantiate(this.duiChoose);
                this.content.addChild(duiChoose);
                duiChoose.setPosition(cc.v3());
            } else {
                duiChoose = this.content.children[index];
            }
            duiChoose.active = true;
            duiChoose.getComponent(cc.Button).enabled = true;
            duiChoose.color = cc.Color.WHITE;
            duiChoose.attr({ iteminfo: answerList[index] });
            duiChoose.getChildByName("str").getComponent(cc.Label).string = xuhaoArray[index] + answerList[index].str;
        }
    }

    onClick(event) {
        let target = event.target as cc.Node;
        target.getComponent(cc.Button).enabled = false;
        target.color = cc.Color.GRAY;

        let index = this.content.children.indexOf(target);
        EventMgr.emitEvent_custom(ryw_Event.DuiChooseResult, { touchIndex: index, duiChooseInfo: target["iteminfo"] });
    }

    private setItem(target?: cc.Node) {
        if (target) {
            if (this.hideItemArray.indexOf(target) == -1) {
                target.active = false;
                this.hideItemArray.push(target);
            }
            return null;
        } else {
            if (this.hideItemArray.length > 0) {
                return this.hideItemArray.shift();
            }
            let duiChoose = cc.instantiate(this.duiChoose);
            this.content.addChild(duiChoose);
            duiChoose.setPosition(cc.v3());
            return duiChoose;
        }
    }

    // update (dt) {}
}