let pg = {
    logger: {
        d: function (str) {
            cc.log(str);
            return null;
        },
        i: function (str) {
            cc.log(str);
            return null;
        },
        w: function (str) {
            cc.warn(str);
            return null;
        }
    },
    view: {
        //---------------------节点管理------------------------------
        //创建节点
        createNode() {
            let node = new cc.Node();
            return node;
        },
        //添加节点
        addChild(item, child, zIndex) {
            if (!child) return console.log("addChild error ->请传入子节点");
            if (!item) return console.log("addChild error ->请传入父节点");
            let node = item.node ? item.node : item;
            if (!node) return console.log("addChild error ->请传入父节点");
            if (child.parent)
                return pg.logger.w("此节点已经有父节点->" + child.name);
            if (zIndex >= 0) {
                node.addChild(child, zIndex)
            } else {
                node.addChild(child);
            }
            return true;
        },
        //删除子节点
        removeChild(item, child) {
            if (!item) return pg.logger.w("节点remove失败,传入了错误的item");
            let node = item.node ? item.node : item;
            if (child.parent && child.parent == node) {
                node.removeChild(child);
                child.destroy();
            }
            return true;
        },
        removeSelf(item) {
            if (!item) return pg.logger.w("节点移除失败,传入了错误的item");
            let node = item.node ? item.node : item;
            node.removeFromParent();
            node.destroy();
        },
        //删除所有子节点
        removChildren(item) {
            if (!item) return pg.logger.w("节点remove失败,传入了错误的item");
            let node = item.node ? item.node : item;
            if (!node.parent) return pg.logger.w("节点remove失败,传入了错误的item");
            node.removeAllChildren();
            return true;
        },
        //查找节点
        find(item, childPath): cc.Node {
            if (typeof item == "string") {
                childPath = item;
                item = null;
            }
            if (!childPath || childPath == '' || typeof childPath != 'string') return pg.logger.w("findChildByPath error->" + "请传入路径");
            let child = null;
            if (item) {
                let node = item.node ? item.node : item;
                if (!node.children || node.children.length == 0) return pg.logger.w("findChild error->" + "找不到此节点，请检查层级路径:" + childPath);
                child = cc.find(childPath, node);
            } else {
                child = cc.find(childPath);
            }
            if (!child) return pg.logger.w("findChildByPath error->" + "找不到此节点，请检查层级路径:" + childPath);
            return child;
        },
        //--------------------触控事件--------------------------------
        //添加监听
        touchOn(item, callback, target) {
            if (!item) return pg.logger.w("添加按钮响应失败,传入了错误的item");
            if (!callback || !target) return pg.logger.w("添加按钮响应失败,传入了空回调");
            let node = item.node ? item.node : item;
            node.off(cc.Node.EventType.TOUCH_END, callback, target);
            node.on(cc.Node.EventType.TOUCH_END, callback, target);
            return true;
        },
        //移除监听
        touchOff(item, callback, target) {
            if (!item) return pg.logger.w("移除按钮响应失败,传入了错误的item");
            if (!callback || !target) return pg.logger.w("移除按钮响应失败,传入了空回调");
            let node = item.node ? item.node : item;
            if (!node || !node.parent) return pg.logger.w("节点已移除");
            node.off(cc.Node.EventType.TOUCH_END, callback, target);
            return true;
        },
        //是否允许点击
        touchEnable(item, isEnable) {
            if (!item) return pg.logger.w("设置按钮响应失败,传入了错误的item");
            let node = item.node ? item.node : item;
            if (!node) return pg.logger.w("设置按钮响应失败,传入了错误的item");
            let btn = node.getComponent(cc.Button);
            if (!btn) return pg.logger.w("当前节点没有添加button->" + node.name);
            btn.interactable = isEnable;
            return true;
        },
        //-------------------渲染相关---------------------------------
        //显示隐藏
        visible(item, isVisible) {
            if (!item) return pg.logger.w("节点显示失败,传入了错误的item");
            let node = item.node ? item.node : item;
            if (!node || !node.parent) return pg.logger.w("节点已移除");
            node.active = isVisible;
            return true;
        },
        //更换图片
        setImg(item, res) {
            return new Promise((resolve, reject) => {
                if (!item) return pg.logger.w("图片更换失败,传入了错误的item");
                if (!res) return pg.logger.w("图片更换失败,传入了错误的res");
                pg.load.loadImg(res).then((spriteFrame: cc.SpriteFrame) => {
                    if (!cc.isValid(item)) return pg.logger.i("节点已销毁");
                    let node = item.node ? item.node : item;
                    if (!cc.isValid(node)) return pg.logger.i("节点已销毁");
                    let component = node.getComponent(cc.Sprite);
                    let { width, height } = spriteFrame.getRect();
                    component.spriteFrame = spriteFrame;
                    resolve({ width, height });
                })
            })
        },
        setNetImg(item, res, cache = true) {
            return new Promise((resolve, reject) => {
                if (!item) return pg.logger.w("图片更换失败,传入了错误的item");
                let node = item.node ? item.node : item;
                if (!res) {
                    node.active = false;
                    return pg.logger.w("图片更换失败,传入了错误的res");
                }
                if (!node) return pg.logger.w("图片更换失败,传入了错误的item");
                if (cache && node.net_url == res) return;
                let w = node.width;
                let h = node.height;
                node.active = false;//
                pg.load.loadNetImg(res).then((texture: cc.Texture2D) => {
                    if (!cc.isValid(node)) return pg.logger.i("节点已销毁");
                    let nw = node.width = texture.width;
                    let nh = node.height = texture.height;
                    
                    let spriteFrame = new cc.SpriteFrame(texture);
                    node.net_url = res;
                    const cover = node.getChildByName('cover');
                    if (cover) {
                        const {width, height} = spriteFrame.getOriginalSize()
                        cover.getComponent(cc.Sprite).spriteFrame = spriteFrame;
                        cover.width = width;
                        cover.height = height;
                        const sx = node.width / width;
                        const sy = node.height / height;
                        const s = Math.min(sx, sy);
                        cover.scale = Math.round(s * 1000) / 1000;
                    } else {
                        let component = node.getComponent(cc.Sprite);
                        component.spriteFrame = spriteFrame;
                        node.width = w;
                        node.height = h;
                    }

                    // setTimeout(() => {
                    if (!cc.isValid(node)) return pg.logger.i("节点已销毁");
                    if (!node) return pg.logger.w("节点已销毁");
                    
                    node.active = true;
                    // }, 30);
                    resolve({ w: nw, h: nh });
                })
            })
        },
        switchMaterial(item, id0 = 0, id1 = 1) {
            let material0 = item.getMaterial(id0);
            let material1 = item.getMaterial(id1);
            item.setMaterial(id0, material1);
            item.setMaterial(id1, material0);
        },
        //更改文字
        setString(item, text, count = 0) {

            if (!item) return pg.logger.w("节点text失败,传入了错误的item");
            if (count > 0) {
                let parse_str = function (str, count) {
                    if (!str) return "";
                    var segmants = str.split('+');
                    str = segmants.join('');
                    var len = 0;
                    var idx = 0;
                    for (var i = 0; i < str.length; i++) {
                        var p = /[^x00-xff]/g;
                        var a = str.charAt(i);
                        if (p.test(a)) {
                            len += 2;
                            idx++;
                        }
                        else {
                            len += 1;
                            idx++;
                        }
                        if (len >= count * 2)
                            break;
                    }
                    return str.substr(0, idx);
                }
                text = parse_str(text, count);
            }
            let node = item.node ? item.node : item;
            if (!node) return;
            let component = node.getComponent(cc.Label);//组件功能 非node的功能
            component.string = text;
            return true;
        },
        //更变颜色
        setColor(item, color, outlineWidth = -1) {
            if (!item) return pg.logger.w("setColor warn->传入了错误的item");
            let RGB = this.colorRgb(color);
            if (!RGB || RGB.length == 0) return pg.logger.w("color ->传入了错误的color");
            item.color = new cc.Color(RGB[0], RGB[1], RGB[2]);
            if (outlineWidth < 0) return;
            let LabelOutline = item.getComponent(cc.LabelOutline);
            if (!LabelOutline) return pg.logger.w("LabelOutline warn->未添加描边");
            LabelOutline.width = outlineWidth;
        },
        colorRgb(color) {
            var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
            var sColor = color;
            if (sColor && reg.test(sColor)) {
                if (sColor.length === 4) {
                    var sColorNew = "#";
                    for (var i = 1; i < 4; i += 1) {
                        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
                    }
                    sColor = sColorNew;
                }
                //处理六位的颜色值
                var sColorChange = [];
                for (var i = 1; i < 7; i += 2) {
                    sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
                }
                return sColorChange;
            } else {
                return sColor;
            }
        },
        //-------------------动画播放--------------------------------
        playSpineAnimation(item, aniName, loop) {
            if (!item || !cc.isValid(item)) return pg.logger.w("动画播放失败,传入了错误的item");
            if (!aniName) return pg.logger.w("动画播放失败,传入了错误的aniName");
            let node = item.node ? item.node : item;
            if (!cc.isValid(node)) return pg.logger.w("节点已销毁");
            let skl = node.getComponent(sp.Skeleton);
            skl.setAnimation(0, aniName, loop);
            return skl;
        },
        playDBAnimation(item: any, aniName: string, loop?: number) {
            if (!item || !cc.isValid(item)) return pg.logger.w("动画播放失败,传入了错误的item");
            if (!aniName) return pg.logger.w("动画播放失败,传入了错误的aniName");
            let node = item.node ? item.node : item;
            if (!cc.isValid(node)) return pg.logger.w("节点已销毁");
            let skl: dragonBones.ArmatureDisplay = node.getComponent(dragonBones.ArmatureDisplay);
            skl.playAnimation(aniName, loop);
            return skl;
        },
    },
    load: {
        //资源加载
        // loadBundle: function (bundleName) {
        //     return new Promise((resolve, reject) => {
        //         // let hallBundle = cc.assetManager.getBundle(`hall`);
        //         // hallBundle.releaseAll();
        //         // cc.assetManager.removeBundle(hallBundle);
        //         let bundle = cc.assetManager.getBundle(bundleName);
        //         if (bundle) return resolve('');
        //         cc.assetManager.loadBundle(bundleName, (err, bundle) => {
        //             if (err) return cc.error(err);
        //             resolve(bundle);
        //         });
        //     });
        // },
        loadRes: function (res, type, bundleName) {
            //此处需要二次封装，新的存在assetbundle
            return new Promise((resolve, reject) => {
                cc.loader.loadRes(res, type, (err, data) => {
                    if (err && !data) return resolve(pg.logger.d('loading loadRes error-> ' + res));
                    resolve(data);
                });
            })
        },
        loadImg: function (url) {
            return new Promise((resolve, reject) => {
                this.loadRes(url, cc.SpriteFrame).then((data) => {
                    if (!data || data.length == 0) return;
                    resolve(data);
                })
            })
        },
        loadPrefab: function (path = "") {
            return new Promise((resolve, reject) => {
                let url = "/prefabs/" + path;
                this.loadRes(url, cc.Prefab).then((data) => {
                    if (!data || data.length == 0) return reject();
                    return resolve(cc.instantiate(data));
                })
            })
        },
        loadNetImg: function (url) {
            return new Promise((resolve, reject) => {
                cc.loader.load({ url }, (err, texture) => {
                    if (err && !texture) return resolve(pg.logger.w('loading loadRes warn-> ' + texture));
                    resolve(texture);
                });
            })
        },
    },
    localStorage: {
        //本地存储
        setItem: function (key, val) {
            cc.sys.localStorage.setItem(key, val);
        },
        getItem: function (key, defVal) {
            return cc.sys.localStorage.getItem(key) || defVal;
        }
    },
    http: {
        //http访问
        send: function (type, url, data) {
            return new Promise((resolve, reject) => {
                // return setTimeout(() => {
                //     return resolve({ status: 200 });
                // }, 60);
                let xhr = cc.loader.getXMLHttpRequest();
                xhr.timeout = 30000;
                xhr.responseType = "text";
                xhr.open(type, url, true);
                xhr.setRequestHeader("token", globalThis.____GAME_ENV____.token);
                xhr.setRequestHeader("Client-Type", 'student');
                xhr.setRequestHeader("Content-Type", "application/json");
                xhr.onreadystatechange = () => {
                    if (xhr.readyState !== 4) return;
                    if (xhr.status >= 200 && xhr.status < 300) {
                        try {
                            let resp = xhr.responseText;
                            // pg.logger.d("resp->" + JSON.stringify(resp));
                            if (typeof resp === 'string') {
                                resp = JSON.parse(resp);
                                // @ts-ignore
                                if (resp.code !=200) {
                                    // @ts-ignore
                                    reject(resp.message)
                                    return
                                }
                                // @ts-ignore
                                resp = resp.data;
                            }
                            resolve(resp);
                        } catch (e) {
                            reject(e)
                        }
                    } else {
                        pg.logger.w("onerror->" + url + ';resp = '+ xhr.responseText);
                        reject(xhr.responseText)
                    }
                };
                xhr.onerror = (e) => {
                    pg.logger.w("onerror->" + url);
                    reject(e);
                };
                xhr.ontimeout = (e) => {
                    pg.logger.w("ontimeout->" + url);
                    reject(e);
                };
                if (data) {
                    xhr.send(JSON.stringify(data));
                } else {
                    xhr.send();
                }
                
            })

        }
    },
};
export default pg;