const { ccclass, property } = cc._decorator;

@ccclass
export default class Test extends cc.Component {

    @property([cc.SpriteFrame])
    private sfs: Array<cc.SpriteFrame> = [];
    @property([cc.Material])
    private mats: Array<cc.Material> = [];

    private img: cc.Sprite;
    private img1: cc.Sprite;
    private img2: cc.Sprite;
    private tabs: Array<cc.Node>;

    private currMat: cc.Material;
    private nextMat: cc.Material;
    private spIndex: number;
    private delayTime: number;
    private progress: number;

    protected onLoad(): void {

        this.img = this.node.getChildByName("img").getComponent(cc.Sprite);
        this.img1 = this.node.getChildByName("img1").getComponent(cc.Sprite);
        this.img2 = this.node.getChildByName("img2").getComponent(cc.Sprite);
        this.tabs = this.node.getChildByName("tabs").children;
        for (const tab of this.tabs) {
            tab.on(cc.Node.EventType.TOUCH_START, (evt: { target: cc.Node }) => {
                this.tab(evt.target);
            });
        }

        this.spIndex = -1;
        this.delayTime = 0;
        this.progress = 1;
        this.tab(this.tabs[0]);
        this.currMat = this.nextMat;
    }

    private tab(tab: cc.Node): void {
        for (const _tab of this.tabs) {
            _tab.color = cc.Color.WHITE;
        }
        tab.color = cc.Color.GREEN;

        this.nextMat = null;
        const matName = tab.getComponent(cc.Label).string;
        for (const mat of this.mats) {
            if (matName == mat.name) {
                this.nextMat = mat;
                break;
            }
        }
        if (this.nextMat) { } else {
            console.error("木有材质：" + matName);
        }
    }

    protected update(): void {
        if (this.currMat) {
            if (this.progress < 1) {
                if ((this.progress += 0.005) >= 1) {
                    this.progress = 1;
                    this.delayTime = 60;
                }
                this.currMat.setProperty("progress", this.progress);
            } else {
                if (--this.delayTime <= 0) {
                    if (++this.spIndex >= this.sfs.length) {
                        this.spIndex = 0;
                    }
                    this.img.spriteFrame = this.img1.spriteFrame = this.sfs[this.spIndex];
                    this.progress = 0;
                    if (this.nextMat) {
                        this.currMat = this.nextMat;
                        this.nextMat = null;
                        this.img.setMaterial(0, this.currMat);
                    }
                    const nextSF = this.sfs[(this.spIndex + 1) % this.sfs.length];
                    this.img2.spriteFrame = nextSF;
                    this.currMat.setProperty("texture2", nextSF.getTexture());
                    this.currMat.setProperty("progress", this.progress);
                }
            }
        }
    }

}
