//*//
import { __private, assert, BaseRenderData, BitmapFont, cclegacy, Color, Component, Director, director, Game, game, gfx, Label, Material, MotionStreak, murmurhash2_32_gc, Node, renderer, resources, Sprite, SpriteFrame, StencilManager, TiledLayer, TiledRenderData, UIRenderer, VERSION } from 'cc';
import { DEBUG, EDITOR, JSB } from 'cc/env';




const MAX_TEX = 8; //最大纹理
//@ts-ignore
gfx.Texture.prototype.texID = -1; //当前纹理id
//@ts-ignore
Material.prototype.isMultTextures = false; //多纹理材质标记


export const MultBatch2D: any = {
    enable: false,
    parent: null,
    incID: 0,
    count: 0,
    hash: 0,
    reset: function () {
        this.incID += this.count;
        this.count = 0;
    }
};


const loadMultTextures = function () {
    MultBatch2D.enable = false; //提前加载多纹理材质
    resources.load("MultTextures/Mult-material", Material, (err, material) => {
        if (!err) {
            let mat = cclegacy.builtinResMgr.get('ui-sprite-material');
            if (mat) {
                mat._hash = MultBatch2D.hash = Material.getHash(mat);
                MultBatch2D.parent = material;
                MultBatch2D.enable = true;
                material.addRef();
            }
        }
    });
}


let _cacheUseCount: number = 0;
let _cacheMaterials: Array<Material> = [];
const getMultMaterial = function (oldMat: any) {

    MultBatch2D.reset();

    if (!MultBatch2D.enable ||
        !oldMat || !oldMat.isMultTextures) {
        return oldMat;
    }

    if (!MultBatch2D.parent
        || !MultBatch2D.parent.isValid) {
        loadMultTextures();
        return oldMat;
    }

    let newMat: any = _cacheMaterials[_cacheUseCount++];
    if (!newMat || !newMat.isValid) {
        const material = { parent: MultBatch2D.parent };
        newMat = new renderer.MaterialInstance(material);
        _cacheMaterials[_cacheUseCount - 1] = newMat;
        newMat['isMultTextures'] = true;
        newMat['cacheTextures'] = [-1];
        newMat.addRef();
    }

    return newMat;
}

//@ts-ignore
Component.prototype.useMult = false; 
//组件控制开关 useMult: 可以开启自定义组件是不参与多纹理
const excludeMaterial = function (uir: UIRenderer, material: any) {
    if (!material) return;

    material['isMultTextures'] = false;
    //@ts-ignore
    if (uir.useMult || uir instanceof Sprite || uir instanceof Label) {
        if (MultBatch2D.hash == material.hash) {
            material['isMultTextures'] = true;
        }
    }
}

game.once(Game.EVENT_GAME_INITED, () => {
    if (EDITOR || JSB) return;

    loadMultTextures();
    const UIR: any = UIRenderer.prototype;
    const updateMaterial: any = UIR.updateMaterial;
    UIR.updateMaterial = function () {
        updateMaterial.call(this); //this.getSharedMaterial(0);
        excludeMaterial(this, this.customMaterial || this.material);
    }

});



game.once(Game.EVENT_ENGINE_INITED, () => {
    if (EDITOR || JSB) return;

    director.on(Director.EVENT_AFTER_DRAW, (dt) => {

        MultBatch2D.reset();
        _cacheUseCount = 0;

    });

    const RenderData = cclegacy.UI.RenderData.prototype;
    RenderData.texID = -1;
    RenderData.sprite = false;
    RenderData.texDirty = true;
    RenderData.dataDirty = 0x0;

    RenderData.updateHash = function () {
        if (this.material && this.material.isMultTextures) {
            const bid = this.chunk ? this.chunk.bufferId : 100000;
            this.dataHash = bid * 1000000000 + this.layer;
            this.hashDirty = false;
            // console.log("updateHash:" + this.chunk.bufferId );
        } else {
            const bid = this.chunk ? this.chunk.bufferId : -1;
            const hashString = `${bid}${this.layer} ${this.textureHash}`;
            this.dataHash = murmurhash2_32_gc(hashString, 666);
            this.hashDirty = false;
        }
    }

    Object.defineProperty(RenderData, "vertDirty", {
        get: function () {
            return this._vertDirty;
        },
        set: function (val: boolean) {
            this._vertDirty = val;
            if (val === true && !this.sprite) {
                this.dataDirty |= 1;
            }
            if (this._renderDrawInfo && val) {
                this._renderDrawInfo.setVertDirty(val);
            }
        }
    });

    Object.defineProperty(RenderData, "textureDirty", {
        get: function () {
            return this.texDirty;
        },
        set: function (val: boolean) {
            this.texDirty = val;
            if (val === true) {
                this.texID = -1;
            }
        }
    });


    let str = (VERSION.concat());
    str = str.replace('.', '').replace('.', '');
    if (parseInt(str) < 384) { //修复 renderManager

        const UIR: any = UIRenderer.prototype;
        const markForUpdateRenderData = UIR.markForUpdateRenderData;
        UIR.markForUpdateRenderData = function (enable = true) {
            markForUpdateRenderData.call(this, enable);
            if (enable && this.renderData) {
                if (!this.renderData.sprite)
                    this.renderData.dataDirty |= 2;
            }
        }

        const updateRenderer = UIR.updateRenderer;
        UIR.updateRenderer = function () {
            updateRenderer.call(this);
            if (this.renderData) {
                if (!this.renderData.sprite)
                    this.renderData.dataDirty &= (~2);
            }

        }

    }



    let SPRA: any = cclegacy.UI.spriteAssembler;
    if (SPRA) {
        const spriteAssembler = SPRA.getAssembler;
        SPRA.getAssembler = function (sprite: Sprite) {
            const spr = spriteAssembler.call(this, sprite);
            if (spr.changeUV == undefined) {
                spr.changeUV = function (s: any) {
                    let rd = s.renderData;
                    if (rd) {
                        rd.dataDirty = 1;
                        rd.sprite = true;
                    }
                };

                const UVs = spr.updateUVs;
                if (UVs) {
                    if (sprite.type == Sprite.Type.FILLED &&
                        sprite.fillType != Sprite.FillType.RADIAL) {
                        spr.updateUVs = function (s: any, f0: number, f1: number) {
                            UVs.call(this, s, f0, f1);
                            this.changeUV(s);
                        }
                    } else {
                        spr.updateUVs = function (s: any) {
                            UVs.call(this, s);
                            this.changeUV(s);
                        }
                    }

                }

                const verUV = spr.updateWorldVertexAndUVData;
                if (verUV) {
                    spr.updateWorldVertexAndUVData = function (s: any, c: any) {
                        verUV.call(this, s, c);
                        this.changeUV(s);
                    }
                }
            }

            return spr;
        }
    }


    cclegacy.internal.Batcher2D.prototype.cacheTextures = [];
    cclegacy.internal.Batcher2D.prototype.currMaterial = null;
    cclegacy.internal.Batcher2D.prototype.isMultTextures = false;
    Object.defineProperty(cclegacy.internal.Batcher2D.prototype, "_currMaterial", {
        get: function () {
            return this.currMaterial;
        },
        set: function (metrial: any) {
            if (this.currMaterial === metrial) return;
            this.currMaterial = getMultMaterial(metrial);
            if (MultBatch2D.enable) {
                this.isMultTextures = false;
                if (this.currMaterial && this.currMaterial.isMultTextures) {
                    this.cacheTextures = this.currMaterial.cacheTextures;
                    this.isMultTextures = true;
                }
            }
        }
    });



    const Stage_ENTER_LEVEL = 2;
    const Stage_ENTER_LEVEL_INVERTED = 6;
    //@ts-ignore
    type TextureBase = __private._cocos_asset_assets_texture_base__TextureBase;
    cclegacy.internal.Batcher2D.prototype.commitComp = function (comp: UIRenderer, renderData: BaseRenderData | null, frame: TextureBase | SpriteFrame | null, assembler: any, transform: Node | null) {


        let dataHash = 0;
        let mat: any = null;
        let bufferID = -1;

        if (renderData && renderData.chunk) {
            if (!renderData.isValid()) return;
            dataHash = renderData.dataHash;
            mat = renderData.material;
            bufferID = renderData.chunk.bufferId;

        }

        // Notice: A little hack, if it is for mask, not need update here, while control by stencilManger
        if (comp.stencilStage === Stage_ENTER_LEVEL || comp.stencilStage === Stage_ENTER_LEVEL_INVERTED) {
            this._insertMaskBatch(comp);
        } else {
            comp.stencilStage = StencilManager.sharedManager!.stage;
        }
        const depthStencilStateStage = comp.stencilStage;


        let texID = -1;
        let texture = null;
        let MB = MultBatch2D;
        let flushBatch = false;
        if (MB.enable && mat && mat.isMultTextures) {
            if (frame && frame.isValid)
                texture = frame.getGFXTexture();
            if (texture) {

                //@ts-ignore
                texID = texture.texID - MB.incID;
                flushBatch = texID < 0 && MB.count >= MAX_TEX;
                if (this.isMultTextures) mat = this._currMaterial;
            }
        }


        if (flushBatch
            || this._currHash !== dataHash || dataHash === 0 || this._currMaterial !== mat
            || this._currDepthStencilStateStage !== depthStencilStateStage) {
            // Merge all previous data to a render batch, and update buffer for next render data
            this.autoMergeBatches(this._currComponent!);
            if (renderData && !renderData._isMeshBuffer) {
                this.updateBuffer(renderData.vertexFormat, bufferID);
            }


            this._currRenderData = renderData;
            this._currHash = renderData ? renderData.dataHash : 0;
            this._currComponent = comp;
            this._currTransform = transform;
            this._currMaterial = comp.getRenderMaterial(0)!;
            this._currDepthStencilStateStage = depthStencilStateStage;
            this._currLayer = comp.node.layer;
            if (frame) {
                if (DEBUG) {
                    assert(frame.isValid, 'frame should not be invalid, it may have been released');
                }
                this._currTexture = frame.getGFXTexture();
                this._currSampler = frame.getGFXSampler();
                this._currTextureHash = frame.getHash();
                this._currSamplerHash = this._currSampler.hash;
            } else {
                this._currTexture = null;
                this._currSampler = null;
                this._currTextureHash = 0;
                this._currSamplerHash = 0;
            }
        }

        assembler.fillBuffers(comp, this);


        if (texture !== null) {

            if (texID < 0 || MB.count === 0) {

                texID = MB.count++;
                //@ts-ignore
                let id = texture.objectID;
                //@ts-ignore
                texture.texID = texID + MB.incID;

                let caches = this.cacheTextures;
                if (texID > 0 && caches[texID] !== id) {
                    caches[texID] = id;
                    //@ts-ignore
                    texture = frame.texture;
                    if(!texture) texture = frame;
                    this._currMaterial.setProperty("texture" + texID, texture);
                }
            }

            this._fillDatas(renderData, texID);
        }

    }


    cclegacy.internal.Batcher2D.prototype["_fillDatas"] = function (renderData: any, texID: number) {

        // if (!renderData) return;
        let uvX = 0;
        let vbuf = renderData.chunk.vb;
        if (renderData.dataDirty === 1) {
            for (let i = 0, length = vbuf.length; i < length; i += 9) {
                uvX = ~~(vbuf[i + 3] * 100000);
                vbuf[i + 3] = uvX * 10 + texID;
            }

        } else {
            if (renderData.texID !== texID) {
                for (let i = 0, length = vbuf.length; i < length; i += 9) {
                    uvX = ~~(vbuf[i + 3] * 0.1);
                    vbuf[i + 3] = uvX * 10 + texID;
                }
            }
        }
        renderData.dataDirty = 0;
        renderData.texID = texID;
    };



    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    if (MotionStreak) {

        //@ts-ignore
        MotionStreak.prototype.useMult = true;
        const motionStreak: any = MotionStreak.Assembler;

        const motionAssembler = motionStreak.getAssembler;
        motionStreak.getAssembler = function (comp: Label) {

            let assembler = motionAssembler.call(this, comp);
            if (!assembler.changDirty) {
                
                assembler.changDirty = function (comp: MotionStreak) {
                    if (comp.points.length >= 2) {
                        let rd:any = comp.renderData;
                        //标记刷新纹理id数据
                        rd && (rd.dataDirty = 1); 
                    }
                }

                const update = assembler.update;
                assembler.update = function (comp: MotionStreak, dt: number) {
                    update.call(this, comp, dt);
                    this.changDirty(comp);
                }
            }
            return assembler;
        };
    }


    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    if (TiledLayer) {

        const Tiled: any = TiledLayer.prototype;;
        Tiled.useMult = true;
        Tiled.dataDirty = false;

        const setUserNodeDirty = Tiled.setUserNodeDirty
        Tiled.setUserNodeDirty = function (dirty: boolean) {
            setUserNodeDirty.call(this, dirty);
            if (!dirty) {
                //标记刷新纹理id数据
                this.dataDirty = true; 
            }
        }

        Tiled._render = function (ui: any): void {
            const layer = this.node.layer;
            for (let i = 0; i < this._tiledDataArray.length; i++) {
                this._tiledDataArrayIdx = i;
                const m = this._tiledDataArray[i];
                if (m.subNodes) {
                    // 提前处理 User Nodes
                    m.subNodes.forEach((c: any) => {
                        if (c) ui.walk(c.node);
                    });
                } else {
                    const td = m as TiledRenderData;
                    if (td.texture) {

                        let isDirty = false;
                        let rd:any = td.renderData!;
                        rd.material = this.material;
                        if (rd.texture !== td.texture) {
                            rd.texture = td.texture;
                            isDirty = true;
                        }

                        if (rd.layer !== layer) {
                            rd.layer = layer;
                            isDirty = true;
                        }

                        //更新renderdata hash
                        isDirty && rd.updateHash();

                        if (this.dataDirty) rd.dataDirty = 1;
                        
                        // NOTE: 由于 commitComp 只支持单张纹理, 故分多次提交
                        ui.commitComp(this, td.renderData, td.texture, this._assembler, null);

                    }
                }
            }
            this.dataDirty = false;
            this.node._static = true;
        }
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
});

//*/
