import Gamecfg from "../common/gameCfg"
import { KindItem } from "../common/Xys"
import { IconUrl } from "../data/const/ResConst"
import { ItemKind } from "../data/const/TypeConst"
import GameDataCenter from "../data/GameDataCenter"
import AssetsBundleMgr from "./AssetsBundleMgr"

/**
 * 动态加载资源
 */
export default class Load {
    static loadPrefabByBundle(bundle: string, prefab: string, callback?: Function) {
        cc.assetManager.loadBundle(bundle, cc.Prefab, (err, bundle: cc.AssetManager.Bundle) => {
            if (err) {
                console.warn(err)
                return
            }
            bundle.load(prefab, cc.Prefab, function (err, prefab) {
                if (callback) {
                    callback(prefab)
                }
            })
        })
    }
    static resList: { [bundleName: string]: { [key: string]: cc.SpriteFrame } } = {}
    // 根据详细地址加载图片资源
    static loadTexture(node: cc.Node, url: string, callback: Function = (success: boolean) => { }, needDelFirst: boolean = true) {
        if (node.getComponent(cc.Sprite) == null) {
            node.addComponent(cc.Sprite)
        }
        let bundleName = url.split("/")[0]
        if (this.resList[bundleName] != null && this.resList[bundleName][url] != null && this.resList[bundleName][url].isValid && this.resList[bundleName][url].loaded) {
            if (this.resList[bundleName][url].getTexture().isValid && this.resList[bundleName][url].getTexture().loaded) {
                node.getComponent(cc.Sprite).spriteFrame = this.resList[bundleName][url]
                callback(true)
                return
            }
        }
        if (needDelFirst) {
            node.getComponent(cc.Sprite).spriteFrame = null
        }
        if (node['imageTag'] == null) {
            node['imageTag'] = 1
        } else {
            if (node['imageTag'] > 100) {
                node['imageTag'] = 1
            } else {
                node['imageTag'] += 1
            }
        }
        let _tempImageTag = node['imageTag']
        if (!bundleName || bundleName == "") return;
        AssetsBundleMgr.loadBundle(bundleName, (error, bundle: cc.AssetManager.Bundle) => {
            if (error) {
                console.error(`bundle加载失败: ${bundleName}`);
                if (needDelFirst == false) {
                    node.getComponent(cc.Sprite).spriteFrame = null
                }
                return;
            }
            let realUrl = url.slice(url.indexOf("/") + 1)
            bundle.load(realUrl, cc.SpriteFrame, (err, asset: cc.SpriteFrame) => {
                if (!node.isValid) { return }
                if (err) {
                    console.warn("加载资源失败:", url)
                    if (needDelFirst == false) {
                        node.getComponent(cc.Sprite).spriteFrame = null
                    }
                    callback(false)
                    return
                }
                if (_tempImageTag != node['imageTag']) {
                    return
                }
                if (this.resList[bundleName] == null) {
                    this.resList[bundleName] = {}
                }
                this.resList[bundleName][url] = asset
                node.getComponent(cc.Sprite).spriteFrame = asset
                callback(true)
            })
        });
    }
    // 根据道具配置id加载道具图标
    static loadItemIcon(node: cc.Node, kindItem: KindItem, callback: Function = (success: boolean) => { }) {
        if (kindItem?.[0] == ItemKind.money) {
            this.loadTexture(node, IconUrl.item + GameDataCenter.item.getItemCfgBase(kindItem)?.icon, callback)
        } else {
            this.loadTexture(node, IconUrl.item + GameDataCenter.item.getItemCfgBase(kindItem)?.icon, callback)
            // console.error("loadItemIcon:未处理的道具类型:", kindItem[0])
        }
    }

    static spineList: { [bundleName: string]: { [key: string]: sp.SkeletonData } } = {}
    // 根据详细地址加载Spine资源
    static loadSpine(node: cc.Node, url: string, callback: Function = (success: boolean) => { }, needDelFirst: boolean = true) {
        if (node.getComponent(sp.Skeleton) == null) {
            node.addComponent(sp.Skeleton)
        }
        let bundleName = url.split("/")[0]
        if (this.spineList[bundleName] != null && this.spineList[bundleName][url] != null && this.spineList[bundleName][url].isValid && this.spineList[bundleName][url].loaded) {
            // if (this.spineList[bundleName][url].getTexture().isValid && this.spineList[bundleName][url].getTexture().loaded) {
                node.getComponent(sp.Skeleton).skeletonData = this.spineList[bundleName][url]
                callback(true)
                return
            // }
        }
        if (needDelFirst) {
            node.getComponent(sp.Skeleton).skeletonData = null
        }
        if (node['imageTag'] == null) {
            node['imageTag'] = 1
        } else {
            if (node['imageTag'] > 100) {
                node['imageTag'] = 1
            } else {
                node['imageTag'] += 1
            }
        }
        let _tempImageTag = node['imageTag']
        AssetsBundleMgr.loadBundle(bundleName, (error, bundle: cc.AssetManager.Bundle) => {
            if (error) {
                console.error(`bundle加载失败: ${bundleName}`);
                if (needDelFirst == false) {
                    node.getComponent(cc.Sprite).spriteFrame = null
                }
                return;
            }
            let realUrl = url.slice(url.indexOf("/") + 1)
            bundle.load(realUrl, sp.SkeletonData, (err, asset: sp.SkeletonData) => {
                if (!node.isValid) { return }
                if (err) {
                    console.warn("加载资源失败:", url)
                    if (needDelFirst == false) {
                        node.getComponent(sp.Skeleton).skeletonData = null
                    }
                    callback(false)
                    return
                }
                if (_tempImageTag != node['imageTag']) {
                    return
                }
                if (this.spineList[bundleName] == null) {
                    this.spineList[bundleName] = {}
                }
                this.spineList[bundleName][url] = asset
                node.getComponent(sp.Skeleton).skeletonData = asset
                callback(true)
            })
        });
    }

    // // 根据详细地址获取图片资源
    // static getTexture(url: string, callback: Function = (success: boolean, asset: cc.SpriteFrame) => { }) {
    //     let bundleName = url.split("/")[0]
    //     if (this.resList[bundleName] != null && this.resList[bundleName][url] != null && this.resList[bundleName][url].isValid && this.resList[bundleName][url].loaded) {
    //         if (this.resList[bundleName][url].getTexture().isValid && this.resList[bundleName][url].getTexture().loaded) {
    //             callback(true, this.resList[bundleName][url])
    //         }
    //     }
    //     AssetsBundleMgr.loadBundle(bundleName, (error, bundle: cc.AssetManager.Bundle) => {
    //         if (error) {
    //             console.error(`bundle加载失败: ${bundleName}`);
    //             return;
    //         }
    //         let realUrl = url.slice(url.indexOf("/") + 1)
    //         bundle.load(realUrl, cc.SpriteFrame, (err, asset: cc.SpriteFrame) => {
    //             if (err) {
    //                 console.warn("加载资源失败:", url)
    //                 callback(false)
    //                 return null
    //             }
    //             if (this.resList[bundleName] == null) {
    //                 this.resList[bundleName] = {}
    //             }
    //             this.resList[bundleName][url] = asset
    //             callback(true, this.resList[bundleName][url])
    //         })
    //     });
    // }

    static clearByBundle(bundleName: string) {
        if (this.resList[bundleName] != null) {
            this.resList[bundleName] = {}
        }
    }
    static clear() {
        this.resList = {}
    }
}