import { preGameData } from "./prefabTestGameData";

const { ccclass, property } = cc._decorator;

@ccclass
export default class item extends cc.Component {

    private _clip: cc.AnimationClip = null;
    private _sp: cc.Sprite = null;
    private _spArr: cc.SpriteFrame[] = [];

    onLoad() {
        // this.loopPlay();
    }

    createGif(num) {
        let key = preGameData.zipData.gifMap.getKey(num);
        let t_frames: Array<cc.SpriteFrame> = preGameData.zipData.gifMap.get(key);
        if (this._clip) {
            this._clip.decRef();
            this._clip.destroy();
            this._clip = null;
        }
        this._clip = cc.AnimationClip.createWithSpriteFrames(t_frames, t_frames.length);
        this._clip.name = "anim";
        this._clip.sample = 60;
        this._clip.speed = 0.4;
        this._clip.wrapMode = cc.WrapMode.Loop;
        this._clip.addRef();
        let sp = this.node.getComponent(cc.Sprite);
        sp.spriteFrame = null;
        let anim: cc.Animation = this.node.getComponent(cc.Animation);
        if (!anim) {
            anim = this.node.addComponent(cc.Animation);
        }
        anim.addClip(this._clip);
        anim.play("anim");
        //另外一种动画播放方案
        // this.playAnim(num);
    }

    // playAnim(num) {
    //     let key = preGameData.zipData.gifMap.getKey(num);
    //     this._spArr = preGameData.zipData.gifMap.get(key);
    //     this._sp = this.node.getComponent(cc.Sprite);
    // }


    // loopPlay(num: number = 0) {
    //     if (this._spArr.length > 0) {
    //         if (num >= this._spArr.length) {
    //             num = 0;
    //         }
    //         this._sp.spriteFrame = this._spArr[num];
    //         this.scheduleOnce(() => {
    //             num++
    //             this.loopPlay(num);
    //         }, 0.1)
    //     } else {
    //         this.scheduleOnce(() => {
    //             this.loopPlay();
    //         }, 0.5);
    //     }
    // }
    /**清除数据 */
    clearData() {
        this._spArr = [];
        let anim = this.node.getComponent(cc.Animation);
        if (anim) {
            anim.stop();
            anim.destroy();
            // this.node.removeComponent(cc.Animation);
        }
        // let sp = this.node.getComponent(cc.Sprite);
        // sp.spriteFrame = null;
        if (this._clip) {
            this._clip.decRef();
            cc.log("--clip-->>>", this._clip.refCount);
            this._clip.destroy();
            this._clip = null;
        }
    }

    removeNode() {
        this.node.destroy();
    }

}
