import { GameEvent } from "../data/const/EventConst";
import EventMng from "../manager/EventMng";


// 已知问题:当修改此节点的透明度和颜色时,渐变会失去效果
const { ccclass, property, requireComponent, menu, executeInEditMode } = cc._decorator;
@ccclass
// 测试了一下,发现使用executeInEditMode后使得引擎每次刷新都会走,考虑到绑定的元素过多,这里关掉了
@executeInEditMode
@requireComponent(cc.RenderComponent)
@menu('Label/LabelColor')
export default class ColorAssembler2D extends cc.Component {

    @property
    private _colors: cc.Color[] = []; // 支持配置4个颜色,顺序是:左下,右下,右上,左上
    @property({ type: [cc.Color] })
    public get colors() {
        return this._colors;
    }
    public set colors(colors) {
        this._colors = colors;
        this._updateColors();
    }
    onEnable() {
        cc.director.once(cc.Director.EVENT_AFTER_DRAW, this._updateColors, this);
        EventMng.on(GameEvent.ON_REFRESH_COLOR, this._updateColors, this);
    }
    onDisable() {
        cc.director.off(cc.Director.EVENT_AFTER_DRAW, this._updateColors, this);
        EventMng.off(GameEvent.ON_REFRESH_COLOR, this._updateColors, this);
        this.node['_renderFlag'] |= cc['RenderFlow'].FLAG_COLOR;
        //
    }
    private _updateColors() {
        if (CC_EDITOR) {
            Editor.log('Label.Color')
        }
        const cmp = this.getComponent(cc.RenderComponent);
        if (!cmp) return;
        const _assembler = cmp['_assembler'];
        if (!(_assembler instanceof cc['Assembler2D'])) return;
        const uintVerts = _assembler._renderData.uintVDatas[0]; // 颜色数组
        if (!uintVerts) return;
        const color = this.node.color;
        const floatsPerVert = _assembler.floatsPerVert;
        const colorOffset = _assembler.colorOffset;
        let count = 0;
        // console.log(`长度uintVerts.length：${uintVerts.length}, floatsPerVert:${floatsPerVert}`)
        for (let i = colorOffset, l = uintVerts.length; i < l; i += floatsPerVert) {
            uintVerts[i] = (this.colors[count++] || color)['_val'];
        }
    }
}